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/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/validation/FlowValidationFactory.java b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/validation/FlowValidationFactory.java index b6f7b527..5a9ff1c9 100644 --- a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/validation/FlowValidationFactory.java +++ b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/validation/FlowValidationFactory.java @@ -1,50 +1,54 @@ /******************************************************************************* * Copyright (c) 2010 xored software, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * xored software, Inc. - initial API and Implementation (Alex Panchenko) *******************************************************************************/ package org.eclipse.dltk.internal.javascript.validation; import java.util.HashSet; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.dltk.core.IScriptProject; import org.eclipse.dltk.core.builder.IBuildContext; import org.eclipse.dltk.core.builder.IBuildParticipant; import org.eclipse.dltk.core.builder.IBuildParticipantFactory; import org.eclipse.dltk.javascript.ast.FunctionStatement; public class FlowValidationFactory implements IBuildParticipantFactory { public IBuildParticipant createBuildParticipant(IScriptProject project) throws CoreException { return new FlowValidation() { - final Set<FunctionStatement> inconsistentReturns = new HashSet<FunctionStatement>(); + private Set<FunctionStatement> inconsistentReturns; @Override public void build(IBuildContext context) throws CoreException { super.build(context); - if (!inconsistentReturns.isEmpty()) { + if (inconsistentReturns != null) { context.set( JavaScriptValidations.ATTR_INCONSISTENT_RETURNS, inconsistentReturns); + inconsistentReturns = null; } } @Override protected void reportInconsistentReturn(FunctionStatement node) { + if (inconsistentReturns == null) { + inconsistentReturns = new HashSet<FunctionStatement>(); + } inconsistentReturns.add(node); } }; } }
false
true
public IBuildParticipant createBuildParticipant(IScriptProject project) throws CoreException { return new FlowValidation() { final Set<FunctionStatement> inconsistentReturns = new HashSet<FunctionStatement>(); @Override public void build(IBuildContext context) throws CoreException { super.build(context); if (!inconsistentReturns.isEmpty()) { context.set( JavaScriptValidations.ATTR_INCONSISTENT_RETURNS, inconsistentReturns); } } @Override protected void reportInconsistentReturn(FunctionStatement node) { inconsistentReturns.add(node); } }; }
public IBuildParticipant createBuildParticipant(IScriptProject project) throws CoreException { return new FlowValidation() { private Set<FunctionStatement> inconsistentReturns; @Override public void build(IBuildContext context) throws CoreException { super.build(context); if (inconsistentReturns != null) { context.set( JavaScriptValidations.ATTR_INCONSISTENT_RETURNS, inconsistentReturns); inconsistentReturns = null; } } @Override protected void reportInconsistentReturn(FunctionStatement node) { if (inconsistentReturns == null) { inconsistentReturns = new HashSet<FunctionStatement>(); } inconsistentReturns.add(node); } }; }
diff --git a/firefox/src/java/org/openqa/selenium/firefox/FirefoxProfile.java b/firefox/src/java/org/openqa/selenium/firefox/FirefoxProfile.java index 8a5c9119b..2701c1b26 100644 --- a/firefox/src/java/org/openqa/selenium/firefox/FirefoxProfile.java +++ b/firefox/src/java/org/openqa/selenium/firefox/FirefoxProfile.java @@ -1,600 +1,601 @@ /* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.firefox; import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.Proxy.ProxyType; import org.openqa.selenium.internal.Cleanly; import org.openqa.selenium.internal.FileHandler; import org.openqa.selenium.internal.TemporaryFilesystem; import org.openqa.selenium.internal.Zip; import org.w3c.dom.Document; import org.w3c.dom.Node; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.text.MessageFormat; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.xml.XMLConstants; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; public class FirefoxProfile { private static final String EXTENSION_NAME = "[email protected]"; private static final String EM_NAMESPACE_URI = "http://www.mozilla.org/2004/em-rdf#"; private File profileDir; private File extensionsDir; private File userPrefs; private Preferences additionalPrefs = new Preferences(); private int port; private boolean enableNativeEvents; private boolean loadNoFocusLib; private boolean acceptUntrustedCerts; private boolean untrustedCertIssuer; /** * Constructs a firefox profile from an existing, physical profile directory. * Not a good idea, please don't. * * <p>Users who need this functionality should be using a named profile. * * @param profileDir */ protected FirefoxProfile(File profileDir) { this.profileDir = profileDir; this.extensionsDir = new File(profileDir, "extensions"); this.userPrefs = new File(profileDir, "user.js"); port = FirefoxDriver.DEFAULT_PORT; enableNativeEvents = FirefoxDriver.DEFAULT_ENABLE_NATIVE_EVENTS; loadNoFocusLib = false; acceptUntrustedCerts = FirefoxDriver.ACCEPT_UNTRUSTED_CERTIFICATES; untrustedCertIssuer = FirefoxDriver.ASSUME_UNTRUSTED_ISSUER; if (!profileDir.exists()) { throw new WebDriverException(MessageFormat.format("Profile directory does not exist: {0}", profileDir.getAbsolutePath())); } } public FirefoxProfile() { this(TemporaryFilesystem.createTempDir("webdriver", "profile")); } protected void addWebDriverExtensionIfNeeded(boolean forceCreation) { File extensionLocation = new File(extensionsDir, EXTENSION_NAME); if (!forceCreation && extensionLocation.exists()) { return; } try { addExtension(FirefoxProfile.class, "webdriver.xpi"); } catch (IOException e) { if (!Boolean.getBoolean("webdriver.development")) { throw new WebDriverException("Failed to install webdriver extension", e); } } deleteExtensionsCacheIfItExists(); } public File addExtension(Class<?> loadResourcesUsing, String loadFrom) throws IOException { // Is loadFrom a file? File file = new File(loadFrom); if (file.exists()) { addExtension(file); return file; } // Try and load it from the classpath InputStream resource = loadResourcesUsing.getResourceAsStream(loadFrom); if (resource == null && !loadFrom.startsWith("/")) { resource = loadResourcesUsing.getResourceAsStream("/" + loadFrom); } if (resource == null) { resource = FirefoxProfile.class.getResourceAsStream(loadFrom); } if (resource == null && !loadFrom.startsWith("/")) { resource = FirefoxProfile.class.getResourceAsStream("/" + loadFrom); } if (resource == null) { throw new FileNotFoundException("Cannot locate resource with name: " + loadFrom); } File root; if (FileHandler.isZipped(loadFrom)) { root = FileHandler.unzip(resource); } else { throw new WebDriverException("Will only install zipped extensions for now"); } addExtension(root); return root; } /** * Attempt to add an extension to install into this instance. * * @param extensionToInstall * @throws IOException */ public void addExtension(File extensionToInstall) throws IOException { if (!extensionToInstall.isDirectory() && !FileHandler.isZipped(extensionToInstall.getAbsolutePath())) { throw new IOException("Can only install from a zip file, an XPI or a directory"); } File root = obtainRootDirectory(extensionToInstall); String id = readIdFromInstallRdf(root); File extensionDirectory = new File(extensionsDir, id); if (extensionDirectory.exists() && !FileHandler.delete(extensionDirectory)) { throw new IOException("Unable to delete existing extension directory: " + extensionDirectory); } FileHandler.createDir(extensionDirectory); FileHandler.makeWritable(extensionDirectory); FileHandler.copy(root, extensionDirectory); } private String readIdFromInstallRdf(File root) { try { File installRdf = new File(root, "install.rdf"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(installRdf); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new NamespaceContext() { public String getNamespaceURI(String prefix) { if ("em".equals(prefix)) { return EM_NAMESPACE_URI; } else if ("RDF".equals(prefix)) { return "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; } return XMLConstants.NULL_NS_URI; } public String getPrefix(String uri) { throw new UnsupportedOperationException("getPrefix"); } public Iterator<?> getPrefixes(String uri) { throw new UnsupportedOperationException("getPrefixes"); } }); Node idNode = (Node) xpath.compile("//em:id").evaluate(doc, XPathConstants.NODE); String id = null; if (idNode == null) { Node descriptionNode = (Node) xpath.compile("//RDF:Description").evaluate(doc, XPathConstants.NODE); Node idAttr = descriptionNode.getAttributes().getNamedItemNS(EM_NAMESPACE_URI, "id"); if (idAttr == null) { throw new WebDriverException( "Cannot locate node containing extension id: " + installRdf.getAbsolutePath()); } id = idAttr.getNodeValue(); } else { id = idNode.getTextContent(); } if (id == null || "".equals(id.trim())) { throw new FileNotFoundException("Cannot install extension with ID: " + id); } return id; } catch (Exception e) { throw new WebDriverException(e); } } private File obtainRootDirectory(File extensionToInstall) throws IOException { File root = extensionToInstall; if (!extensionToInstall.isDirectory()) { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(extensionToInstall)); try { root = FileHandler.unzip(bis); } finally { bis.close(); } } return root; } protected void installDevelopmentExtension() throws IOException { if (!FileHandler.createDir(extensionsDir)) throw new IOException("Cannot create extensions directory: " + extensionsDir.getAbsolutePath()); String home = findFirefoxExtensionRootInSourceCode(); File writeTo = new File(extensionsDir, EXTENSION_NAME); if (writeTo.exists() && !FileHandler.delete(writeTo)) { throw new IOException("Cannot delete existing extensions directory: " + extensionsDir.getAbsolutePath()); } FileWriter writer = null; try { writer = new FileWriter(writeTo); writer.write(home); } catch (IOException e) { throw new WebDriverException(e); } finally { Cleanly.close(writer); } } private String findFirefoxExtensionRootInSourceCode() { String[] possiblePaths = { "firefox/src/extension", "../firefox/src/extension", "../../firefox/src/extension", }; File current; for (String potential : possiblePaths) { current = new File(potential); if (current.exists()) { return current.getAbsolutePath(); } } throw new WebDriverException("Unable to locate firefox driver extension in developer source"); } public File getProfileDir() { return profileDir; } //Assumes that we only really care about the preferences, not the comments private Map<String, String> readExistingPrefs(File userPrefs) { Map<String, String> prefs = new HashMap<String, String>(); BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(userPrefs)); String line = reader.readLine(); while (line != null) { if (!line.startsWith("user_pref(\"")) { line = reader.readLine(); continue; } line = line.substring("user_pref(\"".length()); line = line.substring(0, line.length() - ");".length()); String[] parts = line.split(","); parts[0] = parts[0].substring(0, parts[0].length() - 1); prefs.put(parts[0].trim(), parts[1].trim()); line = reader.readLine(); } } catch (IOException e) { throw new WebDriverException(e); } finally { Cleanly.close(reader); } return prefs; } public File getExtensionsDir() { return extensionsDir; } /** * Set a preference for this particular profile. The value will be properly quoted * before use. Note that if a value looks as if it is a quoted string (that is, starts * with a quote character and ends with one too) an IllegalArgumentException is thrown: * Firefox fails to start properly when some values are set to this. * * @param key The key * @param value The new value. */ public void setPreference(String key, String value) { additionalPrefs.setPreference(key, value); } /** * Set a preference for this particular profile. * * @param key The key * @param value The new value. */ public void setPreference(String key, boolean value) { additionalPrefs.setPreference(key, value); } /** * Set a preference for this particular profile. * * @param key The key * @param value The new value. */ public void setPreference(String key, int value) { additionalPrefs.setPreference(key, value); } /** * Set proxy preferences for this profile. * * @param proxy The proxy preferences. * @return The profile, for further settings. */ public FirefoxProfile setProxyPreferences(Proxy proxy) { if (proxy.getProxyType() == ProxyType.UNSPECIFIED) { return this; } setPreference("network.proxy.type", proxy.getProxyType().ordinal()); switch (proxy.getProxyType()) { case MANUAL:// By default, assume we're proxying the lot setPreference("network.proxy.no_proxies_on", ""); setManualProxyPreference("ftp", proxy.getFtpProxy()); setManualProxyPreference("http", proxy.getHttpProxy()); setManualProxyPreference("ssl", proxy.getSslProxy()); if (proxy.getNoProxy() != null) { setPreference("network.proxy.no_proxies_on", proxy.getNoProxy()); } break; case PAC: setPreference("network.proxy.autoconfig_url", proxy.getProxyAutoconfigUrl()); break; } return this; } private void setManualProxyPreference(String key, String settingString) { if (settingString == null) { return; } String[] hostPort = settingString.split(":"); setPreference("network.proxy." + key, hostPort[0]); if (hostPort.length > 1) { setPreference("network.proxy." + key + "_port", Integer.parseInt(hostPort[1])); } } protected Preferences getAdditionalPreferences() { return additionalPrefs; } public void updateUserPrefs() { if (port == 0) { throw new WebDriverException("You must set the port to listen on before updating user.js"); } Map<String, String> prefs = new HashMap<String, String>(); // Allow users to override these settings prefs.put("browser.startup.homepage", "\"about:blank\""); // The user must be able to override this setting (to 1) in order to // to change homepage on Firefox 3.0 prefs.put("browser.startup.page", "0"); if (userPrefs.exists()) { prefs = readExistingPrefs(userPrefs); if (!userPrefs.delete()) throw new WebDriverException("Cannot delete existing user preferences"); } additionalPrefs.addTo(prefs); // Normal settings to facilitate testing prefs.put("app.update.auto", "false"); prefs.put("app.update.enabled", "false"); prefs.put("browser.download.manager.showWhenStarting", "false"); prefs.put("browser.EULA.override", "true"); prefs.put("browser.EULA.3.accepted", "true"); prefs.put("browser.link.open_external", "2"); prefs.put("browser.link.open_newwindow", "2"); prefs.put("browser.safebrowsing.enabled", "false"); prefs.put("browser.search.update", "false"); prefs.put("browser.sessionstore.resume_from_crash", "false"); prefs.put("browser.shell.checkDefaultBrowser", "false"); prefs.put("browser.tabs.warnOnClose", "false"); prefs.put("browser.tabs.warnOnOpen", "false"); prefs.put("dom.disable_open_during_load", "false"); prefs.put("extensions.update.enabled", "false"); prefs.put("extensions.update.notifyUser", "false"); + prefs.put("network.manage-offline-status", "false"); prefs.put("security.fileuri.origin_policy", "3"); prefs.put("security.fileuri.strict_origin_policy", "false"); prefs.put("security.warn_entering_secure", "false"); prefs.put("security.warn_submit_insecure", "false"); prefs.put("security.warn_entering_secure.show_once", "false"); prefs.put("security.warn_entering_weak", "false"); prefs.put("security.warn_entering_weak.show_once", "false"); prefs.put("security.warn_leaving_secure", "false"); prefs.put("security.warn_leaving_secure.show_once", "false"); prefs.put("security.warn_submit_insecure", "false"); prefs.put("security.warn_viewing_mixed", "false"); prefs.put("security.warn_viewing_mixed.show_once", "false"); prefs.put("signon.rememberSignons", "false"); // Which port should we listen on? prefs.put("webdriver_firefox_port", Integer.toString(port)); // Should we use native events? prefs.put("webdriver_enable_native_events", Boolean.toString(enableNativeEvents)); // Should we accept untrusted certificates or not? prefs.put("webdriver_accept_untrusted_certs", Boolean.toString(acceptUntrustedCerts)); prefs.put("webdriver_assume_untrusted_issuer", Boolean.toString(untrustedCertIssuer)); // Settings to facilitate debugging the driver prefs.put("javascript.options.showInConsole", "true"); // Logs errors in chrome files to the Error Console. prefs.put("browser.dom.window.dump.enabled", "true"); // Enables the use of the dump() statement // If the user sets the home page, we should also start up there prefs.put("startup.homepage_welcome_url", prefs.get("browser.startup.homepage")); if (!"about:blank".equals(prefs.get("browser.startup.homepage"))) { prefs.put("browser.startup.page", "1"); } writeNewPrefs(prefs); } public void deleteExtensionsCacheIfItExists() { File cacheFile = new File(extensionsDir, "../extensions.cache"); if (cacheFile.exists()) cacheFile.delete(); } protected void writeNewPrefs(Map<String, String> prefs) { Writer writer = null; try { writer = new FileWriter(userPrefs); for (Map.Entry<String, String> entry : prefs.entrySet()) { writer.append( String.format("user_pref(\"%s\", %s);\n", entry.getKey(), entry.getValue()) ); } } catch (IOException e) { throw new WebDriverException(e); } finally { Cleanly.close(writer); } } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public boolean enableNativeEvents() { return enableNativeEvents; } public void setEnableNativeEvents(boolean enableNativeEvents) { this.enableNativeEvents = enableNativeEvents; } /** * Returns whether the no focus library should be loaded for Firefox * profiles launched on Linux, even if native events are disabled. * * @return Whether the no focus library should always be loaded for Firefox * on Linux. */ public boolean alwaysLoadNoFocusLib() { return loadNoFocusLib; } /** * Sets whether the no focus library should always be loaded on Linux. * * @param loadNoFocusLib Whether to always load the no focus library. */ public void setAlwaysLoadNoFocusLib(boolean loadNoFocusLib) { this.loadNoFocusLib = loadNoFocusLib; } /** * Sets whether Firefox should accept SSL certificates which have expired, * signed by an unknown authority or are generally untrusted. * This is set to true by defaul.t * * @param acceptUntrustedSsl Whether untrusted SSL certificates should be * accepted. */ public void setAcceptUntrustedCertificates(boolean acceptUntrustedSsl) { this.acceptUntrustedCerts = acceptUntrustedSsl; } /** * By default, when accepting untrusted SSL certificates, assume that * these certificates will come from an untrusted issuer or will be self * signed. * Due to limitation within Firefox, it is easy to find out if the * certificate has expired or does not match the host it was served for, * but hard to find out if the issuer of the certificate is untrusted. * * By default, it is assumed that the certificates were not be issued from * a trusted CA. * * If you are receive an "untrusted site" prompt on Firefox when using a * certificate that was issued by valid issuer, but has expired or * is being served served for a different host (e.g. production certificate * served in a testing environment) set this to false. * * @param untrustedIssuer whether to assume untrusted issuer or not. */ public void setAssumeUntrustedCertificateIssuer(boolean untrustedIssuer) { this.untrustedCertIssuer = untrustedIssuer; } public boolean isRunning() { File macAndLinuxLockFile = new File(profileDir, ".parentlock"); File windowsLockFile = new File(profileDir, "parent.lock"); return macAndLinuxLockFile.exists() || windowsLockFile.exists(); } public void clean() { TemporaryFilesystem.deleteTempDir(profileDir); } public String toJson() throws IOException { updateUserPrefs(); return new Zip().zip(profileDir); } public static FirefoxProfile fromJson(String json) throws IOException { File dir = TemporaryFilesystem.createTempDir("webdriver", "duplicated"); new Zip().unzip(json, dir); return new FirefoxProfile(dir); } }
true
true
public void updateUserPrefs() { if (port == 0) { throw new WebDriverException("You must set the port to listen on before updating user.js"); } Map<String, String> prefs = new HashMap<String, String>(); // Allow users to override these settings prefs.put("browser.startup.homepage", "\"about:blank\""); // The user must be able to override this setting (to 1) in order to // to change homepage on Firefox 3.0 prefs.put("browser.startup.page", "0"); if (userPrefs.exists()) { prefs = readExistingPrefs(userPrefs); if (!userPrefs.delete()) throw new WebDriverException("Cannot delete existing user preferences"); } additionalPrefs.addTo(prefs); // Normal settings to facilitate testing prefs.put("app.update.auto", "false"); prefs.put("app.update.enabled", "false"); prefs.put("browser.download.manager.showWhenStarting", "false"); prefs.put("browser.EULA.override", "true"); prefs.put("browser.EULA.3.accepted", "true"); prefs.put("browser.link.open_external", "2"); prefs.put("browser.link.open_newwindow", "2"); prefs.put("browser.safebrowsing.enabled", "false"); prefs.put("browser.search.update", "false"); prefs.put("browser.sessionstore.resume_from_crash", "false"); prefs.put("browser.shell.checkDefaultBrowser", "false"); prefs.put("browser.tabs.warnOnClose", "false"); prefs.put("browser.tabs.warnOnOpen", "false"); prefs.put("dom.disable_open_during_load", "false"); prefs.put("extensions.update.enabled", "false"); prefs.put("extensions.update.notifyUser", "false"); prefs.put("security.fileuri.origin_policy", "3"); prefs.put("security.fileuri.strict_origin_policy", "false"); prefs.put("security.warn_entering_secure", "false"); prefs.put("security.warn_submit_insecure", "false"); prefs.put("security.warn_entering_secure.show_once", "false"); prefs.put("security.warn_entering_weak", "false"); prefs.put("security.warn_entering_weak.show_once", "false"); prefs.put("security.warn_leaving_secure", "false"); prefs.put("security.warn_leaving_secure.show_once", "false"); prefs.put("security.warn_submit_insecure", "false"); prefs.put("security.warn_viewing_mixed", "false"); prefs.put("security.warn_viewing_mixed.show_once", "false"); prefs.put("signon.rememberSignons", "false"); // Which port should we listen on? prefs.put("webdriver_firefox_port", Integer.toString(port)); // Should we use native events? prefs.put("webdriver_enable_native_events", Boolean.toString(enableNativeEvents)); // Should we accept untrusted certificates or not? prefs.put("webdriver_accept_untrusted_certs", Boolean.toString(acceptUntrustedCerts)); prefs.put("webdriver_assume_untrusted_issuer", Boolean.toString(untrustedCertIssuer)); // Settings to facilitate debugging the driver prefs.put("javascript.options.showInConsole", "true"); // Logs errors in chrome files to the Error Console. prefs.put("browser.dom.window.dump.enabled", "true"); // Enables the use of the dump() statement // If the user sets the home page, we should also start up there prefs.put("startup.homepage_welcome_url", prefs.get("browser.startup.homepage")); if (!"about:blank".equals(prefs.get("browser.startup.homepage"))) { prefs.put("browser.startup.page", "1"); } writeNewPrefs(prefs); }
public void updateUserPrefs() { if (port == 0) { throw new WebDriverException("You must set the port to listen on before updating user.js"); } Map<String, String> prefs = new HashMap<String, String>(); // Allow users to override these settings prefs.put("browser.startup.homepage", "\"about:blank\""); // The user must be able to override this setting (to 1) in order to // to change homepage on Firefox 3.0 prefs.put("browser.startup.page", "0"); if (userPrefs.exists()) { prefs = readExistingPrefs(userPrefs); if (!userPrefs.delete()) throw new WebDriverException("Cannot delete existing user preferences"); } additionalPrefs.addTo(prefs); // Normal settings to facilitate testing prefs.put("app.update.auto", "false"); prefs.put("app.update.enabled", "false"); prefs.put("browser.download.manager.showWhenStarting", "false"); prefs.put("browser.EULA.override", "true"); prefs.put("browser.EULA.3.accepted", "true"); prefs.put("browser.link.open_external", "2"); prefs.put("browser.link.open_newwindow", "2"); prefs.put("browser.safebrowsing.enabled", "false"); prefs.put("browser.search.update", "false"); prefs.put("browser.sessionstore.resume_from_crash", "false"); prefs.put("browser.shell.checkDefaultBrowser", "false"); prefs.put("browser.tabs.warnOnClose", "false"); prefs.put("browser.tabs.warnOnOpen", "false"); prefs.put("dom.disable_open_during_load", "false"); prefs.put("extensions.update.enabled", "false"); prefs.put("extensions.update.notifyUser", "false"); prefs.put("network.manage-offline-status", "false"); prefs.put("security.fileuri.origin_policy", "3"); prefs.put("security.fileuri.strict_origin_policy", "false"); prefs.put("security.warn_entering_secure", "false"); prefs.put("security.warn_submit_insecure", "false"); prefs.put("security.warn_entering_secure.show_once", "false"); prefs.put("security.warn_entering_weak", "false"); prefs.put("security.warn_entering_weak.show_once", "false"); prefs.put("security.warn_leaving_secure", "false"); prefs.put("security.warn_leaving_secure.show_once", "false"); prefs.put("security.warn_submit_insecure", "false"); prefs.put("security.warn_viewing_mixed", "false"); prefs.put("security.warn_viewing_mixed.show_once", "false"); prefs.put("signon.rememberSignons", "false"); // Which port should we listen on? prefs.put("webdriver_firefox_port", Integer.toString(port)); // Should we use native events? prefs.put("webdriver_enable_native_events", Boolean.toString(enableNativeEvents)); // Should we accept untrusted certificates or not? prefs.put("webdriver_accept_untrusted_certs", Boolean.toString(acceptUntrustedCerts)); prefs.put("webdriver_assume_untrusted_issuer", Boolean.toString(untrustedCertIssuer)); // Settings to facilitate debugging the driver prefs.put("javascript.options.showInConsole", "true"); // Logs errors in chrome files to the Error Console. prefs.put("browser.dom.window.dump.enabled", "true"); // Enables the use of the dump() statement // If the user sets the home page, we should also start up there prefs.put("startup.homepage_welcome_url", prefs.get("browser.startup.homepage")); if (!"about:blank".equals(prefs.get("browser.startup.homepage"))) { prefs.put("browser.startup.page", "1"); } writeNewPrefs(prefs); }
diff --git a/src/com/cpcookieman/cookieirc/CommandProcessor.java b/src/com/cpcookieman/cookieirc/CommandProcessor.java index 09dab94..d1e3bc3 100644 --- a/src/com/cpcookieman/cookieirc/CommandProcessor.java +++ b/src/com/cpcookieman/cookieirc/CommandProcessor.java @@ -1,163 +1,163 @@ package com.cpcookieman.cookieirc; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JWindow; public class CommandProcessor { public void process(String s, int tab) { if(s.equals("")) { } else if(s.equals("/spinner")) { new Thread(new Runnable() { @Override public void run() { final JWindow newFrame = new JWindow(); Main.frame.setEnabled(false); newFrame.setVisible(false); newFrame.add(new JLabel(new ImageIcon("res/spinner.gif"))); newFrame.pack(); newFrame.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent arg0) { newFrame.dispose(); Main.frame.setEnabled(true); } @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} }); newFrame.setLocationRelativeTo(Main.frame); newFrame.setVisible(true); } }).run(); } else if(s.equals("/debug")) { int i = 0; Main.gui.tabs.get(tab).output.append("\n### BEGIN DEBUG LOG ###"); while(true) { try { Main.gui.tabs.get(tab).output.append("\n" + Main.getDebugMessages()[i].toString()); i++; } catch(Exception e) { break; } } Main.gui.tabs.get(tab).output.append("\n### END DEBUG LOG ###"); } else if(s.startsWith("/quit")) { System.exit(0); } else if(s.startsWith("/reloaduser")) { Main.gui.tabs.get(tab).onAction(); } else if(s.startsWith("/nick ")) { Main.gui.tabs.get(tab).addMessage(Main.user, s); Main.gui.tabs.get(tab).tabSpecificProcess(s); Main.user = s.substring(6); } else if(s.startsWith("/join ")) { String working = s.substring(6); if(!working.startsWith("#")) { working = "#" + working; } Main.debug("Attempted to join channel " + working); if(Main.gui.tabs.get(tab).action == -1) { Main.gui.tabs.get(tab).addMessage("Not on a server oriented tab!"); } else { int i = Main.gui.addTab(new Tab(working, true, 1)); Main.gui.tabs.get(i).server = Main.gui.tabs.get(tab).server; Main.gui.tabs.get(i).serverid = Main.gui.tabs.get(tab).serverid; Main.gui.tabs.get(i).addMessage("Entering " + working + "..."); Main.servers.get(Main.gui.tabs.get(i).serverid).joinChannel(working); } } else if(s.startsWith("/msg ")) { String working = s.substring(5); Main.debug("Messaging " + working); if(Main.gui.tabs.get(tab).action == -1) { Main.gui.tabs.get(tab).addMessage("Not on a server oriented tab!"); } else { //TODO Add pm joining code int i = Main.gui.addTab(new Tab(working, false, 2)); Main.gui.tabs.get(i).server = Main.gui.tabs.get(tab).server; Main.gui.tabs.get(i).serverid = Main.gui.tabs.get(tab).serverid; Main.gui.tabs.get(i).addMessage("Chatting with " + working + "..."); } } else if(s.startsWith("/server ") || s.startsWith("/connect ")) { try { String working; if(s.startsWith("/server")) { working = s.substring(8); } else { working = s.substring(9); } int i = Main.gui.addTab(new Tab(working, false, 0)); Main.gui.tabs.get(i).addMessage("Connecting to " + working + "..."); Main.debug("Connecting to server with arguments '" + working + "'"); Main.servers.add(new ServerConnection(working, ++Main.servercounter, i)); Main.gui.tabs.get(i).server = working; Main.gui.tabs.get(i).serverid = Main.servercounter; Main.debug("Connected to server '" + working + "'"); } catch(Exception e) { Main.gui.tabs.get(tab).addMessage("/server or /connect", false); Main.gui.tabs.get(tab).addMessage("Starts a connection with a server. Takes server IP as an argument.", false); } } else { Main.gui.tabs.get(tab).addMessage(Main.user, s); Main.gui.tabs.get(tab).tabSpecificProcess(s); try { Main.gui.tabs.get(tab).getServer().sendMessage(Main.gui.tabs.get(tab).title, s); } catch(NullPointerException e) { - //Don't care. + Main.gui.tabs.get(tab).addMessage("I'm not sure I understand \"" + s + "\" (Command not recognized)"); } } } }
true
true
public void process(String s, int tab) { if(s.equals("")) { } else if(s.equals("/spinner")) { new Thread(new Runnable() { @Override public void run() { final JWindow newFrame = new JWindow(); Main.frame.setEnabled(false); newFrame.setVisible(false); newFrame.add(new JLabel(new ImageIcon("res/spinner.gif"))); newFrame.pack(); newFrame.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent arg0) { newFrame.dispose(); Main.frame.setEnabled(true); } @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} }); newFrame.setLocationRelativeTo(Main.frame); newFrame.setVisible(true); } }).run(); } else if(s.equals("/debug")) { int i = 0; Main.gui.tabs.get(tab).output.append("\n### BEGIN DEBUG LOG ###"); while(true) { try { Main.gui.tabs.get(tab).output.append("\n" + Main.getDebugMessages()[i].toString()); i++; } catch(Exception e) { break; } } Main.gui.tabs.get(tab).output.append("\n### END DEBUG LOG ###"); } else if(s.startsWith("/quit")) { System.exit(0); } else if(s.startsWith("/reloaduser")) { Main.gui.tabs.get(tab).onAction(); } else if(s.startsWith("/nick ")) { Main.gui.tabs.get(tab).addMessage(Main.user, s); Main.gui.tabs.get(tab).tabSpecificProcess(s); Main.user = s.substring(6); } else if(s.startsWith("/join ")) { String working = s.substring(6); if(!working.startsWith("#")) { working = "#" + working; } Main.debug("Attempted to join channel " + working); if(Main.gui.tabs.get(tab).action == -1) { Main.gui.tabs.get(tab).addMessage("Not on a server oriented tab!"); } else { int i = Main.gui.addTab(new Tab(working, true, 1)); Main.gui.tabs.get(i).server = Main.gui.tabs.get(tab).server; Main.gui.tabs.get(i).serverid = Main.gui.tabs.get(tab).serverid; Main.gui.tabs.get(i).addMessage("Entering " + working + "..."); Main.servers.get(Main.gui.tabs.get(i).serverid).joinChannel(working); } } else if(s.startsWith("/msg ")) { String working = s.substring(5); Main.debug("Messaging " + working); if(Main.gui.tabs.get(tab).action == -1) { Main.gui.tabs.get(tab).addMessage("Not on a server oriented tab!"); } else { //TODO Add pm joining code int i = Main.gui.addTab(new Tab(working, false, 2)); Main.gui.tabs.get(i).server = Main.gui.tabs.get(tab).server; Main.gui.tabs.get(i).serverid = Main.gui.tabs.get(tab).serverid; Main.gui.tabs.get(i).addMessage("Chatting with " + working + "..."); } } else if(s.startsWith("/server ") || s.startsWith("/connect ")) { try { String working; if(s.startsWith("/server")) { working = s.substring(8); } else { working = s.substring(9); } int i = Main.gui.addTab(new Tab(working, false, 0)); Main.gui.tabs.get(i).addMessage("Connecting to " + working + "..."); Main.debug("Connecting to server with arguments '" + working + "'"); Main.servers.add(new ServerConnection(working, ++Main.servercounter, i)); Main.gui.tabs.get(i).server = working; Main.gui.tabs.get(i).serverid = Main.servercounter; Main.debug("Connected to server '" + working + "'"); } catch(Exception e) { Main.gui.tabs.get(tab).addMessage("/server or /connect", false); Main.gui.tabs.get(tab).addMessage("Starts a connection with a server. Takes server IP as an argument.", false); } } else { Main.gui.tabs.get(tab).addMessage(Main.user, s); Main.gui.tabs.get(tab).tabSpecificProcess(s); try { Main.gui.tabs.get(tab).getServer().sendMessage(Main.gui.tabs.get(tab).title, s); } catch(NullPointerException e) { //Don't care. } } }
public void process(String s, int tab) { if(s.equals("")) { } else if(s.equals("/spinner")) { new Thread(new Runnable() { @Override public void run() { final JWindow newFrame = new JWindow(); Main.frame.setEnabled(false); newFrame.setVisible(false); newFrame.add(new JLabel(new ImageIcon("res/spinner.gif"))); newFrame.pack(); newFrame.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent arg0) { newFrame.dispose(); Main.frame.setEnabled(true); } @Override public void mouseEntered(MouseEvent arg0) {} @Override public void mouseExited(MouseEvent arg0) {} @Override public void mousePressed(MouseEvent arg0) {} @Override public void mouseReleased(MouseEvent arg0) {} }); newFrame.setLocationRelativeTo(Main.frame); newFrame.setVisible(true); } }).run(); } else if(s.equals("/debug")) { int i = 0; Main.gui.tabs.get(tab).output.append("\n### BEGIN DEBUG LOG ###"); while(true) { try { Main.gui.tabs.get(tab).output.append("\n" + Main.getDebugMessages()[i].toString()); i++; } catch(Exception e) { break; } } Main.gui.tabs.get(tab).output.append("\n### END DEBUG LOG ###"); } else if(s.startsWith("/quit")) { System.exit(0); } else if(s.startsWith("/reloaduser")) { Main.gui.tabs.get(tab).onAction(); } else if(s.startsWith("/nick ")) { Main.gui.tabs.get(tab).addMessage(Main.user, s); Main.gui.tabs.get(tab).tabSpecificProcess(s); Main.user = s.substring(6); } else if(s.startsWith("/join ")) { String working = s.substring(6); if(!working.startsWith("#")) { working = "#" + working; } Main.debug("Attempted to join channel " + working); if(Main.gui.tabs.get(tab).action == -1) { Main.gui.tabs.get(tab).addMessage("Not on a server oriented tab!"); } else { int i = Main.gui.addTab(new Tab(working, true, 1)); Main.gui.tabs.get(i).server = Main.gui.tabs.get(tab).server; Main.gui.tabs.get(i).serverid = Main.gui.tabs.get(tab).serverid; Main.gui.tabs.get(i).addMessage("Entering " + working + "..."); Main.servers.get(Main.gui.tabs.get(i).serverid).joinChannel(working); } } else if(s.startsWith("/msg ")) { String working = s.substring(5); Main.debug("Messaging " + working); if(Main.gui.tabs.get(tab).action == -1) { Main.gui.tabs.get(tab).addMessage("Not on a server oriented tab!"); } else { //TODO Add pm joining code int i = Main.gui.addTab(new Tab(working, false, 2)); Main.gui.tabs.get(i).server = Main.gui.tabs.get(tab).server; Main.gui.tabs.get(i).serverid = Main.gui.tabs.get(tab).serverid; Main.gui.tabs.get(i).addMessage("Chatting with " + working + "..."); } } else if(s.startsWith("/server ") || s.startsWith("/connect ")) { try { String working; if(s.startsWith("/server")) { working = s.substring(8); } else { working = s.substring(9); } int i = Main.gui.addTab(new Tab(working, false, 0)); Main.gui.tabs.get(i).addMessage("Connecting to " + working + "..."); Main.debug("Connecting to server with arguments '" + working + "'"); Main.servers.add(new ServerConnection(working, ++Main.servercounter, i)); Main.gui.tabs.get(i).server = working; Main.gui.tabs.get(i).serverid = Main.servercounter; Main.debug("Connected to server '" + working + "'"); } catch(Exception e) { Main.gui.tabs.get(tab).addMessage("/server or /connect", false); Main.gui.tabs.get(tab).addMessage("Starts a connection with a server. Takes server IP as an argument.", false); } } else { Main.gui.tabs.get(tab).addMessage(Main.user, s); Main.gui.tabs.get(tab).tabSpecificProcess(s); try { Main.gui.tabs.get(tab).getServer().sendMessage(Main.gui.tabs.get(tab).title, s); } catch(NullPointerException e) { Main.gui.tabs.get(tab).addMessage("I'm not sure I understand \"" + s + "\" (Command not recognized)"); } } }
diff --git a/pgsnapshot/src/org/openstreetmap/osmosis/pgsnapshot/v0_6/impl/PostgreSqlDatasetContext.java b/pgsnapshot/src/org/openstreetmap/osmosis/pgsnapshot/v0_6/impl/PostgreSqlDatasetContext.java index 266891a0..28d565e1 100644 --- a/pgsnapshot/src/org/openstreetmap/osmosis/pgsnapshot/v0_6/impl/PostgreSqlDatasetContext.java +++ b/pgsnapshot/src/org/openstreetmap/osmosis/pgsnapshot/v0_6/impl/PostgreSqlDatasetContext.java @@ -1,440 +1,440 @@ // This software is released into the Public Domain. See copying.txt for details. package org.openstreetmap.osmosis.pgsnapshot.v0_6.impl; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; import org.openstreetmap.osmosis.core.OsmosisConstants; import org.openstreetmap.osmosis.core.container.v0_6.BoundContainer; import org.openstreetmap.osmosis.core.container.v0_6.BoundContainerIterator; import org.openstreetmap.osmosis.core.container.v0_6.DatasetContext; import org.openstreetmap.osmosis.core.container.v0_6.EntityContainer; import org.openstreetmap.osmosis.core.container.v0_6.EntityManager; import org.openstreetmap.osmosis.core.container.v0_6.NodeContainer; import org.openstreetmap.osmosis.core.container.v0_6.NodeContainerIterator; import org.openstreetmap.osmosis.core.container.v0_6.RelationContainer; import org.openstreetmap.osmosis.core.container.v0_6.RelationContainerIterator; import org.openstreetmap.osmosis.core.container.v0_6.WayContainer; import org.openstreetmap.osmosis.core.container.v0_6.WayContainerIterator; import org.openstreetmap.osmosis.core.database.DatabaseLoginCredentials; import org.openstreetmap.osmosis.core.database.DatabasePreferences; import org.openstreetmap.osmosis.core.domain.v0_6.Bound; import org.openstreetmap.osmosis.core.domain.v0_6.Node; import org.openstreetmap.osmosis.core.domain.v0_6.Relation; import org.openstreetmap.osmosis.core.domain.v0_6.Way; import org.openstreetmap.osmosis.core.lifecycle.ReleasableIterator; import org.openstreetmap.osmosis.core.store.MultipleSourceIterator; import org.openstreetmap.osmosis.core.store.ReleasableAdaptorForIterator; import org.openstreetmap.osmosis.core.store.UpcastIterator; import org.openstreetmap.osmosis.pgsnapshot.common.DatabaseContext; import org.openstreetmap.osmosis.pgsnapshot.common.PolygonBuilder; import org.openstreetmap.osmosis.pgsnapshot.common.SchemaVersionValidator; import org.openstreetmap.osmosis.pgsnapshot.v0_6.PostgreSqlVersionConstants; import org.postgis.PGgeometry; import org.postgis.Point; import org.postgis.Polygon; import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; /** * Provides read-only access to a PostgreSQL dataset store. Each thread * accessing the store must create its own reader. It is important that all * iterators obtained from this reader are released before releasing the reader * itself. * * @author Brett Henderson */ public class PostgreSqlDatasetContext implements DatasetContext { private static final Logger LOG = Logger.getLogger(PostgreSqlDatasetContext.class.getName()); private DatabaseLoginCredentials loginCredentials; private DatabasePreferences preferences; private DatabaseCapabilityChecker capabilityChecker; private boolean initialized; private DatabaseContext dbCtx; private SimpleJdbcTemplate jdbcTemplate; private UserDao userDao; private NodeDao nodeDao; private WayDao wayDao; private RelationDao relationDao; private PostgreSqlEntityManager<Node> nodeManager; private PostgreSqlEntityManager<Way> wayManager; private PostgreSqlEntityManager<Relation> relationManager; private PolygonBuilder polygonBuilder; /** * Creates a new instance. * * @param loginCredentials * Contains all information required to connect to the database. * @param preferences * Contains preferences configuring database behaviour. */ public PostgreSqlDatasetContext(DatabaseLoginCredentials loginCredentials, DatabasePreferences preferences) { this.loginCredentials = loginCredentials; this.preferences = preferences; polygonBuilder = new PolygonBuilder(); initialized = false; } /** * Initialises the database connection and associated data access objects. */ private void initialize() { if (dbCtx == null) { ActionDao actionDao; dbCtx = new DatabaseContext(loginCredentials); jdbcTemplate = dbCtx.getSimpleJdbcTemplate(); dbCtx.beginTransaction(); new SchemaVersionValidator(jdbcTemplate, preferences).validateVersion( PostgreSqlVersionConstants.SCHEMA_VERSION); capabilityChecker = new DatabaseCapabilityChecker(dbCtx); actionDao = new ActionDao(dbCtx); userDao = new UserDao(dbCtx, actionDao); nodeDao = new NodeDao(dbCtx, actionDao); wayDao = new WayDao(dbCtx, actionDao); relationDao = new RelationDao(dbCtx, actionDao); nodeManager = new PostgreSqlEntityManager<Node>(nodeDao, userDao); wayManager = new PostgreSqlEntityManager<Way>(wayDao, userDao); relationManager = new PostgreSqlEntityManager<Relation>(relationDao, userDao); } initialized = true; } /** * {@inheritDoc} */ @Override @Deprecated public Node getNode(long id) { return getNodeManager().getEntity(id); } /** * {@inheritDoc} */ @Override @Deprecated public Way getWay(long id) { return getWayManager().getEntity(id); } /** * {@inheritDoc} */ @Override @Deprecated public Relation getRelation(long id) { return getRelationManager().getEntity(id); } /** * {@inheritDoc} */ @Override public EntityManager<Node> getNodeManager() { if (!initialized) { initialize(); } return nodeManager; } /** * {@inheritDoc} */ @Override public EntityManager<Way> getWayManager() { if (!initialized) { initialize(); } return wayManager; } /** * {@inheritDoc} */ @Override public EntityManager<Relation> getRelationManager() { if (!initialized) { initialize(); } return relationManager; } /** * {@inheritDoc} */ @Override public ReleasableIterator<EntityContainer> iterate() { List<Bound> bounds; List<ReleasableIterator<EntityContainer>> sources; if (!initialized) { initialize(); } // Build the bounds list. bounds = new ArrayList<Bound>(); bounds.add(new Bound("Osmosis " + OsmosisConstants.VERSION)); sources = new ArrayList<ReleasableIterator<EntityContainer>>(); sources.add(new UpcastIterator<EntityContainer, BoundContainer>( new BoundContainerIterator(new ReleasableAdaptorForIterator<Bound>(bounds.iterator())))); sources.add(new UpcastIterator<EntityContainer, NodeContainer>( new NodeContainerIterator(nodeDao.iterate()))); sources.add(new UpcastIterator<EntityContainer, WayContainer>( new WayContainerIterator(wayDao.iterate()))); sources.add(new UpcastIterator<EntityContainer, RelationContainer>( new RelationContainerIterator(relationDao.iterate()))); return new MultipleSourceIterator<EntityContainer>(sources); } /** * {@inheritDoc} */ @Override public ReleasableIterator<EntityContainer> iterateBoundingBox( double left, double right, double top, double bottom, boolean completeWays) { List<Bound> bounds; Point[] bboxPoints; Polygon bboxPolygon; int rowCount; List<ReleasableIterator<EntityContainer>> resultSets; if (!initialized) { initialize(); } // Build the bounds list. bounds = new ArrayList<Bound>(); bounds.add(new Bound(right, left, top, bottom, "Osmosis " + OsmosisConstants.VERSION)); // PostgreSQL sometimes incorrectly chooses to perform full table scans, these options // prevent this. Note that this is not recommended practice according to documentation // but fixing this would require modifying the table statistics gathering // configuration to produce better plans. jdbcTemplate.update("SET enable_seqscan = false"); jdbcTemplate.update("SET enable_mergejoin = false"); jdbcTemplate.update("SET enable_hashjoin = false"); // Build a polygon representing the bounding box. // Sample box for query testing may be: // GeomFromText('POLYGON((144.93912192855174 -37.82981987499741, // 144.93912192855174 -37.79310006709244, 144.98188026000003 // -37.79310006709244, 144.98188026000003 -37.82981987499741, // 144.93912192855174 -37.82981987499741))', -1) bboxPoints = new Point[5]; bboxPoints[0] = new Point(left, bottom); bboxPoints[1] = new Point(left, top); bboxPoints[2] = new Point(right, top); bboxPoints[3] = new Point(right, bottom); bboxPoints[4] = new Point(left, bottom); bboxPolygon = polygonBuilder.createPolygon(bboxPoints); // Select all nodes inside the box into the node temp table. LOG.finer("Selecting all nodes inside bounding box."); rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_nodes ON COMMIT DROP AS" + " SELECT * FROM nodes WHERE (geom && ?)", new PGgeometry(bboxPolygon)); LOG.finer("Adding a primary key to the temporary nodes table."); jdbcTemplate.update("ALTER TABLE ONLY bbox_nodes ADD CONSTRAINT pk_bbox_nodes PRIMARY KEY (id)"); LOG.finer("Updating query analyzer statistics on the temporary nodes table."); jdbcTemplate.update("ANALYZE bbox_nodes"); // Select all ways inside the bounding box into the way temp table. if (capabilityChecker.isWayLinestringSupported()) { LOG.finer("Selecting all ways inside bounding box using way linestring geometry."); // We have full way geometry available so select ways // overlapping the requested bounding box. rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_ways ON COMMIT DROP AS" + " SELECT * FROM ways WHERE (linestring && ?)", new PGgeometry(bboxPolygon)); } else if (capabilityChecker.isWayBboxSupported()) { LOG.finer("Selecting all ways inside bounding box using dynamically built" + " way linestring with way bbox indexing."); // The inner query selects the way id and node coordinates for // all ways constrained by the way bounding box which is // indexed. // The middle query converts the way node coordinates into // linestrings. // The outer query constrains the query to the linestrings // inside the bounding box. These aren't indexed but the inner // query way bbox constraint will minimise the unnecessary data. rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_ways ON COMMIT DROP AS" + " SELECT w.* FROM (" + "SELECT c.id, c.version, c.user_id, c.tstamp, c.changeset_id, c.tags," + " MakeLine(c.geom) AS way_line FROM (" + "SELECT w.*, n.geom AS geom FROM nodes n" + " INNER JOIN way_nodes wn ON n.id = wn.node_id" + " INNER JOIN ways w ON wn.way_id = w.id" + " WHERE (w.bbox && ?) ORDER BY wn.way_id, wn.sequence_id" + ") c " + "GROUP BY c.id, c.version, c.user_id, c.tstamp, c.changeset_id, c.tags" + ") w " + "WHERE (w.way_line && ?)", new PGgeometry(bboxPolygon), new PGgeometry(bboxPolygon) ); } else { LOG.finer("Selecting all way ids inside bounding box using already selected nodes."); // No way bbox support is available so select ways containing // the selected nodes. rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_ways ON COMMIT DROP AS" - + " SELECT w.id, w.version, w.user_id, w.tstamp, w.changeset_id, w.tags FROM ways w" + + " SELECT w.* FROM ways w" + " INNER JOIN (" + " SELECT wn.way_id FROM way_nodes wn" + " INNER JOIN bbox_nodes n ON wn.node_id = n.id GROUP BY wn.way_id" + ") wids ON w.id = wids.way_id" ); } LOG.finer(rowCount + " rows affected."); LOG.finer("Adding a primary key to the temporary ways table."); jdbcTemplate.update("ALTER TABLE ONLY bbox_ways ADD CONSTRAINT pk_bbox_ways PRIMARY KEY (id)"); LOG.finer("Updating query analyzer statistics on the temporary ways table."); jdbcTemplate.update("ANALYZE bbox_ways"); // Select all relations containing the nodes or ways into the relation table. LOG.finer("Selecting all relation ids containing selected nodes or ways."); rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_relations ON COMMIT DROP AS" + " SELECT r.* FROM relations r" + " INNER JOIN (" + " SELECT relation_id FROM (" + " SELECT rm.relation_id AS relation_id FROM relation_members rm" + " INNER JOIN bbox_nodes n ON rm.member_id = n.id WHERE rm.member_type = 'N' " + " UNION " + " SELECT rm.relation_id AS relation_id FROM relation_members rm" + " INNER JOIN bbox_ways w ON rm.member_id = w.id WHERE rm.member_type = 'W'" + " ) rids GROUP BY relation_id" + ") rids ON r.id = rids.relation_id" ); LOG.finer(rowCount + " rows affected."); LOG.finer("Adding a primary key to the temporary relations table."); jdbcTemplate.update("ALTER TABLE ONLY bbox_relations ADD CONSTRAINT pk_bbox_relations PRIMARY KEY (id)"); LOG.finer("Updating query analyzer statistics on the temporary relations table."); jdbcTemplate.update("ANALYZE bbox_relations"); // Include all relations containing the current relations into the // relation table and repeat until no more inclusions occur. do { LOG.finer("Selecting parent relations of selected relations."); rowCount = jdbcTemplate.update( "INSERT INTO bbox_relations " + "SELECT r.* FROM relations r INNER JOIN (" + " SELECT rm.relation_id FROM relation_members rm" + " INNER JOIN bbox_relations br ON rm.member_id = br.id" + " WHERE rm.member_type = 'R' AND NOT EXISTS (" + " SELECT * FROM bbox_relations br2 WHERE rm.relation_id = br2.id" + " ) GROUP BY rm.relation_id" + ") rids ON r.id = rids.relation_id" ); LOG.finer(rowCount + " rows affected."); } while (rowCount > 0); LOG.finer("Updating query analyzer statistics on the temporary relations table."); jdbcTemplate.update("ANALYZE bbox_relations"); // If complete ways is set, select all nodes contained by the ways into the node temp table. if (completeWays) { LOG.finer("Selecting all nodes for selected ways."); jdbcTemplate.update("CREATE TEMPORARY TABLE bbox_way_nodes (id bigint) ON COMMIT DROP"); jdbcTemplate.queryForList("SELECT unnest_bbox_way_nodes()"); jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_missing_way_nodes ON COMMIT DROP AS " + "SELECT buwn.id FROM (SELECT DISTINCT bwn.id FROM bbox_way_nodes bwn) buwn " + "WHERE NOT EXISTS (" + " SELECT * FROM bbox_nodes WHERE id = buwn.id" + ");" ); jdbcTemplate.update("ALTER TABLE ONLY bbox_missing_way_nodes" + " ADD CONSTRAINT pk_bbox_missing_way_nodes PRIMARY KEY (id)"); jdbcTemplate.update("ANALYZE bbox_missing_way_nodes"); rowCount = jdbcTemplate.update("INSERT INTO bbox_nodes " + "SELECT n.* FROM nodes n INNER JOIN bbox_missing_way_nodes bwn ON n.id = bwn.id;"); LOG.finer(rowCount + " rows affected."); } LOG.finer("Updating query analyzer statistics on the temporary nodes table."); jdbcTemplate.update("ANALYZE bbox_nodes"); // Create iterators for the selected records for each of the entity types. LOG.finer("Iterating over results."); resultSets = new ArrayList<ReleasableIterator<EntityContainer>>(); resultSets.add( new UpcastIterator<EntityContainer, BoundContainer>( new BoundContainerIterator(new ReleasableAdaptorForIterator<Bound>(bounds.iterator())))); resultSets.add( new UpcastIterator<EntityContainer, NodeContainer>( new NodeContainerIterator(nodeDao.iterate("bbox_")))); resultSets.add( new UpcastIterator<EntityContainer, WayContainer>( new WayContainerIterator(wayDao.iterate("bbox_")))); resultSets.add( new UpcastIterator<EntityContainer, RelationContainer>( new RelationContainerIterator(relationDao.iterate("bbox_")))); // Merge all readers into a single result iterator and return. return new MultipleSourceIterator<EntityContainer>(resultSets); } /** * {@inheritDoc} */ @Override public void complete() { dbCtx.commitTransaction(); } /** * {@inheritDoc} */ @Override public void release() { if (dbCtx != null) { dbCtx.release(); dbCtx = null; } } }
true
true
public ReleasableIterator<EntityContainer> iterateBoundingBox( double left, double right, double top, double bottom, boolean completeWays) { List<Bound> bounds; Point[] bboxPoints; Polygon bboxPolygon; int rowCount; List<ReleasableIterator<EntityContainer>> resultSets; if (!initialized) { initialize(); } // Build the bounds list. bounds = new ArrayList<Bound>(); bounds.add(new Bound(right, left, top, bottom, "Osmosis " + OsmosisConstants.VERSION)); // PostgreSQL sometimes incorrectly chooses to perform full table scans, these options // prevent this. Note that this is not recommended practice according to documentation // but fixing this would require modifying the table statistics gathering // configuration to produce better plans. jdbcTemplate.update("SET enable_seqscan = false"); jdbcTemplate.update("SET enable_mergejoin = false"); jdbcTemplate.update("SET enable_hashjoin = false"); // Build a polygon representing the bounding box. // Sample box for query testing may be: // GeomFromText('POLYGON((144.93912192855174 -37.82981987499741, // 144.93912192855174 -37.79310006709244, 144.98188026000003 // -37.79310006709244, 144.98188026000003 -37.82981987499741, // 144.93912192855174 -37.82981987499741))', -1) bboxPoints = new Point[5]; bboxPoints[0] = new Point(left, bottom); bboxPoints[1] = new Point(left, top); bboxPoints[2] = new Point(right, top); bboxPoints[3] = new Point(right, bottom); bboxPoints[4] = new Point(left, bottom); bboxPolygon = polygonBuilder.createPolygon(bboxPoints); // Select all nodes inside the box into the node temp table. LOG.finer("Selecting all nodes inside bounding box."); rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_nodes ON COMMIT DROP AS" + " SELECT * FROM nodes WHERE (geom && ?)", new PGgeometry(bboxPolygon)); LOG.finer("Adding a primary key to the temporary nodes table."); jdbcTemplate.update("ALTER TABLE ONLY bbox_nodes ADD CONSTRAINT pk_bbox_nodes PRIMARY KEY (id)"); LOG.finer("Updating query analyzer statistics on the temporary nodes table."); jdbcTemplate.update("ANALYZE bbox_nodes"); // Select all ways inside the bounding box into the way temp table. if (capabilityChecker.isWayLinestringSupported()) { LOG.finer("Selecting all ways inside bounding box using way linestring geometry."); // We have full way geometry available so select ways // overlapping the requested bounding box. rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_ways ON COMMIT DROP AS" + " SELECT * FROM ways WHERE (linestring && ?)", new PGgeometry(bboxPolygon)); } else if (capabilityChecker.isWayBboxSupported()) { LOG.finer("Selecting all ways inside bounding box using dynamically built" + " way linestring with way bbox indexing."); // The inner query selects the way id and node coordinates for // all ways constrained by the way bounding box which is // indexed. // The middle query converts the way node coordinates into // linestrings. // The outer query constrains the query to the linestrings // inside the bounding box. These aren't indexed but the inner // query way bbox constraint will minimise the unnecessary data. rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_ways ON COMMIT DROP AS" + " SELECT w.* FROM (" + "SELECT c.id, c.version, c.user_id, c.tstamp, c.changeset_id, c.tags," + " MakeLine(c.geom) AS way_line FROM (" + "SELECT w.*, n.geom AS geom FROM nodes n" + " INNER JOIN way_nodes wn ON n.id = wn.node_id" + " INNER JOIN ways w ON wn.way_id = w.id" + " WHERE (w.bbox && ?) ORDER BY wn.way_id, wn.sequence_id" + ") c " + "GROUP BY c.id, c.version, c.user_id, c.tstamp, c.changeset_id, c.tags" + ") w " + "WHERE (w.way_line && ?)", new PGgeometry(bboxPolygon), new PGgeometry(bboxPolygon) ); } else { LOG.finer("Selecting all way ids inside bounding box using already selected nodes."); // No way bbox support is available so select ways containing // the selected nodes. rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_ways ON COMMIT DROP AS" + " SELECT w.id, w.version, w.user_id, w.tstamp, w.changeset_id, w.tags FROM ways w" + " INNER JOIN (" + " SELECT wn.way_id FROM way_nodes wn" + " INNER JOIN bbox_nodes n ON wn.node_id = n.id GROUP BY wn.way_id" + ") wids ON w.id = wids.way_id" ); } LOG.finer(rowCount + " rows affected."); LOG.finer("Adding a primary key to the temporary ways table."); jdbcTemplate.update("ALTER TABLE ONLY bbox_ways ADD CONSTRAINT pk_bbox_ways PRIMARY KEY (id)"); LOG.finer("Updating query analyzer statistics on the temporary ways table."); jdbcTemplate.update("ANALYZE bbox_ways"); // Select all relations containing the nodes or ways into the relation table. LOG.finer("Selecting all relation ids containing selected nodes or ways."); rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_relations ON COMMIT DROP AS" + " SELECT r.* FROM relations r" + " INNER JOIN (" + " SELECT relation_id FROM (" + " SELECT rm.relation_id AS relation_id FROM relation_members rm" + " INNER JOIN bbox_nodes n ON rm.member_id = n.id WHERE rm.member_type = 'N' " + " UNION " + " SELECT rm.relation_id AS relation_id FROM relation_members rm" + " INNER JOIN bbox_ways w ON rm.member_id = w.id WHERE rm.member_type = 'W'" + " ) rids GROUP BY relation_id" + ") rids ON r.id = rids.relation_id" ); LOG.finer(rowCount + " rows affected."); LOG.finer("Adding a primary key to the temporary relations table."); jdbcTemplate.update("ALTER TABLE ONLY bbox_relations ADD CONSTRAINT pk_bbox_relations PRIMARY KEY (id)"); LOG.finer("Updating query analyzer statistics on the temporary relations table."); jdbcTemplate.update("ANALYZE bbox_relations"); // Include all relations containing the current relations into the // relation table and repeat until no more inclusions occur. do { LOG.finer("Selecting parent relations of selected relations."); rowCount = jdbcTemplate.update( "INSERT INTO bbox_relations " + "SELECT r.* FROM relations r INNER JOIN (" + " SELECT rm.relation_id FROM relation_members rm" + " INNER JOIN bbox_relations br ON rm.member_id = br.id" + " WHERE rm.member_type = 'R' AND NOT EXISTS (" + " SELECT * FROM bbox_relations br2 WHERE rm.relation_id = br2.id" + " ) GROUP BY rm.relation_id" + ") rids ON r.id = rids.relation_id" ); LOG.finer(rowCount + " rows affected."); } while (rowCount > 0); LOG.finer("Updating query analyzer statistics on the temporary relations table."); jdbcTemplate.update("ANALYZE bbox_relations"); // If complete ways is set, select all nodes contained by the ways into the node temp table. if (completeWays) { LOG.finer("Selecting all nodes for selected ways."); jdbcTemplate.update("CREATE TEMPORARY TABLE bbox_way_nodes (id bigint) ON COMMIT DROP"); jdbcTemplate.queryForList("SELECT unnest_bbox_way_nodes()"); jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_missing_way_nodes ON COMMIT DROP AS " + "SELECT buwn.id FROM (SELECT DISTINCT bwn.id FROM bbox_way_nodes bwn) buwn " + "WHERE NOT EXISTS (" + " SELECT * FROM bbox_nodes WHERE id = buwn.id" + ");" ); jdbcTemplate.update("ALTER TABLE ONLY bbox_missing_way_nodes" + " ADD CONSTRAINT pk_bbox_missing_way_nodes PRIMARY KEY (id)"); jdbcTemplate.update("ANALYZE bbox_missing_way_nodes"); rowCount = jdbcTemplate.update("INSERT INTO bbox_nodes " + "SELECT n.* FROM nodes n INNER JOIN bbox_missing_way_nodes bwn ON n.id = bwn.id;"); LOG.finer(rowCount + " rows affected."); } LOG.finer("Updating query analyzer statistics on the temporary nodes table."); jdbcTemplate.update("ANALYZE bbox_nodes"); // Create iterators for the selected records for each of the entity types. LOG.finer("Iterating over results."); resultSets = new ArrayList<ReleasableIterator<EntityContainer>>(); resultSets.add( new UpcastIterator<EntityContainer, BoundContainer>( new BoundContainerIterator(new ReleasableAdaptorForIterator<Bound>(bounds.iterator())))); resultSets.add( new UpcastIterator<EntityContainer, NodeContainer>( new NodeContainerIterator(nodeDao.iterate("bbox_")))); resultSets.add( new UpcastIterator<EntityContainer, WayContainer>( new WayContainerIterator(wayDao.iterate("bbox_")))); resultSets.add( new UpcastIterator<EntityContainer, RelationContainer>( new RelationContainerIterator(relationDao.iterate("bbox_")))); // Merge all readers into a single result iterator and return. return new MultipleSourceIterator<EntityContainer>(resultSets); }
public ReleasableIterator<EntityContainer> iterateBoundingBox( double left, double right, double top, double bottom, boolean completeWays) { List<Bound> bounds; Point[] bboxPoints; Polygon bboxPolygon; int rowCount; List<ReleasableIterator<EntityContainer>> resultSets; if (!initialized) { initialize(); } // Build the bounds list. bounds = new ArrayList<Bound>(); bounds.add(new Bound(right, left, top, bottom, "Osmosis " + OsmosisConstants.VERSION)); // PostgreSQL sometimes incorrectly chooses to perform full table scans, these options // prevent this. Note that this is not recommended practice according to documentation // but fixing this would require modifying the table statistics gathering // configuration to produce better plans. jdbcTemplate.update("SET enable_seqscan = false"); jdbcTemplate.update("SET enable_mergejoin = false"); jdbcTemplate.update("SET enable_hashjoin = false"); // Build a polygon representing the bounding box. // Sample box for query testing may be: // GeomFromText('POLYGON((144.93912192855174 -37.82981987499741, // 144.93912192855174 -37.79310006709244, 144.98188026000003 // -37.79310006709244, 144.98188026000003 -37.82981987499741, // 144.93912192855174 -37.82981987499741))', -1) bboxPoints = new Point[5]; bboxPoints[0] = new Point(left, bottom); bboxPoints[1] = new Point(left, top); bboxPoints[2] = new Point(right, top); bboxPoints[3] = new Point(right, bottom); bboxPoints[4] = new Point(left, bottom); bboxPolygon = polygonBuilder.createPolygon(bboxPoints); // Select all nodes inside the box into the node temp table. LOG.finer("Selecting all nodes inside bounding box."); rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_nodes ON COMMIT DROP AS" + " SELECT * FROM nodes WHERE (geom && ?)", new PGgeometry(bboxPolygon)); LOG.finer("Adding a primary key to the temporary nodes table."); jdbcTemplate.update("ALTER TABLE ONLY bbox_nodes ADD CONSTRAINT pk_bbox_nodes PRIMARY KEY (id)"); LOG.finer("Updating query analyzer statistics on the temporary nodes table."); jdbcTemplate.update("ANALYZE bbox_nodes"); // Select all ways inside the bounding box into the way temp table. if (capabilityChecker.isWayLinestringSupported()) { LOG.finer("Selecting all ways inside bounding box using way linestring geometry."); // We have full way geometry available so select ways // overlapping the requested bounding box. rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_ways ON COMMIT DROP AS" + " SELECT * FROM ways WHERE (linestring && ?)", new PGgeometry(bboxPolygon)); } else if (capabilityChecker.isWayBboxSupported()) { LOG.finer("Selecting all ways inside bounding box using dynamically built" + " way linestring with way bbox indexing."); // The inner query selects the way id and node coordinates for // all ways constrained by the way bounding box which is // indexed. // The middle query converts the way node coordinates into // linestrings. // The outer query constrains the query to the linestrings // inside the bounding box. These aren't indexed but the inner // query way bbox constraint will minimise the unnecessary data. rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_ways ON COMMIT DROP AS" + " SELECT w.* FROM (" + "SELECT c.id, c.version, c.user_id, c.tstamp, c.changeset_id, c.tags," + " MakeLine(c.geom) AS way_line FROM (" + "SELECT w.*, n.geom AS geom FROM nodes n" + " INNER JOIN way_nodes wn ON n.id = wn.node_id" + " INNER JOIN ways w ON wn.way_id = w.id" + " WHERE (w.bbox && ?) ORDER BY wn.way_id, wn.sequence_id" + ") c " + "GROUP BY c.id, c.version, c.user_id, c.tstamp, c.changeset_id, c.tags" + ") w " + "WHERE (w.way_line && ?)", new PGgeometry(bboxPolygon), new PGgeometry(bboxPolygon) ); } else { LOG.finer("Selecting all way ids inside bounding box using already selected nodes."); // No way bbox support is available so select ways containing // the selected nodes. rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_ways ON COMMIT DROP AS" + " SELECT w.* FROM ways w" + " INNER JOIN (" + " SELECT wn.way_id FROM way_nodes wn" + " INNER JOIN bbox_nodes n ON wn.node_id = n.id GROUP BY wn.way_id" + ") wids ON w.id = wids.way_id" ); } LOG.finer(rowCount + " rows affected."); LOG.finer("Adding a primary key to the temporary ways table."); jdbcTemplate.update("ALTER TABLE ONLY bbox_ways ADD CONSTRAINT pk_bbox_ways PRIMARY KEY (id)"); LOG.finer("Updating query analyzer statistics on the temporary ways table."); jdbcTemplate.update("ANALYZE bbox_ways"); // Select all relations containing the nodes or ways into the relation table. LOG.finer("Selecting all relation ids containing selected nodes or ways."); rowCount = jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_relations ON COMMIT DROP AS" + " SELECT r.* FROM relations r" + " INNER JOIN (" + " SELECT relation_id FROM (" + " SELECT rm.relation_id AS relation_id FROM relation_members rm" + " INNER JOIN bbox_nodes n ON rm.member_id = n.id WHERE rm.member_type = 'N' " + " UNION " + " SELECT rm.relation_id AS relation_id FROM relation_members rm" + " INNER JOIN bbox_ways w ON rm.member_id = w.id WHERE rm.member_type = 'W'" + " ) rids GROUP BY relation_id" + ") rids ON r.id = rids.relation_id" ); LOG.finer(rowCount + " rows affected."); LOG.finer("Adding a primary key to the temporary relations table."); jdbcTemplate.update("ALTER TABLE ONLY bbox_relations ADD CONSTRAINT pk_bbox_relations PRIMARY KEY (id)"); LOG.finer("Updating query analyzer statistics on the temporary relations table."); jdbcTemplate.update("ANALYZE bbox_relations"); // Include all relations containing the current relations into the // relation table and repeat until no more inclusions occur. do { LOG.finer("Selecting parent relations of selected relations."); rowCount = jdbcTemplate.update( "INSERT INTO bbox_relations " + "SELECT r.* FROM relations r INNER JOIN (" + " SELECT rm.relation_id FROM relation_members rm" + " INNER JOIN bbox_relations br ON rm.member_id = br.id" + " WHERE rm.member_type = 'R' AND NOT EXISTS (" + " SELECT * FROM bbox_relations br2 WHERE rm.relation_id = br2.id" + " ) GROUP BY rm.relation_id" + ") rids ON r.id = rids.relation_id" ); LOG.finer(rowCount + " rows affected."); } while (rowCount > 0); LOG.finer("Updating query analyzer statistics on the temporary relations table."); jdbcTemplate.update("ANALYZE bbox_relations"); // If complete ways is set, select all nodes contained by the ways into the node temp table. if (completeWays) { LOG.finer("Selecting all nodes for selected ways."); jdbcTemplate.update("CREATE TEMPORARY TABLE bbox_way_nodes (id bigint) ON COMMIT DROP"); jdbcTemplate.queryForList("SELECT unnest_bbox_way_nodes()"); jdbcTemplate.update( "CREATE TEMPORARY TABLE bbox_missing_way_nodes ON COMMIT DROP AS " + "SELECT buwn.id FROM (SELECT DISTINCT bwn.id FROM bbox_way_nodes bwn) buwn " + "WHERE NOT EXISTS (" + " SELECT * FROM bbox_nodes WHERE id = buwn.id" + ");" ); jdbcTemplate.update("ALTER TABLE ONLY bbox_missing_way_nodes" + " ADD CONSTRAINT pk_bbox_missing_way_nodes PRIMARY KEY (id)"); jdbcTemplate.update("ANALYZE bbox_missing_way_nodes"); rowCount = jdbcTemplate.update("INSERT INTO bbox_nodes " + "SELECT n.* FROM nodes n INNER JOIN bbox_missing_way_nodes bwn ON n.id = bwn.id;"); LOG.finer(rowCount + " rows affected."); } LOG.finer("Updating query analyzer statistics on the temporary nodes table."); jdbcTemplate.update("ANALYZE bbox_nodes"); // Create iterators for the selected records for each of the entity types. LOG.finer("Iterating over results."); resultSets = new ArrayList<ReleasableIterator<EntityContainer>>(); resultSets.add( new UpcastIterator<EntityContainer, BoundContainer>( new BoundContainerIterator(new ReleasableAdaptorForIterator<Bound>(bounds.iterator())))); resultSets.add( new UpcastIterator<EntityContainer, NodeContainer>( new NodeContainerIterator(nodeDao.iterate("bbox_")))); resultSets.add( new UpcastIterator<EntityContainer, WayContainer>( new WayContainerIterator(wayDao.iterate("bbox_")))); resultSets.add( new UpcastIterator<EntityContainer, RelationContainer>( new RelationContainerIterator(relationDao.iterate("bbox_")))); // Merge all readers into a single result iterator and return. return new MultipleSourceIterator<EntityContainer>(resultSets); }
diff --git a/example/src/edu/mit/mobile/android/content/example/SampleProvider.java b/example/src/edu/mit/mobile/android/content/example/SampleProvider.java index 7ca965e..4c9a8f4 100644 --- a/example/src/edu/mit/mobile/android/content/example/SampleProvider.java +++ b/example/src/edu/mit/mobile/android/content/example/SampleProvider.java @@ -1,80 +1,79 @@ package edu.mit.mobile.android.content.example; import android.content.ContentUris; import edu.mit.mobile.android.content.DBHelper; import edu.mit.mobile.android.content.GenericDBHelper; import edu.mit.mobile.android.content.SimpleContentProvider; /** * <p> * This creates a ContentProvider (which you must define in your * AndroidManifest.xml) that you can use to store all your data. You should only * need one ContentProvider per Application, as each ContentProvider can contain * multiple types of data. * </p> * * <p> * ContentProviders are accessed by querying content:// URIs. These helpers * create URIs for you using the following scheme: * </p> * * <p> * a list of messages: * </p> * * <pre> * content://AUTHORITY/PATH * </pre> * <p> * For this example, that would be: * </p> * * <pre> * content://edu.mit.mobile.android.content.example.sampleprovider/message * </pre> * * <p>To make it easier to query in the future, that URI is stored in {@link Message#CONTENT_URI}.</p> * * <p> * a single message: * </p> * * <pre> * content://AUTHORITY/PATH/# * </pre> * <p> * For this example, that would be: * </p> * * <pre> * content://edu.mit.mobile.android.content.example.sampleprovider/message/3 * </pre> * * <p>URIs of this type can be constructed using {@link ContentUris#withAppendedId(android.net.Uri, long)}.</p> */ public class SampleProvider extends SimpleContentProvider { // Each ContentProvider must have a globally unique authority. You should // specify one here starting from your your Application's package string: public static final String AUTHORITY = "edu.mit.mobile.android.content.example.sampleprovider"; // Every time you update your database schema, you must increment the // database version. private static final int DB_VERSION = 1; public SampleProvider() { super(AUTHORITY, DB_VERSION); // This helper creates the table and can do basic database queries. See // Message for more info. - final DBHelper messageHelper = new GenericDBHelper(Message.class, - Message.CONTENT_URI); + final DBHelper messageHelper = new GenericDBHelper(Message.class); // This adds a mapping between the given content:// URI path and the // helper. addDirAndItemUri(messageHelper, Message.PATH); // the above three statements can be repeated to create multiple data // stores. Each will have separate tables and URIs. } }
true
true
public SampleProvider() { super(AUTHORITY, DB_VERSION); // This helper creates the table and can do basic database queries. See // Message for more info. final DBHelper messageHelper = new GenericDBHelper(Message.class, Message.CONTENT_URI); // This adds a mapping between the given content:// URI path and the // helper. addDirAndItemUri(messageHelper, Message.PATH); // the above three statements can be repeated to create multiple data // stores. Each will have separate tables and URIs. }
public SampleProvider() { super(AUTHORITY, DB_VERSION); // This helper creates the table and can do basic database queries. See // Message for more info. final DBHelper messageHelper = new GenericDBHelper(Message.class); // This adds a mapping between the given content:// URI path and the // helper. addDirAndItemUri(messageHelper, Message.PATH); // the above three statements can be repeated to create multiple data // stores. Each will have separate tables and URIs. }
diff --git a/src/mmb/foss/aueb/icong/DrawableAreaView.java b/src/mmb/foss/aueb/icong/DrawableAreaView.java index f405b03..528283e 100644 --- a/src/mmb/foss/aueb/icong/DrawableAreaView.java +++ b/src/mmb/foss/aueb/icong/DrawableAreaView.java @@ -1,308 +1,308 @@ package mmb.foss.aueb.icong; import java.io.InputStream; import java.util.ArrayList; import mmb.foss.aueb.icong.boxes.Box; import mmb.foss.aueb.icong.boxes.SavedState; import android.content.Context; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class DrawableAreaView extends View { private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); private ArrayList<Box> boxes = new ArrayList<Box>(); private Context mContext; private Box selectedBox = null; private int pressedX, pressedY; private int originalX, originalY; private int[] buttonCenter = new int[2]; private int WIDTH, HEIGHT; private ArrayList<BoxButtonPair[]> lines = new ArrayList<BoxButtonPair[]>(); private Box box = null; private int buttonPressed = -1; private int buttonHovered = -1; private boolean drawingline = false; private boolean foundPair = false; private int lineStartX, lineStartY, lineCurrentX, lineCurrentY; private long tap; private final int DOUBLE_TAP_INTERVAL = (int) (0.3 * 1000); private BitmapDrawable trash; private boolean showTrash; private int trashX, trashY; private Box possibleTrash; public DrawableAreaView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub mContext = context; paint.setColor(Color.BLACK); WIDTH = MainActivity.width; HEIGHT = MainActivity.height; boxes = SavedState.getBoxes(); lines = SavedState.getLines(); } protected void onDraw(Canvas c) { if (WIDTH == 0 || trash == null) { WIDTH = this.getWidth(); HEIGHT = this.getHeight(); InputStream is = mContext.getResources().openRawResource( R.drawable.trash); Bitmap originalBitmap = BitmapFactory.decodeStream(is); int w = WIDTH / 10, h = (w * originalBitmap.getHeight()) / originalBitmap.getWidth(); trash = new BitmapDrawable(mContext.getResources(), Bitmap.createScaledBitmap(originalBitmap, w, h, true)); trashX = (WIDTH - trash.getBitmap().getWidth()) / 2; trashY = HEIGHT - 40; } for (Box box : boxes) { // TODO: Zooming to be removed box.setZoom(1.8); c.drawBitmap(box.getBitmap(), box.getX(), box.getY(), null); for (int i = 0; i < box.getNumOfButtons(); i++) { if (box.isPressed(i)) { buttonCenter = box.getButtonCenter(i); c.drawCircle(buttonCenter[0], buttonCenter[1], box.getButtonRadius(i), paint); } } } for (BoxButtonPair[] line : lines) { Box box0 = line[0].getBox(), box1 = line[1].getBox(); int button0 = line[0].getButton(), button1 = line[1].getButton(); int[] center0 = box0.getButtonCenter(button0), center1 = box1 .getButtonCenter(button1); c.drawLine(center0[0], center0[1], center1[0], center1[1], paint); } if (drawingline) { c.drawLine(lineStartX, lineStartY, lineCurrentX, lineCurrentY, paint); } if (showTrash) { c.drawBitmap(trash.getBitmap(), trashX, trashY, paint); } } public void addBox(Box box) { int x, y; if (mContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { y = getLower() + 15; x = (WIDTH / 2) - (box.getWidth() / 2); } else { y = (HEIGHT / 2) - (box.getHeight() / 2); x = getRighter() + 15; } box.setY(y); box.setX(x); boxes.add(box); SavedState.addBox(box); invalidate(); } public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (showTrash && onTrash(event.getX(), event.getY())) { // if trash icon is visible and clicked delete the possibleTrash // box deleteBox(possibleTrash); possibleTrash = null; } box = getBoxTouched((int) event.getX(), (int) event.getY()); if (box != null) { // if we have touched inside a box selectedBox = box; buttonPressed = box.isButton((int) event.getX(), (int) event.getY()); // TODO double tap implementation long tap = System.currentTimeMillis(); if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) { // if we have double tapped inside a box System.out.println("this is double tap"); } else { System.out.println("this is NOT double tap"); } this.tap = tap; if (buttonPressed == -1) { // if we haven't touched the box's button pressedX = (int) event.getX(); pressedY = (int) event.getY(); originalX = box.getX(); originalY = box.getY(); showTrash = true; possibleTrash = box; } else { // if we have touched the box's button showTrash = false; possibleTrash = null; if (buttonPressed >= box.getNoOfInputs()) { // if button pressed is an output button if (!box.isPressed(buttonPressed)) { // if the button pressed wasn't pressed before box.setButtonPressed(buttonPressed); } else { // if the button pressed was pressed before deletes // this connection/line // FIXME do not delete ALL the lines - removeLines(box); + removeLine(box,buttonPressed); } int[] center = box.getButtonCenter(buttonPressed); lineStartX = center[0]; lineStartY = center[1]; lineCurrentX = lineStartX; lineCurrentY = lineStartY; drawingline = true; } invalidate(); selectedBox = null; } } else { // if we haven't touched inside a box showTrash = false; possibleTrash = null; } break; case MotionEvent.ACTION_MOVE: if (selectedBox != null) { // if we have selected a box by tapping once in it selectedBox.setX((int) event.getX() - (pressedX - originalX)); selectedBox.setY((int) event.getY() - (pressedY - originalY)); invalidate(); } if (drawingline) { // if we have pressed a previously not pressed box's output // button lineCurrentX = (int) event.getX(); lineCurrentY = (int) event.getY(); Box boxHovered = getBoxTouched((int) event.getX(), (int) event.getY()); if (boxHovered != null) { // if we have drawned a line on another box buttonHovered = boxHovered.isButton((int) event.getX(), (int) event.getY()); if (buttonHovered != -1) { // if we have drawned a line on FIXME another's box's // button if (((buttonHovered + 1) <= boxHovered.getNoOfInputs())) { // if we have drawned a line on another's box's // input button int[] center = boxHovered .getButtonCenter(buttonHovered); lineStartX = center[0]; lineStartY = center[1]; boxHovered.setButtonPressed(buttonHovered); drawingline = false; BoxButtonPair[] line = { new BoxButtonPair(box, buttonPressed), new BoxButtonPair(boxHovered, buttonHovered) }; lines.add(line); SavedState.addLine(line); foundPair = true; } } } } invalidate(); break; case MotionEvent.ACTION_UP: drawingline = false; selectedBox = null; // if when drawing a line stops and we haven'd reached another box's // input button then erase the line and unpress the button if (!foundPair && buttonPressed != -1 && box != null) if (!((buttonPressed + 1) <= box.getNoOfInputs())) box.unsetButtonPressed(buttonPressed); foundPair = false; pressedX = pressedY = originalX = originalY = 0; // TODO implement here to pou peftei invalidate(); return false; } return true; } // returns the lower pixel of the lower element private int getLower() { int y = 0; for (Box box : boxes) { if (y < box.getYY()) y = box.getYY(); } return y; } // returns the righter pixel of the righter element private int getRighter() { int x = 0; for (Box box : boxes) { if (x < box.getXX()) x = box.getXX(); } return x; } // returns the box that was touched private Box getBoxTouched(int x, int y) { for (Box b : boxes) { if (b.isOnBox(x, y)) { return b; } } return null; } private boolean onTrash(float f, float g) { boolean isOnTrash = false; if (f >= trashX && f <= (trashX + trash.getBitmap().getWidth()) && g >= trashY && g <= (trashY + trash.getBitmap().getHeight())) { isOnTrash = true; } return isOnTrash; } private void deleteBox(Box box2del) { boxes.remove(box2del); removeLines(box2del); SavedState.removeBox(box2del); } private void removeLine(Box box, int button) { BoxButtonPair pair = new BoxButtonPair(box, button); for (BoxButtonPair[] line : lines) { if (line[0].equals(pair)) { Box otherBox = line[1].getBox(); int otherButton = line[1].getButton(); lines.remove(line); SavedState.removeLine(line); otherBox.unsetButtonPressed(otherButton); break; } else if (line[1].equals(pair)) { Box otherBox = line[0].getBox(); int otherButton = line[0].getButton(); lines.remove(line); SavedState.removeLine(line); otherBox.unsetButtonPressed(otherButton); break; } } } private void removeLines(Box box) { for (int i = 0; i < box.getNumOfButtons(); i++) { removeLine(box, i); } } }
true
true
public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (showTrash && onTrash(event.getX(), event.getY())) { // if trash icon is visible and clicked delete the possibleTrash // box deleteBox(possibleTrash); possibleTrash = null; } box = getBoxTouched((int) event.getX(), (int) event.getY()); if (box != null) { // if we have touched inside a box selectedBox = box; buttonPressed = box.isButton((int) event.getX(), (int) event.getY()); // TODO double tap implementation long tap = System.currentTimeMillis(); if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) { // if we have double tapped inside a box System.out.println("this is double tap"); } else { System.out.println("this is NOT double tap"); } this.tap = tap; if (buttonPressed == -1) { // if we haven't touched the box's button pressedX = (int) event.getX(); pressedY = (int) event.getY(); originalX = box.getX(); originalY = box.getY(); showTrash = true; possibleTrash = box; } else { // if we have touched the box's button showTrash = false; possibleTrash = null; if (buttonPressed >= box.getNoOfInputs()) { // if button pressed is an output button if (!box.isPressed(buttonPressed)) { // if the button pressed wasn't pressed before box.setButtonPressed(buttonPressed); } else { // if the button pressed was pressed before deletes // this connection/line // FIXME do not delete ALL the lines removeLines(box); } int[] center = box.getButtonCenter(buttonPressed); lineStartX = center[0]; lineStartY = center[1]; lineCurrentX = lineStartX; lineCurrentY = lineStartY; drawingline = true; } invalidate(); selectedBox = null; } } else { // if we haven't touched inside a box showTrash = false; possibleTrash = null; } break; case MotionEvent.ACTION_MOVE: if (selectedBox != null) { // if we have selected a box by tapping once in it selectedBox.setX((int) event.getX() - (pressedX - originalX)); selectedBox.setY((int) event.getY() - (pressedY - originalY)); invalidate(); } if (drawingline) { // if we have pressed a previously not pressed box's output // button lineCurrentX = (int) event.getX(); lineCurrentY = (int) event.getY(); Box boxHovered = getBoxTouched((int) event.getX(), (int) event.getY()); if (boxHovered != null) { // if we have drawned a line on another box buttonHovered = boxHovered.isButton((int) event.getX(), (int) event.getY()); if (buttonHovered != -1) { // if we have drawned a line on FIXME another's box's // button if (((buttonHovered + 1) <= boxHovered.getNoOfInputs())) { // if we have drawned a line on another's box's // input button int[] center = boxHovered .getButtonCenter(buttonHovered); lineStartX = center[0]; lineStartY = center[1]; boxHovered.setButtonPressed(buttonHovered); drawingline = false; BoxButtonPair[] line = { new BoxButtonPair(box, buttonPressed), new BoxButtonPair(boxHovered, buttonHovered) }; lines.add(line); SavedState.addLine(line); foundPair = true; } } } } invalidate(); break; case MotionEvent.ACTION_UP: drawingline = false; selectedBox = null; // if when drawing a line stops and we haven'd reached another box's // input button then erase the line and unpress the button if (!foundPair && buttonPressed != -1 && box != null) if (!((buttonPressed + 1) <= box.getNoOfInputs())) box.unsetButtonPressed(buttonPressed); foundPair = false; pressedX = pressedY = originalX = originalY = 0; // TODO implement here to pou peftei invalidate(); return false; } return true; }
public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (showTrash && onTrash(event.getX(), event.getY())) { // if trash icon is visible and clicked delete the possibleTrash // box deleteBox(possibleTrash); possibleTrash = null; } box = getBoxTouched((int) event.getX(), (int) event.getY()); if (box != null) { // if we have touched inside a box selectedBox = box; buttonPressed = box.isButton((int) event.getX(), (int) event.getY()); // TODO double tap implementation long tap = System.currentTimeMillis(); if (System.currentTimeMillis() - this.tap < DOUBLE_TAP_INTERVAL) { // if we have double tapped inside a box System.out.println("this is double tap"); } else { System.out.println("this is NOT double tap"); } this.tap = tap; if (buttonPressed == -1) { // if we haven't touched the box's button pressedX = (int) event.getX(); pressedY = (int) event.getY(); originalX = box.getX(); originalY = box.getY(); showTrash = true; possibleTrash = box; } else { // if we have touched the box's button showTrash = false; possibleTrash = null; if (buttonPressed >= box.getNoOfInputs()) { // if button pressed is an output button if (!box.isPressed(buttonPressed)) { // if the button pressed wasn't pressed before box.setButtonPressed(buttonPressed); } else { // if the button pressed was pressed before deletes // this connection/line // FIXME do not delete ALL the lines removeLine(box,buttonPressed); } int[] center = box.getButtonCenter(buttonPressed); lineStartX = center[0]; lineStartY = center[1]; lineCurrentX = lineStartX; lineCurrentY = lineStartY; drawingline = true; } invalidate(); selectedBox = null; } } else { // if we haven't touched inside a box showTrash = false; possibleTrash = null; } break; case MotionEvent.ACTION_MOVE: if (selectedBox != null) { // if we have selected a box by tapping once in it selectedBox.setX((int) event.getX() - (pressedX - originalX)); selectedBox.setY((int) event.getY() - (pressedY - originalY)); invalidate(); } if (drawingline) { // if we have pressed a previously not pressed box's output // button lineCurrentX = (int) event.getX(); lineCurrentY = (int) event.getY(); Box boxHovered = getBoxTouched((int) event.getX(), (int) event.getY()); if (boxHovered != null) { // if we have drawned a line on another box buttonHovered = boxHovered.isButton((int) event.getX(), (int) event.getY()); if (buttonHovered != -1) { // if we have drawned a line on FIXME another's box's // button if (((buttonHovered + 1) <= boxHovered.getNoOfInputs())) { // if we have drawned a line on another's box's // input button int[] center = boxHovered .getButtonCenter(buttonHovered); lineStartX = center[0]; lineStartY = center[1]; boxHovered.setButtonPressed(buttonHovered); drawingline = false; BoxButtonPair[] line = { new BoxButtonPair(box, buttonPressed), new BoxButtonPair(boxHovered, buttonHovered) }; lines.add(line); SavedState.addLine(line); foundPair = true; } } } } invalidate(); break; case MotionEvent.ACTION_UP: drawingline = false; selectedBox = null; // if when drawing a line stops and we haven'd reached another box's // input button then erase the line and unpress the button if (!foundPair && buttonPressed != -1 && box != null) if (!((buttonPressed + 1) <= box.getNoOfInputs())) box.unsetButtonPressed(buttonPressed); foundPair = false; pressedX = pressedY = originalX = originalY = 0; // TODO implement here to pou peftei invalidate(); return false; } return true; }
diff --git a/impl/dao/src/java/org/sakaiproject/poll/dao/impl/PollVoteManagerDaoImpl.java b/impl/dao/src/java/org/sakaiproject/poll/dao/impl/PollVoteManagerDaoImpl.java index 848f8a9..dc0f52a 100644 --- a/impl/dao/src/java/org/sakaiproject/poll/dao/impl/PollVoteManagerDaoImpl.java +++ b/impl/dao/src/java/org/sakaiproject/poll/dao/impl/PollVoteManagerDaoImpl.java @@ -1,131 +1,131 @@ /********************************************************************************** * $URL: $ * $Id: $ *********************************************************************************** * * Copyright (c) 2006,2007 The Sakai Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.poll.dao.impl; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.hibernate.Query; import org.hibernate.criterion.Distinct; import org.hibernate.Session; import org.sakaiproject.poll.logic.PollVoteManager; import org.sakaiproject.poll.model.Poll; import org.sakaiproject.poll.model.Vote; import org.sakaiproject.user.cover.UserDirectoryService; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.HttpAccess; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.api.ResourceProperties; import org.springframework.dao.DataAccessException; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.tool.cover.ToolManager; import org.w3c.dom.Document; import org.w3c.dom.Element; public class PollVoteManagerDaoImpl extends HibernateDaoSupport implements PollVoteManager { // use commons logger private static Log log = LogFactory.getLog(PollListManagerDaoImpl.class); public boolean saveVote(Vote vote) { try { getHibernateTemplate().save(vote); } catch (DataAccessException e) { log.error("Hibernate could not save: " + e.toString()); e.printStackTrace(); return false; } //Session sess = ; //we need the siteID - log.info(" Vote " + vote.getId() + " successfuly saved"); - EventTrackingService.post(EventTrackingService.newEvent("poll.vote", "poll/site/" + ToolManager.getCurrentPlacement() +"/poll/" + vote.getPollId(), false)); + log.debug(" Vote " + vote.getId() + " successfuly saved"); + EventTrackingService.post(EventTrackingService.newEvent("poll.vote", "poll/site/" + ToolManager.getCurrentPlacement().getContext() +"/poll/" + vote.getPollId(), false)); return true; } public void deleteVote(Vote Vote) { // TODO Auto-generated method stub } public List getAllVotesForPoll(Poll poll) { DetachedCriteria d = DetachedCriteria.forClass(Vote.class) .add( Restrictions.eq("pollId",poll.getPollId()) ); Collection pollCollection = getHibernateTemplate().findByCriteria(d); List votes = new ArrayList(); for (Iterator tit = pollCollection.iterator(); tit.hasNext();) { Vote vote = (Vote) tit.next(); votes.add(vote); } return votes; } public int getDisctinctVotersForPoll(Poll poll) { Query q = null; Session session = getHibernateTemplate().getSessionFactory().getCurrentSession(); String statement = "SELECT DISTINCT VOTE_SUBMISSION_ID from POLL_VOTE where VOTE_POLL_ID = " + poll.getPollId().toString(); q = session.createSQLQuery(statement); List results = q.list(); if (results.size()>0) return results.size(); return 0; } public boolean userHasVoted(Long pollid, String userID) { DetachedCriteria d = DetachedCriteria.forClass(Vote.class) .add( Restrictions.eq("userId",userID) ) .add( Restrictions.eq("pollId",pollid) ); Collection pollCollection = getHibernateTemplate().findByCriteria(d); //System.out.println("got " + pollCollection.size() + "votes for this poll"); if (pollCollection.size()>0) return true; else return false; } public boolean userHasVoted(Long pollId) { return userHasVoted(pollId, UserDirectoryService.getCurrentUser().getId()); } }
true
true
public boolean saveVote(Vote vote) { try { getHibernateTemplate().save(vote); } catch (DataAccessException e) { log.error("Hibernate could not save: " + e.toString()); e.printStackTrace(); return false; } //Session sess = ; //we need the siteID log.info(" Vote " + vote.getId() + " successfuly saved"); EventTrackingService.post(EventTrackingService.newEvent("poll.vote", "poll/site/" + ToolManager.getCurrentPlacement() +"/poll/" + vote.getPollId(), false)); return true; }
public boolean saveVote(Vote vote) { try { getHibernateTemplate().save(vote); } catch (DataAccessException e) { log.error("Hibernate could not save: " + e.toString()); e.printStackTrace(); return false; } //Session sess = ; //we need the siteID log.debug(" Vote " + vote.getId() + " successfuly saved"); EventTrackingService.post(EventTrackingService.newEvent("poll.vote", "poll/site/" + ToolManager.getCurrentPlacement().getContext() +"/poll/" + vote.getPollId(), false)); return true; }
diff --git a/ActivityManagerWebPrivate/ActivityManagerWebPrivate-war/src/java/eas/asu/edu/snac/activitymanager/servlets/RegisterNewUser.java b/ActivityManagerWebPrivate/ActivityManagerWebPrivate-war/src/java/eas/asu/edu/snac/activitymanager/servlets/RegisterNewUser.java index 73f0f53..c887039 100644 --- a/ActivityManagerWebPrivate/ActivityManagerWebPrivate-war/src/java/eas/asu/edu/snac/activitymanager/servlets/RegisterNewUser.java +++ b/ActivityManagerWebPrivate/ActivityManagerWebPrivate-war/src/java/eas/asu/edu/snac/activitymanager/servlets/RegisterNewUser.java @@ -1,159 +1,159 @@ package eas.asu.edu.snac.activitymanager.servlets; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ import eas.asu.edu.snac.activitymanager.networking.MessageSender; import edu.asu.eas.snac.activitymanager.messages.FeedbackMessage; import edu.asu.eas.snac.activitymanager.messages.FeedbackType; import edu.asu.eas.snac.activitymanager.messages.RegisterMessage; import edu.asu.edu.snac.activitymanager.util.Constants; import edu.asu.edu.snac.activitymanager.util.SHA1; import edu.asu.edu.snac.activitymanager.util.Validate; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Fred */ public class RegisterNewUser extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { // Get all the information from the POST/GET header String username = request.getParameter("username"); String password = request.getParameter("password"); String password2 = request.getParameter("password2"); String email = request.getParameter("email"); String phone = request.getParameter("phoneNumber"); - String messageResponse = ""; + StringBuilder messageResponse = new StringBuilder(); boolean isValid = false; // Check if data is valid if (!Validate.Username(username)) { - messageResponse = "Invalid Username"; + messageResponse.append("Invalid Username\n"); } else if (!Validate.Password(password)) { - messageResponse = "Invalid Password"; + messageResponse.append( "Invalid Password\n" ); } else if( !password.equals(password2) ) { - messageResponse = "Passwords do not match!"; + messageResponse.append("Passwords do not match!\n"); } else if( !Validate.Email(email) ) { - messageResponse = "Invalid email address."; + messageResponse.append("Invalid email address.\n"); } else if (!Validate.Phone(phone)) { - messageResponse = "Invalid phone number"; + messageResponse.append("Invalid phone number\n"); } else { isValid = true; } if( isValid ) { // Create registration message and send it RegisterMessage reg = new RegisterMessage(); reg.setUsername(username); reg.setPassword(SHA1.sha1(password)); reg.setEmail(email); reg.setPhone(Validate.StripPhoneNum(phone)); //TODO: I don't know what this is for, ask fredzilla out.println("Phone Number: " + request.getParameter("phoneNumber")); FeedbackMessage fbm = (FeedbackMessage) MessageSender.sendMessage(reg); // TODO: check if fbm returns if (fbm.getMsgType() == FeedbackType.SUCCESS) { request.getSession(true).setAttribute(Constants.LOGGED_IN_TOKEN, username); // Redirect to Main Menu response.sendRedirect("Mobile/Menu.jsp"); } else { //TODO: Send some session variables to acknowledge user response.sendRedirect("Mobile/Register.jsp"); } } else { // Something in the data was not valid out.println("Your Registration Information is bad."); request.getSession().setAttribute("username", username); request.getSession().setAttribute("password", password); request.getSession().setAttribute("email", email); request.getSession().setAttribute("phone", phone); request.getSession().setAttribute("message", messageResponse); response.sendRedirect("InvalidData.jsp"); } } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
false
true
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { // Get all the information from the POST/GET header String username = request.getParameter("username"); String password = request.getParameter("password"); String password2 = request.getParameter("password2"); String email = request.getParameter("email"); String phone = request.getParameter("phoneNumber"); String messageResponse = ""; boolean isValid = false; // Check if data is valid if (!Validate.Username(username)) { messageResponse = "Invalid Username"; } else if (!Validate.Password(password)) { messageResponse = "Invalid Password"; } else if( !password.equals(password2) ) { messageResponse = "Passwords do not match!"; } else if( !Validate.Email(email) ) { messageResponse = "Invalid email address."; } else if (!Validate.Phone(phone)) { messageResponse = "Invalid phone number"; } else { isValid = true; } if( isValid ) { // Create registration message and send it RegisterMessage reg = new RegisterMessage(); reg.setUsername(username); reg.setPassword(SHA1.sha1(password)); reg.setEmail(email); reg.setPhone(Validate.StripPhoneNum(phone)); //TODO: I don't know what this is for, ask fredzilla out.println("Phone Number: " + request.getParameter("phoneNumber")); FeedbackMessage fbm = (FeedbackMessage) MessageSender.sendMessage(reg); // TODO: check if fbm returns if (fbm.getMsgType() == FeedbackType.SUCCESS) { request.getSession(true).setAttribute(Constants.LOGGED_IN_TOKEN, username); // Redirect to Main Menu response.sendRedirect("Mobile/Menu.jsp"); } else { //TODO: Send some session variables to acknowledge user response.sendRedirect("Mobile/Register.jsp"); } } else { // Something in the data was not valid out.println("Your Registration Information is bad."); request.getSession().setAttribute("username", username); request.getSession().setAttribute("password", password); request.getSession().setAttribute("email", email); request.getSession().setAttribute("phone", phone); request.getSession().setAttribute("message", messageResponse); response.sendRedirect("InvalidData.jsp"); } } finally { out.close(); } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { // Get all the information from the POST/GET header String username = request.getParameter("username"); String password = request.getParameter("password"); String password2 = request.getParameter("password2"); String email = request.getParameter("email"); String phone = request.getParameter("phoneNumber"); StringBuilder messageResponse = new StringBuilder(); boolean isValid = false; // Check if data is valid if (!Validate.Username(username)) { messageResponse.append("Invalid Username\n"); } else if (!Validate.Password(password)) { messageResponse.append( "Invalid Password\n" ); } else if( !password.equals(password2) ) { messageResponse.append("Passwords do not match!\n"); } else if( !Validate.Email(email) ) { messageResponse.append("Invalid email address.\n"); } else if (!Validate.Phone(phone)) { messageResponse.append("Invalid phone number\n"); } else { isValid = true; } if( isValid ) { // Create registration message and send it RegisterMessage reg = new RegisterMessage(); reg.setUsername(username); reg.setPassword(SHA1.sha1(password)); reg.setEmail(email); reg.setPhone(Validate.StripPhoneNum(phone)); //TODO: I don't know what this is for, ask fredzilla out.println("Phone Number: " + request.getParameter("phoneNumber")); FeedbackMessage fbm = (FeedbackMessage) MessageSender.sendMessage(reg); // TODO: check if fbm returns if (fbm.getMsgType() == FeedbackType.SUCCESS) { request.getSession(true).setAttribute(Constants.LOGGED_IN_TOKEN, username); // Redirect to Main Menu response.sendRedirect("Mobile/Menu.jsp"); } else { //TODO: Send some session variables to acknowledge user response.sendRedirect("Mobile/Register.jsp"); } } else { // Something in the data was not valid out.println("Your Registration Information is bad."); request.getSession().setAttribute("username", username); request.getSession().setAttribute("password", password); request.getSession().setAttribute("email", email); request.getSession().setAttribute("phone", phone); request.getSession().setAttribute("message", messageResponse); response.sendRedirect("InvalidData.jsp"); } } finally { out.close(); } }
diff --git a/Statics/src/edu/gatech/statics/modes/fbd/FBDChecker.java b/Statics/src/edu/gatech/statics/modes/fbd/FBDChecker.java index 7d2f4d09..186b2afc 100644 --- a/Statics/src/edu/gatech/statics/modes/fbd/FBDChecker.java +++ b/Statics/src/edu/gatech/statics/modes/fbd/FBDChecker.java @@ -1,968 +1,968 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.gatech.statics.modes.fbd; import edu.gatech.statics.application.StaticsApplication; import edu.gatech.statics.exercise.Diagram; import edu.gatech.statics.exercise.Exercise; import edu.gatech.statics.math.Unit; import edu.gatech.statics.math.Vector; import edu.gatech.statics.math.Vector3bd; import edu.gatech.statics.objects.Body; import edu.gatech.statics.objects.Force; import edu.gatech.statics.objects.Connector; import edu.gatech.statics.objects.Load; import edu.gatech.statics.objects.Measurement; import edu.gatech.statics.objects.Moment; import edu.gatech.statics.objects.Point; import edu.gatech.statics.objects.SimulationObject; import edu.gatech.statics.objects.bodies.Cable; import edu.gatech.statics.objects.bodies.TwoForceMember; import edu.gatech.statics.objects.connectors.Connector2ForceMember2d; import edu.gatech.statics.objects.connectors.Fix2d; import edu.gatech.statics.objects.connectors.Pin2d; import edu.gatech.statics.util.Pair; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * * @author Calvin Ashmore */ public class FBDChecker { private FreeBodyDiagram diagram; //private Joint nextJoint; //private boolean done = false; private boolean verbose = true; protected FreeBodyDiagram getDiagram() { return diagram; } public FBDChecker(FreeBodyDiagram diagram) { this.diagram = diagram; } /** * Get all of the symbolic measurements in the schematic, for making sure their names * do are not being used for loads. * @return */ private List<Measurement> getSymbolicMeasurements() { List<Measurement> m = new ArrayList<Measurement>(); for (SimulationObject obj : FreeBodyDiagram.getSchematic().allObjects()) { if (obj instanceof Measurement && ((Measurement) obj).isSymbol()) { m.add((Measurement) obj); } } return m; } /** * The verbose flag lets the checker know whether to report information on failure. * Verbose output will report both information to the logger and to the advice box. * @param enable */ public void setVerbose(boolean enable) { verbose = enable; } /** * Get all the points in the schematic, to check against for force names. * @return */ private List<Point> getAllPoints() { List<Point> m = new ArrayList<Point>(); for (SimulationObject obj : FreeBodyDiagram.getSchematic().allObjects()) { if (obj instanceof Point) { m.add((Point) obj); } } return m; } /** * Get all the loads added to the free body diagram. * @return */ private List<Load> getAddedLoads() { return diagram.getAddedLoads(); /*List<Load> addedForces = new ArrayList<Load>(); for (SimulationObject obj : diagram.allObjects()) { if (!(obj instanceof Load)) { continue; } // this force has been added, and is not a given that could have been selected. addedForces.add((Load) obj); } return addedForces;*/ } /** * Get the given loads that are present in the diagram. * The givens are loads present in the schematic, and should be added to the diagram * by the user in the FBD. Givens are first looked up in the symbol manager to * see if a stored symbol has been used. * @return */ private List<Load> getGivenLoads() { List<Load> givenForces = new ArrayList<Load>(); for (Body body : FreeBodyDiagram.getSchematic().allBodies()) { if (diagram.getBodySubset().getBodies().contains(body)) { for (SimulationObject obj : body.getAttachedObjects()) { if (obj instanceof Load) { Load given = (Load) obj; // attempt to find an equivalent that might have been stored in the symbol manager. Load symbolEquivalent = Exercise.getExercise().getSymbolManager().getLoad(given); if (symbolEquivalent != null) { givenForces.add(symbolEquivalent); } else { givenForces.add(given); } } } } } return givenForces; } private void logInfo(String info) { if (verbose) { Logger.getLogger("Statics").info(info); } } private void setAdviceKey(String key, Object... parameters) { if (verbose) { StaticsApplication.getApp().setAdviceKey(key, parameters); } } public boolean checkDiagram() { //done = false; // step 1: assemble a list of all the forces the user has added. - List<Load> addedLoads = getAddedLoads(); + List<Load> addedLoads = new ArrayList<Load>(getAddedLoads()); logInfo("check: user added loads: " + addedLoads); if (addedLoads.size() <= 0) { logInfo("check: diagram does not contain any loads"); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_add"); return false; } // step 2: for vectors that we can click on and add, ie, given added forces, // make sure that the user has added all of them. for (Load given : getGivenLoads()) { boolean ok = performGivenCheck(addedLoads, given); if (!ok) { return false; } } // step 3: Make sure weights exist, and remove them from our addedForces. for (Body body : diagram.getBodySubset().getBodies()) { if (body.getWeight().getDiagramValue().floatValue() == 0) { continue; } Load weight = new Force( body.getCenterOfMassPoint(), Vector3bd.UNIT_Y.negate(), new BigDecimal(body.getWeight().doubleValue())); boolean ok = performWeightCheck(addedLoads, weight, body); if (!ok) { return false; } } // Step 4: go through all the border connectors connecting this FBD to the external world, // and check each load implied by the connector. for (int i = 0; i < diagram.allObjects().size(); i++) { SimulationObject obj = diagram.allObjects().get(i); if (!(obj instanceof Connector)) { continue; } Connector connector = (Connector) obj; // find the body in this diagram to which the connector is attached. Body body = null; if (diagram.allBodies().contains(connector.getBody1())) { body = connector.getBody1(); } if (diagram.allBodies().contains(connector.getBody2())) { body = connector.getBody2(); } // ^ is java's XOR operator // we want the joint IF it connects a body in the body list // to a body that is not in the body list. This means xor. if (!(diagram.getBodySubset().getBodies().contains(connector.getBody1()) ^ diagram.getBodySubset().getBodies().contains(connector.getBody2()))) { continue; } // build a list of the loads at this point List<Load> userLoadsAtConnector = new ArrayList<Load>(); for (Load load : addedLoads) { if (load.getAnchor().equals(connector.getAnchor())) { userLoadsAtConnector.add(load); } } logInfo("check: testing connector: " + connector); // special case, userLoadsAtConnector is empty: if (userLoadsAtConnector.isEmpty()) { logInfo("check: have any forces been added"); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_reaction", connector.connectorName(), connector.getAnchor().getLabelText()); return false; } // //this is trying to make sure two force members have the same values at either end // if (body instanceof TwoForceMember) { // List<Load> userLoadsAtOtherConnector = new ArrayList<Load>(); // Connector con; // if (((TwoForceMember) body).getConnector1() == connector) { // con = ((TwoForceMember) body).getConnector2(); // } else { // con = ((TwoForceMember) body).getConnector1(); // } // for (Load load : addedLoads) { // if (load.getAnchor().equals(con.getAnchor())) { // userLoadsAtOtherConnector.add(load); // } // } // if (!userLoadsAtConnector.get(0).getLabelText().equalsIgnoreCase(userLoadsAtOtherConnector.get(0).getLabelText())) { // logInfo("check: the user has given a 2ForceMember's loads different values"); // logInfo("check: FAILED"); // setAdviceKey("fbd_feedback_check_fail_2force_not_same"); // return false; // } // } ConnectorCheckResult connectorResult = checkConnector(userLoadsAtConnector, connector, body); switch (connectorResult) { case passed: // okay, the check passed without complaint. // The loads may still not be correct, but that will be tested afterwards. // for now, continue normally. break; case inappropriateDirection: // check for special case of 2FM: logInfo("check: User added loads at " + connector.getAnchor().getName() + ": " + userLoadsAtConnector); logInfo("check: Was expecting: " + getReactionLoads(connector, connector.getReactions(body))); if (connector instanceof Connector2ForceMember2d) { Connector2ForceMember2d connector2fm = (Connector2ForceMember2d) connector; if (connector2fm.getMember() instanceof Cable) { // special message for cables: logInfo("check: user created a cable in compression at point " + connector.getAnchor().getName()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_cable", connector.getAnchor().getName(), connector2fm.getMember()); return false; } } else { // one of the directions is the wrong way, and it's not a cable this time // it is probably a roller or something. logInfo("check: loads have wrong direction at point " + connector.getAnchor().getName()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_some_reverse", connector.getAnchor().getName()); return false; } case somethingExtra: // this particular check could be fine // in some problems there are multiple connectors at one point (notably in frame problems) // and this means that extra loads are okay. We check to see if multiple connectors are present, // and if so, continue gracefully, as inapporpriate extra things will be checked at the end // otherwise the check will continue to the next step, "missingSomething" where other conditions // will be tested. if (diagram.getConnectorsAtPoint(connector.getAnchor()).size() > 1) { // continue on. break; } case missingSomething: // okay, if we are here then either something is missing, or something is extra. // check against pins or rollers and see what happens. logInfo("check: User added loads at " + connector.getAnchor().getName() + ": " + userLoadsAtConnector); logInfo("check: Was expecting: " + getReactionLoads(connector, connector.getReactions(body))); // check if this is mistaken for a pin if (!connector.connectorName().equals("pin")) { Pin2d testPin = new Pin2d(connector.getAnchor()); if (checkConnector(userLoadsAtConnector, testPin, null) == ConnectorCheckResult.passed) { logInfo("check: user wrongly created a pin at point " + connector.getAnchor().getLabelText()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "pin", connector.connectorName()); return false; } } // check if this is mistaken for a fix if (!connector.connectorName().equals("fix")) { Fix2d testFix = new Fix2d(connector.getAnchor()); if (checkConnector(userLoadsAtConnector, testFix, null) == ConnectorCheckResult.passed) { logInfo("check: user wrongly created a fix at point " + connector.getAnchor().getLabelText()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "fix", connector.connectorName()); return false; } } // otherwise, the user did something strange. logInfo("check: user simply added reactions to a joint that don't make sense to point " + connector.getAnchor().getLabelText()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_wrong", connector.connectorName(), connector.getAnchor().getLabelText()); return false; } // okay, now the connector test has passed. // We know now that the loads present in the diagram satisfy the reactions for the connector. // All reactions loads are necessarily symbolic, and thus will either be new symbols, or // they will be present in the symbol manager. List<Load> expectedReactions = getReactionLoads(connector, connector.getReactions(body)); for (Load reaction : expectedReactions) { // get a load and result corresponding to this check. Load loadFromSymbolManager = Exercise.getExercise().getSymbolManager().getLoad(reaction); if (loadFromSymbolManager != null) { // make sure the directions are pointing the correct way: if (reaction.getVectorValue().equals(loadFromSymbolManager.getVectorValue().negate())) { loadFromSymbolManager = loadFromSymbolManager.clone(); loadFromSymbolManager.getVectorValue().negateLocal(); } // of the user loads, only check those which point in maybe the right direction List<Load> userLoadsAtConnectorInDirection = new ArrayList<Load>(); for (Load load : userLoadsAtConnector) { if (load.getVectorValue().equals(reaction.getVectorValue()) || load.getVectorValue().equals(reaction.getVectorValue().negate())) { userLoadsAtConnectorInDirection.add(load); } } Pair<Load, LoadCheckResult> result = checkAllCandidatesAgainstTarget( userLoadsAtConnectorInDirection, loadFromSymbolManager); Load candidate = result.getLeft(); // this load has been solved for already. Now we can check against it. if (result.getRight() == LoadCheckResult.passed) { // check is OK, we can remove the load from our addedLoads. addedLoads.remove(candidate); } else { complainAboutLoadCheck(result.getRight(), candidate); return false; } } else { // this load is new, so it requires a name check. // let's find a load that seems to match the expected reaction. Load candidate = null; for (Load possibleCandidate : userLoadsAtConnector) { // we know that these all are at the right anchor, so only test direction. // direction may also be negated, since these are new symbols. if (possibleCandidate.getVectorValue().equals(reaction.getVectorValue()) || possibleCandidate.getVectorValue().equals(reaction.getVectorValue().negate())) { candidate = possibleCandidate; } } // candidate should not be null at this point since the main test passed. NameCheckResult nameResult; if (connector instanceof Connector2ForceMember2d) { nameResult = checkLoadName2FM(candidate, (Connector2ForceMember2d) connector); } else { nameResult = checkLoadName(candidate); } if (nameResult == NameCheckResult.passed) { // we're okay!! addedLoads.remove(candidate); } else { complainAboutName(nameResult, candidate); return false; } } } } // Step 5: Make sure we've used all the user added forces. if (!addedLoads.isEmpty()) { logInfo("check: user added more forces than necessary: " + addedLoads); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_additional", addedLoads.get(0).getAnchor().getName()); return false; } // Step 6: Verify labels // verify that all unknowns are symbols // these are reaction forces and moments // knowns should not be symbols: externals, weights // symbols must also not be repeated, unless this is valid somehow? (not yet) // Yay, we've passed the test! logInfo("check: PASSED!"); return true; } /** * Checks against a given load. * The check removes the candidate from addedLoads if the check passes. * @param addedLoads * @param given * @return */ protected boolean performGivenCheck(List<Load> addedLoads, Load given) { List<Load> candidates = getCandidates(addedLoads, given, given.isSymbol() && !given.isKnown()); // try all candidates // realistically there should only be one, but this check tries to be secure. Pair<Load, LoadCheckResult> result = checkAllCandidatesAgainstTarget(candidates, given); // we have no candidates, so terminate. if (result.getRight() == null) { //user has forgotten to add a given load logInfo("check: diagram does not contain given load " + given); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_given", given.getAnchor().getLabelText()); return false; } Load candidate = result.getLeft(); // report failures switch (result.getRight()) { case passed: // Our test has passed, we can continue. addedLoads.remove(candidate); break; case shouldNotBeNumeric: //A given value that should be symbolic has been added as numeric logInfo("check: external value should be a symbol at point" + given.getAnchor().getLabelText()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_given_symbol", candidate.getLabelText(), candidate.getAnchor().getLabelText()); return false; case shouldNotBeSymbol: //A given value that should be numeric has been added as symbolic logInfo("check: external value should be a numeric at point" + given.getAnchor().getLabelText()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_given_number", candidate.getLabelText(), candidate.getAnchor().getLabelText()); return false; case wrongSymbol: // user has given a symbol that does not match the symbol of the given load. // this is generally okay, but we want there to be consistency if the user has already put a name down. if (Exercise.getExercise().getSymbolManager().getLoad(candidate) == null) { // we're okay addedLoads.remove(candidate); break; } default: complainAboutLoadCheck(result.getRight(), candidate); return false; } // user candidate is a symbolic value if (candidate.isSymbol() && Exercise.getExercise().getSymbolManager().getLoad(candidate) == null) { NameCheckResult nameResult = checkLoadName(candidate); if (nameResult != NameCheckResult.passed) { complainAboutName(nameResult, candidate); return false; } } return true; } /** * Checks against a weight. This method is very similar to the Given check, * but uses different log and feedback messages. A good way to do the check might be to abstract them out, * but the difference is kind of immaterial at this point. * The check removes the candidate from addedLoads if the check passes. * @param addedLoads * @param given * @return */ protected boolean performWeightCheck(List<Load> addedLoads, Load weight, Body body) { List<Load> candidates = getCandidates(addedLoads, weight, weight.isSymbol() && !weight.isKnown()); // try all candidates // realistically there should only be one, but this check tries to be secure. Pair<Load, LoadCheckResult> result = checkAllCandidatesAgainstTarget(candidates, weight); // we have no candidates, so terminate. if (result.getRight() == null) { // weight does not exist in system. logInfo("check: diagram does not contain weight for " + body); logInfo("check: weight is: " + weight); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_weight", body.getName()); return false; } Load candidate = result.getLeft(); // report failures switch (result.getRight()) { case passed: // Our test has passed, we can continue. addedLoads.remove(candidate); break; case shouldNotBeNumeric: //A given value that should be symbolic has been added as numeric logInfo("check: weight should be a symbol at point" + weight.getAnchor().getName()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_weight_symbol", body.getName()); return false; case shouldNotBeSymbol: //A given value that should be numeric has been added as symbolic logInfo("check: weight should be numeric at point" + weight.getAnchor().getName()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_weight_number", body.getName()); return false; case wrongNumericValue: // wrong numeric value logInfo("check: diagram contains incorrect weight " + weight); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_weight_value", body.getName()); return false; default: complainAboutLoadCheck(result.getRight(), candidate); return false; } // user candidate is a symbolic value if (candidate.isSymbol() && Exercise.getExercise().getSymbolManager().getLoad(candidate) == null) { NameCheckResult nameResult = checkLoadName(candidate); if (nameResult != NameCheckResult.passed) { complainAboutName(nameResult, candidate); return false; } } return true; } private void complainAboutLoadCheck(LoadCheckResult result, Load candidate) { switch (result) { case shouldNotBeNumeric: logInfo("check: force should not be numeric: " + candidate); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_numeric", forceOrMoment(candidate), candidate.getLabelText(), candidate.getAnchor().getName()); return; case shouldNotBeSymbol: logInfo("check: force should not be symbol: " + candidate); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_symbol", forceOrMoment(candidate), candidate.getAnchor().getLabelText(), candidate.getAnchor().getName()); return; case wrongNumericValue: logInfo("check: numeric values do not match: " + candidate); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_not_same_number", forceOrMoment(candidate), candidate.getLabelText(), candidate.getAnchor().getName()); return; case wrongDirection: logInfo("check: load is pointing the wrong direction: " + candidate); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_reverse", forceOrMoment(candidate), candidate.getLabelText(), candidate.getAnchor().getName()); return; case wrongSymbol: //the student has created a load with a name that doesn't match its opposing force logInfo("check: load should equal its opposite: " + candidate); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_not_same_symbol", forceOrMoment(candidate), candidate.getLabelText(), candidate.getAnchor().getName()); return; } } private void complainAboutName(NameCheckResult result, Load candidate) { switch (result) { case duplicateInThisDiagram: case matchesSymbolElsewhere: logInfo("check: forces and moments should not have the same name as any other force or moment: " + candidate); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_duplicate", forceOrMoment(candidate), candidate.getAnchor().getLabelText()); return; case matchesMeasurementSymbol: logInfo("check: force or moment should not share the same name with an unknown measurement "); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_duplicate_measurement", forceOrMoment(candidate), candidate.getAnchor().getLabelText()); return; case matchesPointName: logInfo("check: anchors and added force/moments should not share names"); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_duplicate_anchor", forceOrMoment(candidate), candidate.getAnchor().getLabelText()); return; case shouldMatch2FM: //the student has created a 2FM with non matching forces logInfo("check: forces on a 2FM need to have the same name: " + candidate); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_2force_not_same"); return; } } /** * Return a negated version of the given load. The negated version is equal to * the given reaction only in that it exists at the same anchor and has the same vector value. * It does not necessarily have the same value stored for its symbol or known flag. * @param reaction * @return */ private Load negate(Load reaction) { if (reaction instanceof Force) { return new Force(reaction.getAnchor(), reaction.getVector().negate()); } else if (reaction instanceof Moment) { return new Moment(reaction.getAnchor(), reaction.getVector().negate()); } else { // ignore this case return null; } } protected enum NameCheckResult { passed, // passed, no conficts matchesSymbolElsewhere, // same as a symbolic load from another diagram matchesPointName, // same as the name for a point matchesMeasurementSymbol, // same as a symbol used in an unknown measurement duplicateInThisDiagram, // two loads incorrectly have the same name in this diagram shouldMatch2FM // the opposing forces of a 2FM should match } /** * This check makes sure this load has a suitable name. The given candidate * must be a symbolic load. * This check is intended for loads which have *not yet* been added to the symbol manager. * This check will go through and make sure the name does not coincide with that of a point or * a different load in this diagram or in other diagrams. A special case must be * made with Two Force Members, and for these it is necessary to use checkLoadName2FM(). * @param candidate * @return */ protected NameCheckResult checkLoadName(Load candidate) { String name = candidate.getSymbolName(); for (SimulationObject obj : Diagram.getSchematic().allObjects()) { // look through simulation objects to find name conflicts // first look at measurements if (obj instanceof Measurement) { Measurement measure = (Measurement) obj; if (measure.isSymbol() && measure.getSymbolName().equalsIgnoreCase(name)) { return NameCheckResult.matchesMeasurementSymbol; } } // then points if (obj instanceof Point) { if (name.equalsIgnoreCase(obj.getName())) { return NameCheckResult.matchesPointName; } } } // look through other symbols stored in the symbol manager if (Exercise.getExercise().getSymbolManager().getSymbols().contains(name)) { //the name exists elsewhere in the fbd return NameCheckResult.matchesSymbolElsewhere; } // now look through other loads in this diagram. for (SimulationObject obj : diagram.allObjects()) { if (obj instanceof Load && obj != candidate) { Load load = (Load) obj; if (candidate.getSymbolName().equalsIgnoreCase(load.getSymbolName())) { return NameCheckResult.duplicateInThisDiagram; } } } return NameCheckResult.passed; } /** * This is an extension of the checkLoadName() method, which applies specifically * to loads which are reactions to Two Force Members. This method assumes that the candidate provided is * actually the reaction force to the 2fm. * @param candidate * @param connector * @return */ protected NameCheckResult checkLoadName2FM(Load candidate, Connector2ForceMember2d connector) { NameCheckResult result = checkLoadName(candidate); //if we passed, which we usually want, this means that the loads' labels //do not match, which is bad if (result == NameCheckResult.passed) { return NameCheckResult.shouldMatch2FM; } // if the result of the standard check is anything but "there is a duplicate in this diagram" // then we can return that result. We are only interested in the case where there // might be a second load with the same name, which implies a duplicate. if (result != NameCheckResult.duplicateInThisDiagram) { return result; } TwoForceMember member = connector.getMember(); if (!diagram.allBodies().contains(member)) { return result; } Connector2ForceMember2d otherConnector; if (member.getConnector1() == connector) { otherConnector = member.getConnector2(); } else if (member.getConnector2() == connector) { otherConnector = member.getConnector1(); } else { // shouldn't get here, but fail gracefully return result; } // get the other load that satisfies the reactions of the otherConnector List<Load> loadsAtOtherReaction = diagram.getLoadsAtPoint(otherConnector.getAnchor()); List<Load> otherConnectorReactions = getReactionLoads(connector, otherConnector.getReactions()); Load otherReactionTarget = otherConnectorReactions.get(0); Load otherReaction = null; // iterate through the list and look for the one that should do it. // we want to find something that could be a reaction on the other end of the 2fm, // and we want it to match the name of our current load. for (Load otherLoad : loadsAtOtherReaction) { if (otherLoad.getVectorValue().equals(otherReactionTarget.getVectorValue()) || otherLoad.getVectorValue().equals(otherReactionTarget.getVectorValue().negate())) { if (candidate.getSymbolName().equalsIgnoreCase(otherLoad.getSymbolName())) { otherReaction = otherLoad; } } } // okay, we found it. That means that this load should have an appropriate name. // in the case that there is some case that is invalid and escapes the above, it should // be caught by other parts of the check (for instance, if the user was especially // difficult and put two reactions at one end of a 2fm or something like that) if (otherReaction != null) { return NameCheckResult.passed; } return result; } /** * Attempts to find a load from a pool of possibilities which might match the target. * The search will search for loads that are the same type, are at the same point, and * point in the same direction as the target, or the opposite direction, if the * testOpposites flag is checked. * @param searchPool * @param target * @param testOpposites * @return */ protected List<Load> getCandidates(List<Load> searchPool, Load target, boolean testOpposites) { List<Load> candidates = new ArrayList<Load>(); for (Load load : searchPool) { // make sure types are the same if (load.getClass() != target.getClass()) { continue; } // make sure the anchor is the same if (!load.getAnchor().equals(target.getAnchor())) { continue; } // add if direction is the same, or is opposite and the testOpposites flag is set if (load.getVectorValue().equals(target.getVectorValue()) || (testOpposites && load.getVectorValue().negate().equals(target.getVectorValue()))) { candidates.add(load); } } return candidates; } /** * This is a result that is returned when a load is checked against some stored version. * This works when checking against a given, a weight, or a stored symbolic load. */ protected enum LoadCheckResult { passed, //check passes wrongDirection, // occurs when solved value is in wrong direction wrongSymbol, // symbol is stored, this should change its symbol wrongNumericValue, // number is stored, user put in wrong value shouldNotBeSymbol, // store is numeric shouldNotBeNumeric // store is symbolic } /** * Like checkLoadAgainstTarget() this method aims to check whether a load matches the * target. However, this method checks against a collection of candidates, rather than just one. * @param candidates * @param target * @return */ protected Pair<Load, LoadCheckResult> checkAllCandidatesAgainstTarget(List<Load> candidates, Load target) { LoadCheckResult result = null; Load lastCandidate = null; for (Load candidate : candidates) { lastCandidate = candidate; result = checkLoadAgainstTarget(candidate, target); if (result == LoadCheckResult.passed) { return new Pair<Load, LoadCheckResult>(candidate, result); } } return new Pair<Load, LoadCheckResult>(lastCandidate, result); } /** * Returns a result indicating whether the candidate sufficiently matches the target provided. * Target can be a stored symbolic load, a given, or a weight. The target could be known, symbolic, numeric, * or what-have-you. The goal of this check is to abstract out some of the detailed checks making sure * that candidates are named or valud appropriately and pointing the right direction given * other information that might be known about other diagrams. * @param candidate * @param target * @return */ protected LoadCheckResult checkLoadAgainstTarget(Load candidate, Load target) { if (target.isKnown()) { // target is a known load // the numeric value must be correct, and the direction must be correct. if (!candidate.isKnown()) { // candidate is not known, so complain. return LoadCheckResult.shouldNotBeSymbol; } if (!candidate.getDiagramValue().equals(target.getDiagramValue())) { // the numeric values are off. return LoadCheckResult.wrongNumericValue; } if (!candidate.getVectorValue().equals(target.getVectorValue())) { // pointing the wrong way return LoadCheckResult.wrongDirection; } // this is sufficient for the load to be correct return LoadCheckResult.passed; } else { // target is unknown, it must be symbolic // the symbol must be correct if (candidate.isKnown()) { // candidate is not symbolic, so complain return LoadCheckResult.shouldNotBeNumeric; } if (!candidate.getSymbolName().equalsIgnoreCase(target.getSymbolName())) { // candidate has the wrong symbol name return LoadCheckResult.wrongSymbol; } // we should be okay now. return LoadCheckResult.passed; } } /** * This is a result of a check of a connector. This returns *no* information about * whether the loads are appropriately valued or named, it merely returns information regarding whether * the loads provided could work for the connector. */ protected enum ConnectorCheckResult { passed, // ok missingSomething, // some reaction is missing from the candidates somethingExtra, // the candidates have an extra force that is not necessary inappropriateDirection, // one or more of the candidates is the wrong direction for the connector // (ie, in a 2 force member, or in a roller) } /** * Checks to see whether candidateLoads, the list of loads provided, is a suitable match for * the reactions of the given connector. This does not check if the loads are named or have * the correct names or symbols. This check assumes that all candidateLoads are on the connector's anchor. * The method will return ConnectorCheckResult.somethingExtra if everything is okay except for there being more * loads than expected. Sometimes, this is okay, for instance if there are more than one connector at a point. * The check method itself is responsible for identifying these situations and handling them appropriately. * @param cadidateLoads * @param connector * @param localBody * @return */ protected ConnectorCheckResult checkConnector(List<Load> candidateLoads, Connector connector, Body localBody) { List<Vector> reactions; if (localBody == null) { reactions = connector.getReactions(); } else { reactions = connector.getReactions(localBody); } List<Load> reactionLoads = getReactionLoads(connector, reactions); boolean negatable = connector.isForceDirectionNegatable(); for (Load reaction : reactionLoads) { // check each reaction load to make sure it is present and proper List<Load> candidates = getCandidates(candidateLoads, reaction, negatable); if (candidates.isEmpty()) { // okay, this one is missing, which is bad. if (!negatable && !getCandidates(candidateLoads, reaction, true).isEmpty()) { // candidates allowing negation is not empty, meaning that user is adding // a load in the wrong direction return ConnectorCheckResult.inappropriateDirection; } return ConnectorCheckResult.missingSomething; } } // okay, all reactions are accounted for. // if our list of candidateLoads is larger, then there may be a problem if (candidateLoads.size() > reactionLoads.size()) { return ConnectorCheckResult.somethingExtra; } // otherwise, we're okay. return ConnectorCheckResult.passed; } /** * Returns the reactions present from a connector as Loads instead of Vectors. * This returns a fresh new list, so it does no harm to remove loads from it. * @param joint * @param reactions * @return */ private List<Load> getReactionLoads(Connector joint, List<Vector> reactions) { List<Load> loads = new ArrayList<Load>(); for (Vector vector : reactions) { if (vector.getUnit() == Unit.force) { loads.add(new Force(joint.getAnchor(), vector)); } else if (vector.getUnit() == Unit.moment) { loads.add(new Moment(joint.getAnchor(), vector)); } } return loads; } /** * Returns a string denoting whether the given load is a force or moment. * Simply returns "force" if the load is a Force, and "moment" if the load is a Moment. * @param load * @return */ private String forceOrMoment(Load load) { if (load instanceof Force) { return "force"; } else if (load instanceof Moment) { return "moment"; } else { return "unknown?"; } } }
true
true
public boolean checkDiagram() { //done = false; // step 1: assemble a list of all the forces the user has added. List<Load> addedLoads = getAddedLoads(); logInfo("check: user added loads: " + addedLoads); if (addedLoads.size() <= 0) { logInfo("check: diagram does not contain any loads"); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_add"); return false; } // step 2: for vectors that we can click on and add, ie, given added forces, // make sure that the user has added all of them. for (Load given : getGivenLoads()) { boolean ok = performGivenCheck(addedLoads, given); if (!ok) { return false; } } // step 3: Make sure weights exist, and remove them from our addedForces. for (Body body : diagram.getBodySubset().getBodies()) { if (body.getWeight().getDiagramValue().floatValue() == 0) { continue; } Load weight = new Force( body.getCenterOfMassPoint(), Vector3bd.UNIT_Y.negate(), new BigDecimal(body.getWeight().doubleValue())); boolean ok = performWeightCheck(addedLoads, weight, body); if (!ok) { return false; } } // Step 4: go through all the border connectors connecting this FBD to the external world, // and check each load implied by the connector. for (int i = 0; i < diagram.allObjects().size(); i++) { SimulationObject obj = diagram.allObjects().get(i); if (!(obj instanceof Connector)) { continue; } Connector connector = (Connector) obj; // find the body in this diagram to which the connector is attached. Body body = null; if (diagram.allBodies().contains(connector.getBody1())) { body = connector.getBody1(); } if (diagram.allBodies().contains(connector.getBody2())) { body = connector.getBody2(); } // ^ is java's XOR operator // we want the joint IF it connects a body in the body list // to a body that is not in the body list. This means xor. if (!(diagram.getBodySubset().getBodies().contains(connector.getBody1()) ^ diagram.getBodySubset().getBodies().contains(connector.getBody2()))) { continue; } // build a list of the loads at this point List<Load> userLoadsAtConnector = new ArrayList<Load>(); for (Load load : addedLoads) { if (load.getAnchor().equals(connector.getAnchor())) { userLoadsAtConnector.add(load); } } logInfo("check: testing connector: " + connector); // special case, userLoadsAtConnector is empty: if (userLoadsAtConnector.isEmpty()) { logInfo("check: have any forces been added"); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_reaction", connector.connectorName(), connector.getAnchor().getLabelText()); return false; } // //this is trying to make sure two force members have the same values at either end // if (body instanceof TwoForceMember) { // List<Load> userLoadsAtOtherConnector = new ArrayList<Load>(); // Connector con; // if (((TwoForceMember) body).getConnector1() == connector) { // con = ((TwoForceMember) body).getConnector2(); // } else { // con = ((TwoForceMember) body).getConnector1(); // } // for (Load load : addedLoads) { // if (load.getAnchor().equals(con.getAnchor())) { // userLoadsAtOtherConnector.add(load); // } // } // if (!userLoadsAtConnector.get(0).getLabelText().equalsIgnoreCase(userLoadsAtOtherConnector.get(0).getLabelText())) { // logInfo("check: the user has given a 2ForceMember's loads different values"); // logInfo("check: FAILED"); // setAdviceKey("fbd_feedback_check_fail_2force_not_same"); // return false; // } // } ConnectorCheckResult connectorResult = checkConnector(userLoadsAtConnector, connector, body); switch (connectorResult) { case passed: // okay, the check passed without complaint. // The loads may still not be correct, but that will be tested afterwards. // for now, continue normally. break; case inappropriateDirection: // check for special case of 2FM: logInfo("check: User added loads at " + connector.getAnchor().getName() + ": " + userLoadsAtConnector); logInfo("check: Was expecting: " + getReactionLoads(connector, connector.getReactions(body))); if (connector instanceof Connector2ForceMember2d) { Connector2ForceMember2d connector2fm = (Connector2ForceMember2d) connector; if (connector2fm.getMember() instanceof Cable) { // special message for cables: logInfo("check: user created a cable in compression at point " + connector.getAnchor().getName()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_cable", connector.getAnchor().getName(), connector2fm.getMember()); return false; } } else { // one of the directions is the wrong way, and it's not a cable this time // it is probably a roller or something. logInfo("check: loads have wrong direction at point " + connector.getAnchor().getName()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_some_reverse", connector.getAnchor().getName()); return false; } case somethingExtra: // this particular check could be fine // in some problems there are multiple connectors at one point (notably in frame problems) // and this means that extra loads are okay. We check to see if multiple connectors are present, // and if so, continue gracefully, as inapporpriate extra things will be checked at the end // otherwise the check will continue to the next step, "missingSomething" where other conditions // will be tested. if (diagram.getConnectorsAtPoint(connector.getAnchor()).size() > 1) { // continue on. break; } case missingSomething: // okay, if we are here then either something is missing, or something is extra. // check against pins or rollers and see what happens. logInfo("check: User added loads at " + connector.getAnchor().getName() + ": " + userLoadsAtConnector); logInfo("check: Was expecting: " + getReactionLoads(connector, connector.getReactions(body))); // check if this is mistaken for a pin if (!connector.connectorName().equals("pin")) { Pin2d testPin = new Pin2d(connector.getAnchor()); if (checkConnector(userLoadsAtConnector, testPin, null) == ConnectorCheckResult.passed) { logInfo("check: user wrongly created a pin at point " + connector.getAnchor().getLabelText()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "pin", connector.connectorName()); return false; } } // check if this is mistaken for a fix if (!connector.connectorName().equals("fix")) { Fix2d testFix = new Fix2d(connector.getAnchor()); if (checkConnector(userLoadsAtConnector, testFix, null) == ConnectorCheckResult.passed) { logInfo("check: user wrongly created a fix at point " + connector.getAnchor().getLabelText()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "fix", connector.connectorName()); return false; } } // otherwise, the user did something strange. logInfo("check: user simply added reactions to a joint that don't make sense to point " + connector.getAnchor().getLabelText()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_wrong", connector.connectorName(), connector.getAnchor().getLabelText()); return false; } // okay, now the connector test has passed. // We know now that the loads present in the diagram satisfy the reactions for the connector. // All reactions loads are necessarily symbolic, and thus will either be new symbols, or // they will be present in the symbol manager. List<Load> expectedReactions = getReactionLoads(connector, connector.getReactions(body)); for (Load reaction : expectedReactions) { // get a load and result corresponding to this check. Load loadFromSymbolManager = Exercise.getExercise().getSymbolManager().getLoad(reaction); if (loadFromSymbolManager != null) { // make sure the directions are pointing the correct way: if (reaction.getVectorValue().equals(loadFromSymbolManager.getVectorValue().negate())) { loadFromSymbolManager = loadFromSymbolManager.clone(); loadFromSymbolManager.getVectorValue().negateLocal(); } // of the user loads, only check those which point in maybe the right direction List<Load> userLoadsAtConnectorInDirection = new ArrayList<Load>(); for (Load load : userLoadsAtConnector) { if (load.getVectorValue().equals(reaction.getVectorValue()) || load.getVectorValue().equals(reaction.getVectorValue().negate())) { userLoadsAtConnectorInDirection.add(load); } } Pair<Load, LoadCheckResult> result = checkAllCandidatesAgainstTarget( userLoadsAtConnectorInDirection, loadFromSymbolManager); Load candidate = result.getLeft(); // this load has been solved for already. Now we can check against it. if (result.getRight() == LoadCheckResult.passed) { // check is OK, we can remove the load from our addedLoads. addedLoads.remove(candidate); } else { complainAboutLoadCheck(result.getRight(), candidate); return false; } } else { // this load is new, so it requires a name check. // let's find a load that seems to match the expected reaction. Load candidate = null; for (Load possibleCandidate : userLoadsAtConnector) { // we know that these all are at the right anchor, so only test direction. // direction may also be negated, since these are new symbols. if (possibleCandidate.getVectorValue().equals(reaction.getVectorValue()) || possibleCandidate.getVectorValue().equals(reaction.getVectorValue().negate())) { candidate = possibleCandidate; } } // candidate should not be null at this point since the main test passed. NameCheckResult nameResult; if (connector instanceof Connector2ForceMember2d) { nameResult = checkLoadName2FM(candidate, (Connector2ForceMember2d) connector); } else { nameResult = checkLoadName(candidate); } if (nameResult == NameCheckResult.passed) { // we're okay!! addedLoads.remove(candidate); } else { complainAboutName(nameResult, candidate); return false; } } } } // Step 5: Make sure we've used all the user added forces. if (!addedLoads.isEmpty()) { logInfo("check: user added more forces than necessary: " + addedLoads); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_additional", addedLoads.get(0).getAnchor().getName()); return false; } // Step 6: Verify labels // verify that all unknowns are symbols // these are reaction forces and moments // knowns should not be symbols: externals, weights // symbols must also not be repeated, unless this is valid somehow? (not yet) // Yay, we've passed the test! logInfo("check: PASSED!"); return true; }
public boolean checkDiagram() { //done = false; // step 1: assemble a list of all the forces the user has added. List<Load> addedLoads = new ArrayList<Load>(getAddedLoads()); logInfo("check: user added loads: " + addedLoads); if (addedLoads.size() <= 0) { logInfo("check: diagram does not contain any loads"); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_add"); return false; } // step 2: for vectors that we can click on and add, ie, given added forces, // make sure that the user has added all of them. for (Load given : getGivenLoads()) { boolean ok = performGivenCheck(addedLoads, given); if (!ok) { return false; } } // step 3: Make sure weights exist, and remove them from our addedForces. for (Body body : diagram.getBodySubset().getBodies()) { if (body.getWeight().getDiagramValue().floatValue() == 0) { continue; } Load weight = new Force( body.getCenterOfMassPoint(), Vector3bd.UNIT_Y.negate(), new BigDecimal(body.getWeight().doubleValue())); boolean ok = performWeightCheck(addedLoads, weight, body); if (!ok) { return false; } } // Step 4: go through all the border connectors connecting this FBD to the external world, // and check each load implied by the connector. for (int i = 0; i < diagram.allObjects().size(); i++) { SimulationObject obj = diagram.allObjects().get(i); if (!(obj instanceof Connector)) { continue; } Connector connector = (Connector) obj; // find the body in this diagram to which the connector is attached. Body body = null; if (diagram.allBodies().contains(connector.getBody1())) { body = connector.getBody1(); } if (diagram.allBodies().contains(connector.getBody2())) { body = connector.getBody2(); } // ^ is java's XOR operator // we want the joint IF it connects a body in the body list // to a body that is not in the body list. This means xor. if (!(diagram.getBodySubset().getBodies().contains(connector.getBody1()) ^ diagram.getBodySubset().getBodies().contains(connector.getBody2()))) { continue; } // build a list of the loads at this point List<Load> userLoadsAtConnector = new ArrayList<Load>(); for (Load load : addedLoads) { if (load.getAnchor().equals(connector.getAnchor())) { userLoadsAtConnector.add(load); } } logInfo("check: testing connector: " + connector); // special case, userLoadsAtConnector is empty: if (userLoadsAtConnector.isEmpty()) { logInfo("check: have any forces been added"); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_reaction", connector.connectorName(), connector.getAnchor().getLabelText()); return false; } // //this is trying to make sure two force members have the same values at either end // if (body instanceof TwoForceMember) { // List<Load> userLoadsAtOtherConnector = new ArrayList<Load>(); // Connector con; // if (((TwoForceMember) body).getConnector1() == connector) { // con = ((TwoForceMember) body).getConnector2(); // } else { // con = ((TwoForceMember) body).getConnector1(); // } // for (Load load : addedLoads) { // if (load.getAnchor().equals(con.getAnchor())) { // userLoadsAtOtherConnector.add(load); // } // } // if (!userLoadsAtConnector.get(0).getLabelText().equalsIgnoreCase(userLoadsAtOtherConnector.get(0).getLabelText())) { // logInfo("check: the user has given a 2ForceMember's loads different values"); // logInfo("check: FAILED"); // setAdviceKey("fbd_feedback_check_fail_2force_not_same"); // return false; // } // } ConnectorCheckResult connectorResult = checkConnector(userLoadsAtConnector, connector, body); switch (connectorResult) { case passed: // okay, the check passed without complaint. // The loads may still not be correct, but that will be tested afterwards. // for now, continue normally. break; case inappropriateDirection: // check for special case of 2FM: logInfo("check: User added loads at " + connector.getAnchor().getName() + ": " + userLoadsAtConnector); logInfo("check: Was expecting: " + getReactionLoads(connector, connector.getReactions(body))); if (connector instanceof Connector2ForceMember2d) { Connector2ForceMember2d connector2fm = (Connector2ForceMember2d) connector; if (connector2fm.getMember() instanceof Cable) { // special message for cables: logInfo("check: user created a cable in compression at point " + connector.getAnchor().getName()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_cable", connector.getAnchor().getName(), connector2fm.getMember()); return false; } } else { // one of the directions is the wrong way, and it's not a cable this time // it is probably a roller or something. logInfo("check: loads have wrong direction at point " + connector.getAnchor().getName()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_some_reverse", connector.getAnchor().getName()); return false; } case somethingExtra: // this particular check could be fine // in some problems there are multiple connectors at one point (notably in frame problems) // and this means that extra loads are okay. We check to see if multiple connectors are present, // and if so, continue gracefully, as inapporpriate extra things will be checked at the end // otherwise the check will continue to the next step, "missingSomething" where other conditions // will be tested. if (diagram.getConnectorsAtPoint(connector.getAnchor()).size() > 1) { // continue on. break; } case missingSomething: // okay, if we are here then either something is missing, or something is extra. // check against pins or rollers and see what happens. logInfo("check: User added loads at " + connector.getAnchor().getName() + ": " + userLoadsAtConnector); logInfo("check: Was expecting: " + getReactionLoads(connector, connector.getReactions(body))); // check if this is mistaken for a pin if (!connector.connectorName().equals("pin")) { Pin2d testPin = new Pin2d(connector.getAnchor()); if (checkConnector(userLoadsAtConnector, testPin, null) == ConnectorCheckResult.passed) { logInfo("check: user wrongly created a pin at point " + connector.getAnchor().getLabelText()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "pin", connector.connectorName()); return false; } } // check if this is mistaken for a fix if (!connector.connectorName().equals("fix")) { Fix2d testFix = new Fix2d(connector.getAnchor()); if (checkConnector(userLoadsAtConnector, testFix, null) == ConnectorCheckResult.passed) { logInfo("check: user wrongly created a fix at point " + connector.getAnchor().getLabelText()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_wrong_type", connector.getAnchor().getLabelText(), "fix", connector.connectorName()); return false; } } // otherwise, the user did something strange. logInfo("check: user simply added reactions to a joint that don't make sense to point " + connector.getAnchor().getLabelText()); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_joint_wrong", connector.connectorName(), connector.getAnchor().getLabelText()); return false; } // okay, now the connector test has passed. // We know now that the loads present in the diagram satisfy the reactions for the connector. // All reactions loads are necessarily symbolic, and thus will either be new symbols, or // they will be present in the symbol manager. List<Load> expectedReactions = getReactionLoads(connector, connector.getReactions(body)); for (Load reaction : expectedReactions) { // get a load and result corresponding to this check. Load loadFromSymbolManager = Exercise.getExercise().getSymbolManager().getLoad(reaction); if (loadFromSymbolManager != null) { // make sure the directions are pointing the correct way: if (reaction.getVectorValue().equals(loadFromSymbolManager.getVectorValue().negate())) { loadFromSymbolManager = loadFromSymbolManager.clone(); loadFromSymbolManager.getVectorValue().negateLocal(); } // of the user loads, only check those which point in maybe the right direction List<Load> userLoadsAtConnectorInDirection = new ArrayList<Load>(); for (Load load : userLoadsAtConnector) { if (load.getVectorValue().equals(reaction.getVectorValue()) || load.getVectorValue().equals(reaction.getVectorValue().negate())) { userLoadsAtConnectorInDirection.add(load); } } Pair<Load, LoadCheckResult> result = checkAllCandidatesAgainstTarget( userLoadsAtConnectorInDirection, loadFromSymbolManager); Load candidate = result.getLeft(); // this load has been solved for already. Now we can check against it. if (result.getRight() == LoadCheckResult.passed) { // check is OK, we can remove the load from our addedLoads. addedLoads.remove(candidate); } else { complainAboutLoadCheck(result.getRight(), candidate); return false; } } else { // this load is new, so it requires a name check. // let's find a load that seems to match the expected reaction. Load candidate = null; for (Load possibleCandidate : userLoadsAtConnector) { // we know that these all are at the right anchor, so only test direction. // direction may also be negated, since these are new symbols. if (possibleCandidate.getVectorValue().equals(reaction.getVectorValue()) || possibleCandidate.getVectorValue().equals(reaction.getVectorValue().negate())) { candidate = possibleCandidate; } } // candidate should not be null at this point since the main test passed. NameCheckResult nameResult; if (connector instanceof Connector2ForceMember2d) { nameResult = checkLoadName2FM(candidate, (Connector2ForceMember2d) connector); } else { nameResult = checkLoadName(candidate); } if (nameResult == NameCheckResult.passed) { // we're okay!! addedLoads.remove(candidate); } else { complainAboutName(nameResult, candidate); return false; } } } } // Step 5: Make sure we've used all the user added forces. if (!addedLoads.isEmpty()) { logInfo("check: user added more forces than necessary: " + addedLoads); logInfo("check: FAILED"); setAdviceKey("fbd_feedback_check_fail_additional", addedLoads.get(0).getAnchor().getName()); return false; } // Step 6: Verify labels // verify that all unknowns are symbols // these are reaction forces and moments // knowns should not be symbols: externals, weights // symbols must also not be repeated, unless this is valid somehow? (not yet) // Yay, we've passed the test! logInfo("check: PASSED!"); return true; }
diff --git a/sgs-server/src/main/java/com/sun/sgs/impl/profile/ProfileReportImpl.java b/sgs-server/src/main/java/com/sun/sgs/impl/profile/ProfileReportImpl.java index 5b4e63c35..887439189 100644 --- a/sgs-server/src/main/java/com/sun/sgs/impl/profile/ProfileReportImpl.java +++ b/sgs-server/src/main/java/com/sun/sgs/impl/profile/ProfileReportImpl.java @@ -1,380 +1,380 @@ /* * Copyright 2007-2008 Sun Microsystems, Inc. * * This file is part of Project Darkstar Server. * * Project Darkstar Server 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 and * distributed hereunder to you. * * Project Darkstar Server is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.sun.sgs.impl.profile; import com.sun.sgs.auth.Identity; import com.sun.sgs.kernel.KernelRunnable; import com.sun.sgs.profile.ProfileOperation; import com.sun.sgs.profile.ProfileParticipantDetail; import com.sun.sgs.profile.ProfileReport; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * Package-private implementation of <code>ProfileReport</code>. */ class ProfileReportImpl implements ProfileReport { /** * An empty map for returning when no profile counters have been * updated. */ private static final Map<String,Long> EMPTY_COUNTER_MAP = Collections.emptyMap(); /** * An empty map for returning when no profile samples have been * updated. We need this map as well because typing issues * prevent us from using {@link Collections#emptyMap()}. */ private static final Map<String,List<Long>> EMPTY_SAMPLE_MAP = Collections.unmodifiableMap(new HashMap<String,List<Long>>()); // the final fields, set by the constructor final KernelRunnable task; final Identity owner; final long scheduledStartTime; final int readyCount; final long actualStartTime; // the other fields, set directly by the ProfileCollectorImpl boolean transactional = false; boolean succeeded = false; long runningTime = 0; int tryCount = 0; Throwable throwable = null; Set<ProfileParticipantDetail> participants; // counters that are updated through methods on this class Map<String,Long> aggCounters; Map<String,Long> taskCounters; // a list of operations performed, which is updated through // methods on this class List<ProfileOperation> ops; // samples that are aggregated through methods on this class Map<String,List<Long>> localSamples; Map<String,List<Long>> aggregateSamples; /** * Creates an instance of <code>ProfileReportImpl</code> with the * actual starting time being set to the current time. * * @param task the <code>KernelRunnable</code> being reported on * @param owner the <code>Identity</code> that owns the task * @param scheduledStartTime the time the task was scheduled to run * @param readyCount the number of tasks in the scheduler, ready to run, * that are associated with the same context as the task */ ProfileReportImpl(KernelRunnable task, Identity owner, long scheduledStartTime, int readyCount) { this.task = task; this.owner = owner; this.scheduledStartTime = scheduledStartTime; this.readyCount = readyCount; this.actualStartTime = System.currentTimeMillis(); ops = new ArrayList<ProfileOperation>(); participants = new HashSet<ProfileParticipantDetail>(); aggCounters = null; taskCounters = null; localSamples = null; aggregateSamples = null; } /** * Package-private method used to update aggregate counters that were * changed during this task. * * @param counter the name of the counter * @param value the new value of this counter */ void updateAggregateCounter(String counter, long value) { if (aggCounters == null) aggCounters = new HashMap<String,Long>(); aggCounters.put(counter, value); } /** * Package-private method used to increment task-local counters * that were changed during this task. If this counter hasn't had a * value reported yet for this task, then the provided value is * set as the current value for the counter. * * @param counter the name of the counter * @param value the amount to increment the counter */ void incrementTaskCounter(String counter, long value) { long currentValue = 0; if (taskCounters == null) { taskCounters = new HashMap<String,Long>(); } else { if (taskCounters.containsKey(counter)) currentValue = taskCounters.get(counter); } taskCounters.put(counter, currentValue + value); } /** * Package-private method used to add to a task-local sample. If * this sample hasn't had a value reported yet for this task, then * a new list is made and the the provided value is added to it. * * @param sampleName the name of the sample * @param value the latest value for the sample */ void addLocalSample(String sampleName, long value) { List<Long> samples; if (localSamples == null) { localSamples = new HashMap<String,List<Long>>(); samples = new LinkedList<Long>(); localSamples.put(sampleName, samples); } else { if (localSamples.containsKey(sampleName)) samples = localSamples.get(sampleName); else { samples = new LinkedList<Long>(); localSamples.put(sampleName, samples); } } samples.add(value); } /** * Package-private method used to add to an aggregate sample. If * this sample hasn't had a value reported yet for this task, then * a new list is made and the the provided value is added to it. * * @param sampleName the name of the sample * @param samples the list of all samples for this name */ void registerAggregateSamples(String sampleName, List<Long> samples) { // NOTE: we make the list unmodifiable so that the user cannot // alter any of the samples. This is important since the same // list is used for the lifetime of the application. if (aggregateSamples == null) { aggregateSamples = new HashMap<String,List<Long>>(); aggregateSamples.put(sampleName, Collections.unmodifiableList(samples)); } else if (!aggregateSamples.containsKey(sampleName)) aggregateSamples.put(sampleName, Collections.unmodifiableList(samples)); } /** * {@inheritDoc} */ public KernelRunnable getTask() { return task; } /** * {@inheritDoc} */ public Identity getTaskOwner() { return owner; } /** * {@inheritDoc} */ public boolean wasTaskTransactional() { return transactional; } /** * {@inheritDoc} */ public Set<ProfileParticipantDetail> getParticipantDetails() { return participants; } /** * {@inheritDoc} */ public boolean wasTaskSuccessful() { return succeeded; } /** * {@inheritDoc} */ public long getScheduledStartTime() { return scheduledStartTime; } /** * {@inheritDoc} */ public long getActualStartTime() { return actualStartTime; } /** * {@inheritDoc} */ public long getRunningTime() { return runningTime; } /** * {@inheritDoc} */ public int getRetryCount() { return tryCount; } /** * {@inheritDoc} */ public List<ProfileOperation> getReportedOperations() { return ops; } /** * {@inheritDoc} */ public Map<String,Long> getUpdatedAggregateCounters() { return (aggCounters == null) ? EMPTY_COUNTER_MAP : aggCounters; } /** * {@inheritDoc} */ public Map<String,Long> getUpdatedTaskCounters() { return (taskCounters == null) ? EMPTY_COUNTER_MAP : taskCounters; } /** * {@inheritDoc} */ public Map<String,List<Long>> getUpdatedAggregateSamples() { return (aggregateSamples == null) ? EMPTY_SAMPLE_MAP : aggregateSamples; } /** * {@inheritDoc} */ public Map<String,List<Long>> getUpdatedTaskSamples() { return (localSamples == null) ? EMPTY_SAMPLE_MAP : localSamples; } /** * {@inheritDoc} */ public int getReadyCount() { return readyCount; } /** * {@inheritDoc} */ public Throwable getFailureCause() { return throwable; } /** * Package-private method used to merge the state of one report into * another. This is typically used when a nested, profiled task * completes and needs to share its data with its parent. */ void merge(ProfileReportImpl report) { // for each of the child task counters and samples, we first // check whether the task recorded any data. If so, then we // copy the data to this report. if (report.taskCounters != null) { if (taskCounters == null) { taskCounters = new HashMap<String,Long>(report.taskCounters); } else { for (Map.Entry<String,Long> e : report.taskCounters.entrySet()) { Long curCount = taskCounters.get(e.getKey()); taskCounters.put(e.getKey(), (curCount == null) ? e.getValue() : curCount + e.getValue()); } } } if (report.localSamples != null) { if (localSamples == null) { localSamples = new HashMap<String,List<Long>>(); for (Map.Entry<String,List<Long>> e : report.localSamples.entrySet()) { // make a copy of the child task's samples List<Long> samples = new LinkedList<Long>(e.getValue()); localSamples.put(e.getKey(), samples); } } else { for (Map.Entry<String,List<Long>> e : report.localSamples.entrySet()) { List<Long> samples = localSamples.get(e.getKey()); if (samples == null) // make a copy of the child task's samples localSamples.put(e.getKey(), new LinkedList<Long>(e.getValue())); else samples.addAll(e.getValue()); } } } if (report.ops != null) { if (ops == null) { - ops = new LinekdList<ProfileOperation>(report.ops); + ops = new LinkedList<ProfileOperation>(report.ops); } else { ops.addAll(report.ops); } } // NOTE: we do not need to update the aggregateSamples and // aggregateCounters, as this is being collected across // all tasks, and so by updating we would really be // double counting the data // NOTE: we do not include the the participants information // since this is specific to a task and not to its // children. } }
true
true
void merge(ProfileReportImpl report) { // for each of the child task counters and samples, we first // check whether the task recorded any data. If so, then we // copy the data to this report. if (report.taskCounters != null) { if (taskCounters == null) { taskCounters = new HashMap<String,Long>(report.taskCounters); } else { for (Map.Entry<String,Long> e : report.taskCounters.entrySet()) { Long curCount = taskCounters.get(e.getKey()); taskCounters.put(e.getKey(), (curCount == null) ? e.getValue() : curCount + e.getValue()); } } } if (report.localSamples != null) { if (localSamples == null) { localSamples = new HashMap<String,List<Long>>(); for (Map.Entry<String,List<Long>> e : report.localSamples.entrySet()) { // make a copy of the child task's samples List<Long> samples = new LinkedList<Long>(e.getValue()); localSamples.put(e.getKey(), samples); } } else { for (Map.Entry<String,List<Long>> e : report.localSamples.entrySet()) { List<Long> samples = localSamples.get(e.getKey()); if (samples == null) // make a copy of the child task's samples localSamples.put(e.getKey(), new LinkedList<Long>(e.getValue())); else samples.addAll(e.getValue()); } } } if (report.ops != null) { if (ops == null) { ops = new LinekdList<ProfileOperation>(report.ops); } else { ops.addAll(report.ops); } } // NOTE: we do not need to update the aggregateSamples and // aggregateCounters, as this is being collected across // all tasks, and so by updating we would really be // double counting the data // NOTE: we do not include the the participants information // since this is specific to a task and not to its // children. }
void merge(ProfileReportImpl report) { // for each of the child task counters and samples, we first // check whether the task recorded any data. If so, then we // copy the data to this report. if (report.taskCounters != null) { if (taskCounters == null) { taskCounters = new HashMap<String,Long>(report.taskCounters); } else { for (Map.Entry<String,Long> e : report.taskCounters.entrySet()) { Long curCount = taskCounters.get(e.getKey()); taskCounters.put(e.getKey(), (curCount == null) ? e.getValue() : curCount + e.getValue()); } } } if (report.localSamples != null) { if (localSamples == null) { localSamples = new HashMap<String,List<Long>>(); for (Map.Entry<String,List<Long>> e : report.localSamples.entrySet()) { // make a copy of the child task's samples List<Long> samples = new LinkedList<Long>(e.getValue()); localSamples.put(e.getKey(), samples); } } else { for (Map.Entry<String,List<Long>> e : report.localSamples.entrySet()) { List<Long> samples = localSamples.get(e.getKey()); if (samples == null) // make a copy of the child task's samples localSamples.put(e.getKey(), new LinkedList<Long>(e.getValue())); else samples.addAll(e.getValue()); } } } if (report.ops != null) { if (ops == null) { ops = new LinkedList<ProfileOperation>(report.ops); } else { ops.addAll(report.ops); } } // NOTE: we do not need to update the aggregateSamples and // aggregateCounters, as this is being collected across // all tasks, and so by updating we would really be // double counting the data // NOTE: we do not include the the participants information // since this is specific to a task and not to its // children. }
diff --git a/src/main/java/com/jdkcn/jabber/web/servlet/IndexServlet.java b/src/main/java/com/jdkcn/jabber/web/servlet/IndexServlet.java index fde1ccc..545a493 100644 --- a/src/main/java/com/jdkcn/jabber/web/servlet/IndexServlet.java +++ b/src/main/java/com/jdkcn/jabber/web/servlet/IndexServlet.java @@ -1,73 +1,73 @@ /** * Project:jabberer * File:IndexServlet.java * Copyright 2004-2012 Homolo Co., Ltd. All rights reserved. */ package com.jdkcn.jabber.web.servlet; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jdkcn.jabber.domain.User; import org.codehaus.jackson.JsonNode; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.Roster.SubscriptionMode; import org.jivesoftware.smack.RosterEntry; import org.jivesoftware.smack.XMPPConnection; import com.google.inject.Singleton; import com.jdkcn.jabber.robot.Robot; import com.jdkcn.jabber.util.Constants; /** * @author Rory * @version $Id$ * @date Feb 7, 2012 */ @Singleton public class IndexServlet extends HttpServlet { private static final long serialVersionUID = -4585928956316091202L; /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { JsonNode jsonConfig = (JsonNode) req.getServletContext().getAttribute(Constants.JABBERERJSONCONFIG); User loginUser = (User) req.getSession().getAttribute(Constants.LOGIN_USER); List<Robot> allRobots = (List<Robot>) req.getServletContext().getAttribute(Constants.ROBOTS); List<Robot> robots = new ArrayList<Robot>(); Boolean allRobotsOnline = true; for (Robot robot : allRobots) { XMPPConnection connection = robot.getConnection(); if (connection != null && connection.isConnected()) { robot.getOnlineRosters().clear(); Roster roster = connection.getRoster(); - for (RosterEntry entry : robot.getRosters()) { + for (RosterEntry entry : roster.getEntries()) { if (roster.getPresence(entry.getUser()).isAvailable() && !robot.getOnlineRosters().contains(entry)) { robot.getOnlineRosters().add(entry); } } } else { robot.getOnlineRosters().clear(); allRobotsOnline = false; } if (!loginUser.getManageRobots().isEmpty() && loginUser.getManageRobots().contains(robot.getName())) { robots.add(robot); } } req.setAttribute("allRobotsOnline", allRobotsOnline); req.setAttribute("robots", robots); req.setAttribute("jsonConfig", jsonConfig); req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req, resp); } }
true
true
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { JsonNode jsonConfig = (JsonNode) req.getServletContext().getAttribute(Constants.JABBERERJSONCONFIG); User loginUser = (User) req.getSession().getAttribute(Constants.LOGIN_USER); List<Robot> allRobots = (List<Robot>) req.getServletContext().getAttribute(Constants.ROBOTS); List<Robot> robots = new ArrayList<Robot>(); Boolean allRobotsOnline = true; for (Robot robot : allRobots) { XMPPConnection connection = robot.getConnection(); if (connection != null && connection.isConnected()) { robot.getOnlineRosters().clear(); Roster roster = connection.getRoster(); for (RosterEntry entry : robot.getRosters()) { if (roster.getPresence(entry.getUser()).isAvailable() && !robot.getOnlineRosters().contains(entry)) { robot.getOnlineRosters().add(entry); } } } else { robot.getOnlineRosters().clear(); allRobotsOnline = false; } if (!loginUser.getManageRobots().isEmpty() && loginUser.getManageRobots().contains(robot.getName())) { robots.add(robot); } } req.setAttribute("allRobotsOnline", allRobotsOnline); req.setAttribute("robots", robots); req.setAttribute("jsonConfig", jsonConfig); req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req, resp); }
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { JsonNode jsonConfig = (JsonNode) req.getServletContext().getAttribute(Constants.JABBERERJSONCONFIG); User loginUser = (User) req.getSession().getAttribute(Constants.LOGIN_USER); List<Robot> allRobots = (List<Robot>) req.getServletContext().getAttribute(Constants.ROBOTS); List<Robot> robots = new ArrayList<Robot>(); Boolean allRobotsOnline = true; for (Robot robot : allRobots) { XMPPConnection connection = robot.getConnection(); if (connection != null && connection.isConnected()) { robot.getOnlineRosters().clear(); Roster roster = connection.getRoster(); for (RosterEntry entry : roster.getEntries()) { if (roster.getPresence(entry.getUser()).isAvailable() && !robot.getOnlineRosters().contains(entry)) { robot.getOnlineRosters().add(entry); } } } else { robot.getOnlineRosters().clear(); allRobotsOnline = false; } if (!loginUser.getManageRobots().isEmpty() && loginUser.getManageRobots().contains(robot.getName())) { robots.add(robot); } } req.setAttribute("allRobotsOnline", allRobotsOnline); req.setAttribute("robots", robots); req.setAttribute("jsonConfig", jsonConfig); req.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(req, resp); }
diff --git a/tests/tests/view/src/android/view/cts/View_AnimationTest.java b/tests/tests/view/src/android/view/cts/View_AnimationTest.java index 7a22a3b5..06763f53 100644 --- a/tests/tests/view/src/android/view/cts/View_AnimationTest.java +++ b/tests/tests/view/src/android/view/cts/View_AnimationTest.java @@ -1,169 +1,171 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.view.cts; import android.app.Activity; import android.test.ActivityInstrumentationTestCase2; import android.view.View; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.view.animation.cts.AnimationTestUtils; import android.view.animation.cts.DelayedCheck; import com.android.cts.stub.R; import dalvik.annotation.TestLevel; import dalvik.annotation.TestTargetClass; import dalvik.annotation.TestTargetNew; import dalvik.annotation.TestTargets; import dalvik.annotation.ToBeFixed; /** * Test {@link View}. */ @TestTargetClass(View.class) public class View_AnimationTest extends ActivityInstrumentationTestCase2<ViewTestStubActivity> { private static final int TIME_OUT = 5000; private static final int DURATION = 2000; private Activity mActivity; private TranslateAnimation mAnimation; public View_AnimationTest() { super("com.android.cts.stub", ViewTestStubActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); mActivity = getActivity(); mAnimation = new TranslateAnimation(0.0f, 10.0f, 0.0f, 10.0f); mAnimation.setDuration(DURATION); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "setAnimation", args = {Animation.class} ) }) public void testAnimation() throws Throwable { final View view = mActivity.findViewById(R.id.fit_windows); // set null animation view.setAnimation(null); assertNull(view.getAnimation()); view.setAnimation(mAnimation); runTestOnUiThread(new Runnable() { public void run() { view.invalidate(); } }); AnimationTestUtils.assertRunAnimation(getInstrumentation(), view, mAnimation, TIME_OUT); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "startAnimation", args = {Animation.class} ) }) @ToBeFixed(bug = "1695243", explanation = "Android API javadocs are incomplete") public void testStartAnimation() throws Throwable { final View view = mActivity.findViewById(R.id.fit_windows); // start null animation try { view.startAnimation(null); fail("did not throw NullPointerException when start null animation"); } catch (NullPointerException e) { // expected } runTestOnUiThread(new Runnable() { public void run() { view.startAnimation(mAnimation); } }); AnimationTestUtils.assertRunAnimation(getInstrumentation(), view, mAnimation, TIME_OUT); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "clearAnimation", args = {} ), @TestTargetNew( level = TestLevel.COMPLETE, method = "getAnimation", args = {} ) }) public void testClearBeforeAnimation() throws Throwable { final View view = mActivity.findViewById(R.id.fit_windows); assertFalse(mAnimation.hasStarted()); view.setAnimation(mAnimation); assertSame(mAnimation, view.getAnimation()); view.clearAnimation(); runTestOnUiThread(new Runnable() { public void run() { view.invalidate(); } }); Thread.sleep(TIME_OUT); assertFalse(mAnimation.hasStarted()); assertNull(view.getAnimation()); } @TestTargets({ @TestTargetNew( level = TestLevel.COMPLETE, method = "View.clearAnimation", args = {} ) }) public void testClearDuringAnimation() throws Throwable { final View view = mActivity.findViewById(R.id.fit_windows); runTestOnUiThread(new Runnable() { public void run() { view.startAnimation(mAnimation); + assertNotNull(view.getAnimation()); } }); new DelayedCheck(TIME_OUT) { @Override protected boolean check() { return mAnimation.hasStarted(); } }.run(); view.clearAnimation(); Thread.sleep(TIME_OUT); assertTrue(mAnimation.hasStarted()); - assertFalse(mAnimation.hasEnded()); + assertTrue(mAnimation.hasEnded()); + assertNull(view.getAnimation()); } }
false
true
public void testClearDuringAnimation() throws Throwable { final View view = mActivity.findViewById(R.id.fit_windows); runTestOnUiThread(new Runnable() { public void run() { view.startAnimation(mAnimation); } }); new DelayedCheck(TIME_OUT) { @Override protected boolean check() { return mAnimation.hasStarted(); } }.run(); view.clearAnimation(); Thread.sleep(TIME_OUT); assertTrue(mAnimation.hasStarted()); assertFalse(mAnimation.hasEnded()); }
public void testClearDuringAnimation() throws Throwable { final View view = mActivity.findViewById(R.id.fit_windows); runTestOnUiThread(new Runnable() { public void run() { view.startAnimation(mAnimation); assertNotNull(view.getAnimation()); } }); new DelayedCheck(TIME_OUT) { @Override protected boolean check() { return mAnimation.hasStarted(); } }.run(); view.clearAnimation(); Thread.sleep(TIME_OUT); assertTrue(mAnimation.hasStarted()); assertTrue(mAnimation.hasEnded()); assertNull(view.getAnimation()); }
diff --git a/src/org/geworkbench/util/pathwaydecoder/mutualinformation/AdjacencyMatrixDataSet.java b/src/org/geworkbench/util/pathwaydecoder/mutualinformation/AdjacencyMatrixDataSet.java index 2e0ef05e..17fb8fdf 100755 --- a/src/org/geworkbench/util/pathwaydecoder/mutualinformation/AdjacencyMatrixDataSet.java +++ b/src/org/geworkbench/util/pathwaydecoder/mutualinformation/AdjacencyMatrixDataSet.java @@ -1,122 +1,124 @@ package org.geworkbench.util.pathwaydecoder.mutualinformation; import org.geworkbench.bison.datastructure.biocollections.CSAncillaryDataSet; import org.geworkbench.bison.datastructure.biocollections.DSAncillaryDataSet; import org.geworkbench.bison.datastructure.biocollections.microarrays.DSMicroarraySet; import org.geworkbench.bison.datastructure.complex.panels.DSItemList; import org.geworkbench.bison.datastructure.bioobjects.markers.DSGeneMarker; import org.geworkbench.bison.util.RandomNumberGenerator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import javax.swing.*; import java.io.File; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** * @author John Watkinson */ public class AdjacencyMatrixDataSet extends CSAncillaryDataSet implements DSAncillaryDataSet { static Log log = LogFactory.getLog(AdjacencyMatrixDataSet.class); /** * */ private static final long serialVersionUID = -6835973287728524201L; private AdjacencyMatrix matrix; private int geneId; private double threshold; private int depth; private String networkName; public AdjacencyMatrixDataSet(AdjacencyMatrix matrix, int geneId, double threshold, int depth, String name, String networkName, DSMicroarraySet parent) { super(parent, name); setID(RandomNumberGenerator.getID()); this.matrix = matrix; this.geneId = geneId; this.threshold = threshold; this.depth = depth; this.networkName = networkName; } public void writeToFile(String fileName) { File file = new File(fileName); try { file.createNewFile(); if (!file.canWrite()) { JOptionPane.showMessageDialog(null, "Cannot write to specified file."); return; } BufferedWriter writer = new BufferedWriter(new FileWriter(file)); DSMicroarraySet mset = matrix.getMicroarraySet(); DSItemList<DSGeneMarker> markers = mset.getMarkers(); HashMap<Integer, HashMap<Integer, Float>> geneRows = matrix.getGeneRows(); for (Map.Entry<Integer, HashMap<Integer, Float>> entry : geneRows.entrySet()) { String geneName = markers.get(entry.getKey()).getLabel(); + writer.write(geneName + "\t"); HashMap<Integer, Float> destRows = entry.getValue(); for (Map.Entry<Integer, Float> entry2 : destRows.entrySet()) { String geneName2 = markers.get(entry2.getKey()).getLabel(); - writer.write(geneName + ", " + entry2.getValue() + ", " + geneName2 + "\n"); + writer.write(geneName2 + "\t" + entry2.getValue() + "\t"); } + writer.write("\n"); } writer.close(); } catch (IOException e) { log.error(e); } } public AdjacencyMatrix getMatrix() { return matrix; } public void setMatrix(AdjacencyMatrix matrix) { this.matrix = matrix; } public int getGeneId() { return geneId; } public void setGeneId(int geneId) { this.geneId = geneId; } public double getThreshold() { return threshold; } public void setThreshold(double threshold) { this.threshold = threshold; } public int getDepth() { return depth; } public void setDepth(int depth) { this.depth = depth; } public File getDataSetFile() { // no-op return null; } public void setDataSetFile(File file) { // no-op } public String getNetworkName() { return networkName; } public void setNetworkName(String networkName) { this.networkName = networkName; } }
false
true
public void writeToFile(String fileName) { File file = new File(fileName); try { file.createNewFile(); if (!file.canWrite()) { JOptionPane.showMessageDialog(null, "Cannot write to specified file."); return; } BufferedWriter writer = new BufferedWriter(new FileWriter(file)); DSMicroarraySet mset = matrix.getMicroarraySet(); DSItemList<DSGeneMarker> markers = mset.getMarkers(); HashMap<Integer, HashMap<Integer, Float>> geneRows = matrix.getGeneRows(); for (Map.Entry<Integer, HashMap<Integer, Float>> entry : geneRows.entrySet()) { String geneName = markers.get(entry.getKey()).getLabel(); HashMap<Integer, Float> destRows = entry.getValue(); for (Map.Entry<Integer, Float> entry2 : destRows.entrySet()) { String geneName2 = markers.get(entry2.getKey()).getLabel(); writer.write(geneName + ", " + entry2.getValue() + ", " + geneName2 + "\n"); } } writer.close(); } catch (IOException e) { log.error(e); } }
public void writeToFile(String fileName) { File file = new File(fileName); try { file.createNewFile(); if (!file.canWrite()) { JOptionPane.showMessageDialog(null, "Cannot write to specified file."); return; } BufferedWriter writer = new BufferedWriter(new FileWriter(file)); DSMicroarraySet mset = matrix.getMicroarraySet(); DSItemList<DSGeneMarker> markers = mset.getMarkers(); HashMap<Integer, HashMap<Integer, Float>> geneRows = matrix.getGeneRows(); for (Map.Entry<Integer, HashMap<Integer, Float>> entry : geneRows.entrySet()) { String geneName = markers.get(entry.getKey()).getLabel(); writer.write(geneName + "\t"); HashMap<Integer, Float> destRows = entry.getValue(); for (Map.Entry<Integer, Float> entry2 : destRows.entrySet()) { String geneName2 = markers.get(entry2.getKey()).getLabel(); writer.write(geneName2 + "\t" + entry2.getValue() + "\t"); } writer.write("\n"); } writer.close(); } catch (IOException e) { log.error(e); } }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/JavaPrimitiveValueEditor.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/JavaPrimitiveValueEditor.java index 68f81a9ae..49e0ff915 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/JavaPrimitiveValueEditor.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/actions/JavaPrimitiveValueEditor.java @@ -1,139 +1,137 @@ /******************************************************************************* * Copyright (c) 2004 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 implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.ui.actions; import java.text.MessageFormat; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.model.IVariable; import org.eclipse.debug.internal.ui.DebugUIPlugin; import org.eclipse.debug.ui.actions.IVariableValueEditor; import org.eclipse.jface.dialogs.IInputValidator; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.window.Window; import org.eclipse.swt.widgets.Shell; /** * A variable value editor that prompts the user to set a primitive's value. */ public class JavaPrimitiveValueEditor implements IVariableValueEditor { /** * The signature of the edited variable. */ private String fSignature= null; /** * Creates a new editor for a variable with the given signature * @param signature the signature of the primitive to be edited */ public JavaPrimitiveValueEditor(String signature) { fSignature= signature; } private JavaPrimitiveValueEditor() { // Do not call. } /* (non-Javadoc) * @see org.eclipse.debug.ui.actions.IVariableValueEditor#editVariable(org.eclipse.debug.core.model.IVariable, org.eclipse.swt.widgets.Shell) */ public boolean editVariable(IVariable variable, Shell shell) { try { String name= variable.getName(); String title= ActionMessages.getString("JavaPrimitiveValueEditor.0"); //$NON-NLS-1$ String message= MessageFormat.format(ActionMessages.getString("JavaPrimitiveValueEditor.1"), new String[] {name}); //$NON-NLS-1$ String initialValue= variable.getValue().getValueString(); IInputValidator validator= new PrimitiveValidator(); InputDialog dialog= new InputDialog(shell, title, message, initialValue, validator); if (dialog.open() == Window.OK) { String stringValue = dialog.getValue(); variable.setValue(stringValue); } } catch (DebugException e) { DebugUIPlugin.errorDialog(shell, ActionMessages.getString("JavaPrimitiveValueEditor.2"), ActionMessages.getString("JavaPrimitiveValueEditor.3"), e); //$NON-NLS-1$ //$NON-NLS-2$ } return true; } /** * Input validator for primitive types */ protected class PrimitiveValidator implements IInputValidator { /* (non-Javadoc) * @see org.eclipse.jface.dialogs.IInputValidator#isValid(java.lang.String) */ public String isValid(String newText) { String type= null; switch (fSignature.charAt(0)) { case 'B': try { Byte.parseByte(newText); } catch (NumberFormatException e) { type= "byte"; //$NON-NLS-1$ } break; case 'C': if (newText.length() != 1) { type="char"; //$NON-NLS-1$ } break; case 'D': try { Double.parseDouble(newText); } catch (NumberFormatException e) { type="double"; //$NON-NLS-1$ } break; case 'F': try { Float.parseFloat(newText); } catch (NumberFormatException e) { type="float"; //$NON-NLS-1$ } break; case 'I': try { Integer.parseInt(newText); } catch (NumberFormatException e) { type="int"; //$NON-NLS-1$ } break; case 'J': try { Long.parseLong(newText); } catch (NumberFormatException e) { type="long"; //$NON-NLS-1$ } break; case 'S': try { Short.parseShort(newText); } catch (NumberFormatException e) { type="short"; //$NON-NLS-1$ } break; case 'Z': - try { - Boolean.parseBoolean(newText); - } catch (NumberFormatException e) { - type="boolean"; //$NON-NLS-1$ - } + if (!("true".equals(newText) || "false".equals(newText))) { //$NON-NLS-1$ //$NON-NLS-2$ + type="boolean"; //$NON-NLS-1$ + } break; } if (type != null) { return MessageFormat.format(ActionMessages.getString("JavaPrimitiveValueEditor.4"), new String[] { type }); //$NON-NLS-1$ } return null; } } }
true
true
public String isValid(String newText) { String type= null; switch (fSignature.charAt(0)) { case 'B': try { Byte.parseByte(newText); } catch (NumberFormatException e) { type= "byte"; //$NON-NLS-1$ } break; case 'C': if (newText.length() != 1) { type="char"; //$NON-NLS-1$ } break; case 'D': try { Double.parseDouble(newText); } catch (NumberFormatException e) { type="double"; //$NON-NLS-1$ } break; case 'F': try { Float.parseFloat(newText); } catch (NumberFormatException e) { type="float"; //$NON-NLS-1$ } break; case 'I': try { Integer.parseInt(newText); } catch (NumberFormatException e) { type="int"; //$NON-NLS-1$ } break; case 'J': try { Long.parseLong(newText); } catch (NumberFormatException e) { type="long"; //$NON-NLS-1$ } break; case 'S': try { Short.parseShort(newText); } catch (NumberFormatException e) { type="short"; //$NON-NLS-1$ } break; case 'Z': try { Boolean.parseBoolean(newText); } catch (NumberFormatException e) { type="boolean"; //$NON-NLS-1$ } break; } if (type != null) { return MessageFormat.format(ActionMessages.getString("JavaPrimitiveValueEditor.4"), new String[] { type }); //$NON-NLS-1$ } return null; }
public String isValid(String newText) { String type= null; switch (fSignature.charAt(0)) { case 'B': try { Byte.parseByte(newText); } catch (NumberFormatException e) { type= "byte"; //$NON-NLS-1$ } break; case 'C': if (newText.length() != 1) { type="char"; //$NON-NLS-1$ } break; case 'D': try { Double.parseDouble(newText); } catch (NumberFormatException e) { type="double"; //$NON-NLS-1$ } break; case 'F': try { Float.parseFloat(newText); } catch (NumberFormatException e) { type="float"; //$NON-NLS-1$ } break; case 'I': try { Integer.parseInt(newText); } catch (NumberFormatException e) { type="int"; //$NON-NLS-1$ } break; case 'J': try { Long.parseLong(newText); } catch (NumberFormatException e) { type="long"; //$NON-NLS-1$ } break; case 'S': try { Short.parseShort(newText); } catch (NumberFormatException e) { type="short"; //$NON-NLS-1$ } break; case 'Z': if (!("true".equals(newText) || "false".equals(newText))) { //$NON-NLS-1$ //$NON-NLS-2$ type="boolean"; //$NON-NLS-1$ } break; } if (type != null) { return MessageFormat.format(ActionMessages.getString("JavaPrimitiveValueEditor.4"), new String[] { type }); //$NON-NLS-1$ } return null; }
diff --git a/src/main/java/me/limebyte/battlenight/core/util/BattleClass.java b/src/main/java/me/limebyte/battlenight/core/util/BattleClass.java index 5921d7c..8fb8552 100644 --- a/src/main/java/me/limebyte/battlenight/core/util/BattleClass.java +++ b/src/main/java/me/limebyte/battlenight/core/util/BattleClass.java @@ -1,40 +1,40 @@ package me.limebyte.battlenight.core.util; import java.util.List; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; public class BattleClass { private String name; private List<ItemStack> items, armour; public BattleClass(String name, List<ItemStack> items, List<ItemStack> armour) { this.name = name; this.items = items; this.armour = armour; } public String getName() { return name; } public List<ItemStack> getItems() { return items; } public List<ItemStack> getArmour() { return armour; } public void equip(Player player) { PlayerInventory inv = player.getInventory(); - inv.setContents((ItemStack[]) items.toArray()); + inv.setContents(items.toArray(new ItemStack[items.size()])); inv.setHelmet(armour.get(0)); inv.setChestplate(armour.get(1)); inv.setLeggings(armour.get(2)); inv.setBoots(armour.get(3)); } }
true
true
public void equip(Player player) { PlayerInventory inv = player.getInventory(); inv.setContents((ItemStack[]) items.toArray()); inv.setHelmet(armour.get(0)); inv.setChestplate(armour.get(1)); inv.setLeggings(armour.get(2)); inv.setBoots(armour.get(3)); }
public void equip(Player player) { PlayerInventory inv = player.getInventory(); inv.setContents(items.toArray(new ItemStack[items.size()])); inv.setHelmet(armour.get(0)); inv.setChestplate(armour.get(1)); inv.setLeggings(armour.get(2)); inv.setBoots(armour.get(3)); }
diff --git a/src/org/eclipse/jface/window/ToolTip.java b/src/org/eclipse/jface/window/ToolTip.java index 5d6e350d..82439856 100644 --- a/src/org/eclipse/jface/window/ToolTip.java +++ b/src/org/eclipse/jface/window/ToolTip.java @@ -1,633 +1,633 @@ /******************************************************************************* * Copyright (c) 2006, 2007 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tom Schindl <[email protected]> - initial API and implementation *******************************************************************************/ package org.eclipse.jface.window; import java.util.HashMap; import org.eclipse.jface.viewers.ColumnViewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Monitor; import org.eclipse.swt.widgets.Shell; /** * This class gives implementors to provide customized tooltips for any control. * * @since 3.3 */ public abstract class ToolTip { private Control control; private int xShift = 3; private int yShift = 0; private int popupDelay = 0; private int hideDelay = 0; private ToolTipOwnerControlListener listener; private HashMap data; // Ensure that only one tooltip is active in time private static Shell CURRENT_TOOLTIP; /** * Recreate the tooltip on every mouse move */ public static final int RECREATE = 1; /** * Don't recreate the tooltip as long the mouse doesn't leave the area * triggering the Tooltip creation */ public static final int NO_RECREATE = 1 << 1; private TooltipHideListener hideListener = new TooltipHideListener(); private boolean hideOnMouseDown = true; private boolean respectDisplayBounds = true; private boolean respectMonitorBounds = true; private int style; private Object currentArea; /** * Create new instance which add TooltipSupport to the widget * * @param control * the control on whose action the tooltip is shown */ public ToolTip(Control control) { this(control, RECREATE, false); } /** * @param control * the control to which the tooltip is bound * @param style * style passed to control tooltip behaviour * * @param manualActivation * <code>true</code> if the activation is done manually using * {@link #show(Point)} * @see #RECREATE * @see #NO_RECREATE */ public ToolTip(Control control, int style, boolean manualActivation) { this.control = control; this.style = style; this.control.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { deactivate(); } }); this.listener = new ToolTipOwnerControlListener(); if (!manualActivation) { activate(); } } /** * Restore arbitary data under the given key * * @param key * the key * @param value * the value */ public void setData(String key, Object value) { if (data == null) { data = new HashMap(); } data.put(key, value); } /** * Get the data restored under the key * * @param key * the key * @return data or <code>null</code> if no entry is restored under the key */ public Object getData(String key) { if (data != null) { return data.get(key); } return null; } /** * Set the shift (from the mouse position triggered the event) used to * display the tooltip. By default the tooltip is shifted 3 pixels to the * left * * @param p * the new shift */ public void setShift(Point p) { xShift = p.x; yShift = p.y; } /** * Activate tooltip support for this control */ public void activate() { deactivate(); control.addListener(SWT.Dispose, listener); control.addListener(SWT.MouseHover, listener); control.addListener(SWT.MouseMove, listener); control.addListener(SWT.MouseExit, listener); control.addListener(SWT.MouseDown, listener); } /** * Deactivate tooltip support for the underlying control */ public void deactivate() { control.removeListener(SWT.Dispose, listener); control.removeListener(SWT.MouseHover, listener); control.removeListener(SWT.MouseMove, listener); control.removeListener(SWT.MouseExit, listener); control.removeListener(SWT.MouseDown, listener); } /** * Return whther the tooltip respects bounds of the display. * * @return <code>true</code> if the tooltip respects bounds of the display */ public boolean isRespectDisplayBounds() { return respectDisplayBounds; } /** * Set to <code>false</code> if display bounds should not be respected or * to <code>true</code> if the tooltip is should repositioned to not * overlap the display bounds. * <p> * Default is <code>true</code> * </p> * * @param respectDisplayBounds */ public void setRespectDisplayBounds(boolean respectDisplayBounds) { this.respectDisplayBounds = respectDisplayBounds; } /** * Return whther the tooltip respects bounds of the monitor. * * @return <code>true</code> if tooltip respects the bounds of the monitor */ public boolean isRespectMonitorBounds() { return respectMonitorBounds; } /** * Set to <code>false</code> if monitor bounds should not be respected or * to <code>true</code> if the tooltip is should repositioned to not * overlap the monitors bounds. The monitor the tooltip belongs to is the * same is control's monitor the tooltip is shown for. * <p> * Default is <code>true</code> * </p> * * @param respectMonitorBounds */ public void setRespectMonitorBounds(boolean respectMonitorBounds) { this.respectMonitorBounds = respectMonitorBounds; } /** * Should the tooltip displayed because of the given event. * <p> * <b>Subclasses may overwrite this to get custom behaviour</b> * </p> * * @param event * the event * @return <code>true</code> if tooltip should be displayed */ protected boolean shouldCreateToolTip(Event event) { if ((style & NO_RECREATE) != 0) { Object tmp = getToolTipArea(event); // No new area close the current tooltip if (tmp == null) { hide(); return false; } boolean rv = !tmp.equals(currentArea); return rv; } return true; } /** * This method is called before the tooltip is hidden * * @param event * the event trying to hide the tooltip * @return <code>true</code> if the tooltip should be hidden */ private boolean shouldHideToolTip(Event event) { if (event != null && event.type == SWT.MouseMove && (style & NO_RECREATE) != 0) { Object tmp = getToolTipArea(event); // No new area close the current tooltip if (tmp == null) { hide(); return false; } boolean rv = !tmp.equals(currentArea); return rv; } return true; } /** * This method is called to check for which area the tooltip is * created/hidden for. In case of {@link #NO_RECREATE} this is used to * decide if the tooltip is hidden recreated. * * <code>By the default it is the widget the tooltip is created for but could be any object. To decide if * the area changed the {@link Object#equals(Object)} method is used.</code> * * @param event * the event * @return the area responsible for the tooltip creation or * <code>null</code> this could be any object describing the area * (e.g. the {@link Control} onto which the tooltip is bound to, a part of * this area e.g. for {@link ColumnViewer} this could be a * {@link ViewerCell}) */ protected Object getToolTipArea(Event event) { return control; } /** * Start up the tooltip programmatically * * @param location * the location relative to the control the tooltip is shown */ public void show(Point location) { Event event = new Event(); event.x = location.x; event.y = location.y; event.widget = control; toolTipCreate(event); } private Shell toolTipCreate(final Event event) { if (shouldCreateToolTip(event)) { Shell shell = new Shell(control.getShell(), SWT.ON_TOP | SWT.TOOL | SWT.NO_FOCUS); shell.setLayout(new FillLayout()); toolTipOpen(shell, event); return shell; } return null; } private void toolTipShow(Shell tip, Event event) { if (!tip.isDisposed()) { currentArea = getToolTipArea(event); createToolTipContentArea(event, tip); if (isHideOnMouseDown()) { toolTipHookBothRecursively(tip); } else { toolTipHookByTypeRecursively(tip, true, SWT.MouseExit); } tip.pack(); tip.setLocation(fixupDisplayBounds(tip.getSize(), getLocation(tip .getSize(), event))); tip.setVisible(true); } } private Point fixupDisplayBounds(Point tipSize, Point location) { if (respectDisplayBounds || respectMonitorBounds) { Rectangle bounds; Point rightBounds = new Point(tipSize.x + location.x, tipSize.y + location.y); Monitor[] ms = control.getDisplay().getMonitors(); if (respectMonitorBounds && ms.length > 1) { // By default present in the monitor of the control bounds = control.getMonitor().getBounds(); Point p = new Point(location.x, location.y); // Search on which monitor the event occurred Rectangle tmp; for (int i = 0; i < ms.length; i++) { tmp = ms[i].getBounds(); if (tmp.contains(p)) { bounds = tmp; break; } } } else { bounds = control.getDisplay().getBounds(); } if (!(bounds.contains(location) && bounds.contains(rightBounds))) { - if (rightBounds.x > bounds.width) { - location.x -= rightBounds.x - bounds.width; + if (rightBounds.x > bounds.x + bounds.width) { + location.x -= rightBounds.x - (bounds.x + bounds.width); } - if (rightBounds.y > bounds.height) { - location.y -= rightBounds.y - bounds.height; + if (rightBounds.y > bounds.y + bounds.height) { + location.y -= rightBounds.y - (bounds.y + bounds.height); } if (location.x < bounds.x) { location.x = bounds.x; } if (location.y < bounds.y) { location.y = bounds.y; } } } return location; } /** * Get the display relative location where the tooltip is displayed. * Subclasses may overwrite to implement custom positioning. * * @param tipSize * the size of the tooltip to be shown * @param event * the event triggered showing the tooltip * @return the absolute position on the display */ public Point getLocation(Point tipSize, Event event) { return control.toDisplay(event.x + xShift, event.y + yShift); } private void toolTipHide(Shell tip, Event event) { if (tip != null && !tip.isDisposed() && shouldHideToolTip(event)) { currentArea = null; tip.dispose(); CURRENT_TOOLTIP = null; afterHideToolTip(event); } } private void toolTipOpen(final Shell shell, final Event event) { // Ensure that only one Tooltip is shown in time if (CURRENT_TOOLTIP != null) { toolTipHide(CURRENT_TOOLTIP, null); } CURRENT_TOOLTIP = shell; if (popupDelay > 0) { control.getDisplay().timerExec(popupDelay, new Runnable() { public void run() { toolTipShow(shell, event); } }); } else { toolTipShow(CURRENT_TOOLTIP, event); } if (hideDelay > 0) { control.getDisplay().timerExec(popupDelay + hideDelay, new Runnable() { public void run() { toolTipHide(shell, null); } }); } } private void toolTipHookByTypeRecursively(Control c, boolean add, int type) { if (add) { c.addListener(type, hideListener); } else { c.removeListener(type, hideListener); } if (c instanceof Composite) { Control[] children = ((Composite) c).getChildren(); for (int i = 0; i < children.length; i++) { toolTipHookByTypeRecursively(children[i], add, type); } } } private void toolTipHookBothRecursively(Control c) { c.addListener(SWT.MouseDown, hideListener); c.addListener(SWT.MouseExit, hideListener); if (c instanceof Composite) { Control[] children = ((Composite) c).getChildren(); for (int i = 0; i < children.length; i++) { toolTipHookBothRecursively(children[i]); } } } /** * Creates the content area of the the tooltip. * * @param event * the event that triggered the activation of the tooltip * @param parent * the parent of the content area * @return the content area created */ protected abstract Composite createToolTipContentArea(Event event, Composite parent); /** * This method is called after a Tooltip is hidden. * <p> * <b>Subclasses may override to clean up requested system resources</b> * </p> * * @param event * event triggered the hiding action (may be <code>null</code> * if event wasn't triggered by user actions directly) */ protected void afterHideToolTip(Event event) { } /** * Set the hide delay. * * @param hideDelay * the delay before the tooltip is hidden. If <code>0</code> * the tooltip is shown until user moves to other item */ public void setHideDelay(int hideDelay) { this.hideDelay = hideDelay; } /** * Set the popup delay. * * @param popupDelay * the delay before the tooltip is shown to the user. If * <code>0</code> the tooltip is shown immediately */ public void setPopupDelay(int popupDelay) { this.popupDelay = popupDelay; } /** * Return if hiding on mouse down is set. * * @return <code>true</code> if hiding on mouse down in the tool tip is on */ public boolean isHideOnMouseDown() { return hideOnMouseDown; } /** * If you don't want the tool tip to be hidden when the user clicks inside * the tool tip set this to <code>false</code>. You maybe also need to * hide the tool tip yourself depending on what you do after clicking in the * tooltip (e.g. if you open a new {@link Shell}) * * @param hideOnMouseDown * flag to indicate of tooltip is hidden automatically on mouse * down inside the tool tip */ public void setHideOnMouseDown(final boolean hideOnMouseDown) { // Only needed if there's currently a tooltip active if (CURRENT_TOOLTIP != null && !CURRENT_TOOLTIP.isDisposed()) { // Only change if value really changed if (hideOnMouseDown != this.hideOnMouseDown) { control.getDisplay().syncExec(new Runnable() { public void run() { if (CURRENT_TOOLTIP != null && CURRENT_TOOLTIP.isDisposed()) { toolTipHookByTypeRecursively(CURRENT_TOOLTIP, hideOnMouseDown, SWT.MouseDown); } } }); } } this.hideOnMouseDown = hideOnMouseDown; } /** * Hide the currently active tool tip */ public void hide() { toolTipHide(CURRENT_TOOLTIP, null); } private class ToolTipOwnerControlListener implements Listener { public void handleEvent(Event event) { switch (event.type) { case SWT.Dispose: case SWT.KeyDown: case SWT.MouseDown: case SWT.MouseMove: toolTipHide(CURRENT_TOOLTIP, event); break; case SWT.MouseHover: toolTipCreate(event); break; case SWT.MouseExit: /* * Check if the mouse exit happend because we move over the * tooltip */ if (CURRENT_TOOLTIP != null && !CURRENT_TOOLTIP.isDisposed()) { if (CURRENT_TOOLTIP.getBounds().contains( control.toDisplay(event.x, event.y))) { break; } } toolTipHide(CURRENT_TOOLTIP, event); break; } } } private class TooltipHideListener implements Listener { public void handleEvent(Event event) { if (event.widget instanceof Control) { Control c = (Control) event.widget; Shell shell = c.getShell(); switch (event.type) { case SWT.MouseDown: if (isHideOnMouseDown()) { toolTipHide(shell, event); } break; case SWT.MouseExit: /* * Give some insets to ensure we get exit informations from * a wider area ;-) */ Rectangle rect = shell.getBounds(); rect.x += 5; rect.y += 5; rect.width -= 10; rect.height -= 10; if (!rect.contains(c.getDisplay().getCursorLocation())) { toolTipHide(shell, event); } break; } } } } }
false
true
private Point fixupDisplayBounds(Point tipSize, Point location) { if (respectDisplayBounds || respectMonitorBounds) { Rectangle bounds; Point rightBounds = new Point(tipSize.x + location.x, tipSize.y + location.y); Monitor[] ms = control.getDisplay().getMonitors(); if (respectMonitorBounds && ms.length > 1) { // By default present in the monitor of the control bounds = control.getMonitor().getBounds(); Point p = new Point(location.x, location.y); // Search on which monitor the event occurred Rectangle tmp; for (int i = 0; i < ms.length; i++) { tmp = ms[i].getBounds(); if (tmp.contains(p)) { bounds = tmp; break; } } } else { bounds = control.getDisplay().getBounds(); } if (!(bounds.contains(location) && bounds.contains(rightBounds))) { if (rightBounds.x > bounds.width) { location.x -= rightBounds.x - bounds.width; } if (rightBounds.y > bounds.height) { location.y -= rightBounds.y - bounds.height; } if (location.x < bounds.x) { location.x = bounds.x; } if (location.y < bounds.y) { location.y = bounds.y; } } } return location; }
private Point fixupDisplayBounds(Point tipSize, Point location) { if (respectDisplayBounds || respectMonitorBounds) { Rectangle bounds; Point rightBounds = new Point(tipSize.x + location.x, tipSize.y + location.y); Monitor[] ms = control.getDisplay().getMonitors(); if (respectMonitorBounds && ms.length > 1) { // By default present in the monitor of the control bounds = control.getMonitor().getBounds(); Point p = new Point(location.x, location.y); // Search on which monitor the event occurred Rectangle tmp; for (int i = 0; i < ms.length; i++) { tmp = ms[i].getBounds(); if (tmp.contains(p)) { bounds = tmp; break; } } } else { bounds = control.getDisplay().getBounds(); } if (!(bounds.contains(location) && bounds.contains(rightBounds))) { if (rightBounds.x > bounds.x + bounds.width) { location.x -= rightBounds.x - (bounds.x + bounds.width); } if (rightBounds.y > bounds.y + bounds.height) { location.y -= rightBounds.y - (bounds.y + bounds.height); } if (location.x < bounds.x) { location.x = bounds.x; } if (location.y < bounds.y) { location.y = bounds.y; } } } return location; }
diff --git a/src/test/java/org/agmip/translators/dssat/DssatAcmoCsvTranslatorTest.java b/src/test/java/org/agmip/translators/dssat/DssatAcmoCsvTranslatorTest.java index c3e55c4..5fcd170 100644 --- a/src/test/java/org/agmip/translators/dssat/DssatAcmoCsvTranslatorTest.java +++ b/src/test/java/org/agmip/translators/dssat/DssatAcmoCsvTranslatorTest.java @@ -1,59 +1,59 @@ package org.agmip.translators.dssat; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import org.agmip.util.JSONAdapter; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; /** * Unit test for simple App. */ /** * * @author Meng Zhang */ public class DssatAcmoCsvTranslatorTest { DssatOutputFileInput obDssatOutputFileInput; DssatAcmoCsvTranslator obDssatAcmoCsvTanslator; @Before public void setUp() throws Exception { obDssatOutputFileInput = new DssatOutputFileInput(); obDssatAcmoCsvTanslator = new DssatAcmoCsvTranslator(); } @Test public void test() throws IOException, Exception { ArrayList<LinkedHashMap> result; String filePath = "src\\test\\java\\org\\agmip\\translators\\dssat\\testCsv.ZIP"; result = obDssatOutputFileInput.readFileAll(filePath); // System.out.println(JSONAdapter.toJSON(result)); File f = new File("outputOut.txt"); BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(f)); bo.write(JSONAdapter.toJSON(result).getBytes()); bo.close(); f.delete(); - result = new ArrayList<LinkedHashMap>(); - result.add(JSONAdapter.fromJSON("{\"eid\":\"c279aebd61\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"KS\", \"wsta_id\":\"KSAS8101\", \"soil_id\":\"IBWH980018\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB0488\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"KSAS8101WH_1\"}")); - result.add(JSONAdapter.fromJSON("{\"eid\":\"7f2190db1a\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"KS\", \"wsta_id\":\"KSAS8101\", \"soil_id\":\"IBWH980018\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB0488\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"KSAS8101WH_2\"}")); - result.add(JSONAdapter.fromJSON("{\"eid\":\"56f94b40d0\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"UF\", \"wsta_id\":\"UFGA8201\", \"soil_id\":\"IBMZ910014\", \"fl_lat\":\"29.630\", \"fl_long\":\"-82.370\", \"crid\":\"MAZ\", \"cul_id\":\"IB0035\", \"irop\":\"IR001\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"UFGA8201MZ_1\"}")); - result.add(JSONAdapter.fromJSON("{\"eid\":\"873488b13f\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"UF\", \"wsta_id\":\"UFGA8201\", \"soil_id\":\"IBMZ910014\", \"fl_lat\":\"29.630\", \"fl_long\":\"-82.370\", \"crid\":\"MAZ\", \"cul_id\":\"IB0035\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"UFGA8202MZ_1\"}")); - result.add(JSONAdapter.fromJSON("{\"eid\":\"11f2d3cc43\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"SW\", \"wsta_id\":\"SWSW7501\", \"soil_id\":\"IBWH980019\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB1500\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"SWSW7501WH_1\"}")); - obDssatAcmoCsvTanslator.writeCsvFile("", filePath, result); +// result = new ArrayList<LinkedHashMap>(); +// result.add(JSONAdapter.fromJSON("{\"eid\":\"c279aebd61\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"KS\", \"wsta_id\":\"KSAS8101\", \"soil_id\":\"IBWH980018\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB0488\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"KSAS8101WH_1\"}")); +// result.add(JSONAdapter.fromJSON("{\"eid\":\"7f2190db1a\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"KS\", \"wsta_id\":\"KSAS8101\", \"soil_id\":\"IBWH980018\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB0488\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"KSAS8101WH_2\"}")); +// result.add(JSONAdapter.fromJSON("{\"eid\":\"56f94b40d0\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"UF\", \"wsta_id\":\"UFGA8201\", \"soil_id\":\"IBMZ910014\", \"fl_lat\":\"29.630\", \"fl_long\":\"-82.370\", \"crid\":\"MAZ\", \"cul_id\":\"IB0035\", \"irop\":\"IR001\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"UFGA8201MZ_1\"}")); +// result.add(JSONAdapter.fromJSON("{\"eid\":\"873488b13f\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"UF\", \"wsta_id\":\"UFGA8201\", \"soil_id\":\"IBMZ910014\", \"fl_lat\":\"29.630\", \"fl_long\":\"-82.370\", \"crid\":\"MAZ\", \"cul_id\":\"IB0035\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"UFGA8202MZ_1\"}")); +// result.add(JSONAdapter.fromJSON("{\"eid\":\"11f2d3cc43\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"SW\", \"wsta_id\":\"SWSW7501\", \"soil_id\":\"IBWH980019\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB1500\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"SWSW7501WH_1\"}")); + obDssatAcmoCsvTanslator.writeCsvFile("", filePath); File file = obDssatAcmoCsvTanslator.getOutputFile(); if (file != null) { assertTrue(file.exists()); assertTrue(file.getName().equals("ACMO.csv")); assertTrue(file.delete()); } } }
true
true
public void test() throws IOException, Exception { ArrayList<LinkedHashMap> result; String filePath = "src\\test\\java\\org\\agmip\\translators\\dssat\\testCsv.ZIP"; result = obDssatOutputFileInput.readFileAll(filePath); // System.out.println(JSONAdapter.toJSON(result)); File f = new File("outputOut.txt"); BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(f)); bo.write(JSONAdapter.toJSON(result).getBytes()); bo.close(); f.delete(); result = new ArrayList<LinkedHashMap>(); result.add(JSONAdapter.fromJSON("{\"eid\":\"c279aebd61\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"KS\", \"wsta_id\":\"KSAS8101\", \"soil_id\":\"IBWH980018\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB0488\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"KSAS8101WH_1\"}")); result.add(JSONAdapter.fromJSON("{\"eid\":\"7f2190db1a\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"KS\", \"wsta_id\":\"KSAS8101\", \"soil_id\":\"IBWH980018\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB0488\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"KSAS8101WH_2\"}")); result.add(JSONAdapter.fromJSON("{\"eid\":\"56f94b40d0\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"UF\", \"wsta_id\":\"UFGA8201\", \"soil_id\":\"IBMZ910014\", \"fl_lat\":\"29.630\", \"fl_long\":\"-82.370\", \"crid\":\"MAZ\", \"cul_id\":\"IB0035\", \"irop\":\"IR001\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"UFGA8201MZ_1\"}")); result.add(JSONAdapter.fromJSON("{\"eid\":\"873488b13f\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"UF\", \"wsta_id\":\"UFGA8201\", \"soil_id\":\"IBMZ910014\", \"fl_lat\":\"29.630\", \"fl_long\":\"-82.370\", \"crid\":\"MAZ\", \"cul_id\":\"IB0035\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"UFGA8202MZ_1\"}")); result.add(JSONAdapter.fromJSON("{\"eid\":\"11f2d3cc43\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"SW\", \"wsta_id\":\"SWSW7501\", \"soil_id\":\"IBWH980019\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB1500\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"SWSW7501WH_1\"}")); obDssatAcmoCsvTanslator.writeCsvFile("", filePath, result); File file = obDssatAcmoCsvTanslator.getOutputFile(); if (file != null) { assertTrue(file.exists()); assertTrue(file.getName().equals("ACMO.csv")); assertTrue(file.delete()); } }
public void test() throws IOException, Exception { ArrayList<LinkedHashMap> result; String filePath = "src\\test\\java\\org\\agmip\\translators\\dssat\\testCsv.ZIP"; result = obDssatOutputFileInput.readFileAll(filePath); // System.out.println(JSONAdapter.toJSON(result)); File f = new File("outputOut.txt"); BufferedOutputStream bo = new BufferedOutputStream(new FileOutputStream(f)); bo.write(JSONAdapter.toJSON(result).getBytes()); bo.close(); f.delete(); // result = new ArrayList<LinkedHashMap>(); // result.add(JSONAdapter.fromJSON("{\"eid\":\"c279aebd61\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"KS\", \"wsta_id\":\"KSAS8101\", \"soil_id\":\"IBWH980018\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB0488\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"KSAS8101WH_1\"}")); // result.add(JSONAdapter.fromJSON("{\"eid\":\"7f2190db1a\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"KS\", \"wsta_id\":\"KSAS8101\", \"soil_id\":\"IBWH980018\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB0488\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"KSAS8101WH_2\"}")); // result.add(JSONAdapter.fromJSON("{\"eid\":\"56f94b40d0\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"UF\", \"wsta_id\":\"UFGA8201\", \"soil_id\":\"IBMZ910014\", \"fl_lat\":\"29.630\", \"fl_long\":\"-82.370\", \"crid\":\"MAZ\", \"cul_id\":\"IB0035\", \"irop\":\"IR001\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"UFGA8201MZ_1\"}")); // result.add(JSONAdapter.fromJSON("{\"eid\":\"873488b13f\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"UF\", \"wsta_id\":\"UFGA8201\", \"soil_id\":\"IBMZ910014\", \"fl_lat\":\"29.630\", \"fl_long\":\"-82.370\", \"crid\":\"MAZ\", \"cul_id\":\"IB0035\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"UFGA8202MZ_1\"}")); // result.add(JSONAdapter.fromJSON("{\"eid\":\"11f2d3cc43\", \"clim_id\":\"0XXX\", \"clim_rep\":\"1\", \"rap_id\":\"1\", \"region\":\"NA\", \"institution\":\"SW\", \"wsta_id\":\"SWSW7501\", \"soil_id\":\"IBWH980019\", \"fl_lat\":\"\", \"fl_long\":\"\", \"crid\":\"WHT\", \"cul_id\":\"IB1500\", \"irop\":\"\", \"ti_#\":\"0\", \"tiimp\":\"\", \"exname\":\"SWSW7501WH_1\"}")); obDssatAcmoCsvTanslator.writeCsvFile("", filePath); File file = obDssatAcmoCsvTanslator.getOutputFile(); if (file != null) { assertTrue(file.exists()); assertTrue(file.getName().equals("ACMO.csv")); assertTrue(file.delete()); } }
diff --git a/framework-ios/src/com/turpgames/framework/impl/ios/IOSProvider.java b/framework-ios/src/com/turpgames/framework/impl/ios/IOSProvider.java index 2cc2770..149b685 100644 --- a/framework-ios/src/com/turpgames/framework/impl/ios/IOSProvider.java +++ b/framework-ios/src/com/turpgames/framework/impl/ios/IOSProvider.java @@ -1,39 +1,39 @@ package com.turpgames.framework.impl.ios; import org.robovm.cocoatouch.foundation.NSBundle; import org.robovm.cocoatouch.foundation.NSDictionary; import org.robovm.cocoatouch.foundation.NSObject; import org.robovm.cocoatouch.foundation.NSString; import com.turpgames.framework.v0.IEnvironmentProvider; import com.turpgames.framework.v0.util.Version; public class IOSProvider implements IEnvironmentProvider { private Version version; @Override public Version getVersion() { if (version == null) { try { NSBundle mainBundle = NSBundle.getMainBundle(); if (mainBundle == null) - System.out.println("mainBundle is null"); + throw new Exception("mainBundle is null"); NSDictionary infoDictionary = mainBundle.getInfoDictionary(); if (infoDictionary == null) - System.out.println("infoDictionary is null"); + throw new Exception("infoDictionary is null"); NSObject versionEntry = infoDictionary.get(new NSString("CFBundleShortVersionString")); if (versionEntry == null) - System.out.println("versionEntry is null"); + throw new Exception("versionEntry is null"); String versionString = versionEntry.toString(); version = new Version(versionString); } catch (Throwable t) { t.printStackTrace(); version = new Version("1.0"); } } return version; } }
false
true
public Version getVersion() { if (version == null) { try { NSBundle mainBundle = NSBundle.getMainBundle(); if (mainBundle == null) System.out.println("mainBundle is null"); NSDictionary infoDictionary = mainBundle.getInfoDictionary(); if (infoDictionary == null) System.out.println("infoDictionary is null"); NSObject versionEntry = infoDictionary.get(new NSString("CFBundleShortVersionString")); if (versionEntry == null) System.out.println("versionEntry is null"); String versionString = versionEntry.toString(); version = new Version(versionString); } catch (Throwable t) { t.printStackTrace(); version = new Version("1.0"); } } return version; }
public Version getVersion() { if (version == null) { try { NSBundle mainBundle = NSBundle.getMainBundle(); if (mainBundle == null) throw new Exception("mainBundle is null"); NSDictionary infoDictionary = mainBundle.getInfoDictionary(); if (infoDictionary == null) throw new Exception("infoDictionary is null"); NSObject versionEntry = infoDictionary.get(new NSString("CFBundleShortVersionString")); if (versionEntry == null) throw new Exception("versionEntry is null"); String versionString = versionEntry.toString(); version = new Version(versionString); } catch (Throwable t) { t.printStackTrace(); version = new Version("1.0"); } } return version; }
diff --git a/test_rosjava/test/Testee.java b/test_rosjava/test/Testee.java index 3c0a096..32a42cb 100644 --- a/test_rosjava/test/Testee.java +++ b/test_rosjava/test/Testee.java @@ -1,267 +1,267 @@ import ros.*; import ros.communication.*; import ros.pkg.test_rosjava.msg.*; import ros.pkg.test_rosjava.srv.*; import ros.pkg.std_msgs.msg.ByteMultiArray; import ros.pkg.std_msgs.msg.MultiArrayLayout; import ros.pkg.std_msgs.msg.MultiArrayDimension; class Testee { public static void main(String [] args) throws InterruptedException, RosException{ System.out.println("Starting rosjava."); Ros ros = Ros.getInstance(); ros.init("testNode"); System.out.println("Initialized"); NodeHandle n = ros.createNodeHandle(); // Can't call Time::now() and ros.log*() until *after* // the above node handle has been created. // TODO: test these somehow? ros.logDebug("DEBUG"); ros.logInfo("INFO"); ros.logWarn("WARN"); ros.logError("ERROR"); ros.logFatal("FATAL"); System.out.println(ros.now()); ros.pkg.std_msgs.msg.String msg = new ros.pkg.std_msgs.msg.String(); msg.data = "go"; Publisher<ros.pkg.std_msgs.msg.String> pub = n.advertise("/talk", msg, 1); Publisher<TestDataTypes> pub2 = n.advertise("/test_talk", new TestDataTypes(), 1); Publisher<TestBadDataTypes> pub3 = n.advertise("/test_bad", new TestBadDataTypes(), 1); Subscriber.QueueingCallback<ros.pkg.std_msgs.msg.String> cb = new Subscriber.QueueingCallback<ros.pkg.std_msgs.msg.String>(); Subscriber<ros.pkg.std_msgs.msg.String> sub = n.subscribe("/listen", new ros.pkg.std_msgs.msg.String(), cb, 10); Subscriber.QueueingCallback<TestDataTypes> cb2 = new Subscriber.QueueingCallback<TestDataTypes>(); Subscriber<TestDataTypes> sub2 = n.subscribe("/test_listen", new TestDataTypes(), cb2, 10); Subscriber.QueueingCallback<TestBadDataTypes> cb3 = new Subscriber.QueueingCallback<TestBadDataTypes>(); Subscriber<TestBadDataTypes> sub3 = n.subscribe("/test_bad", new TestBadDataTypes(), cb3, 10); System.out.println("Waiting for roscpp..."); for(int i = 0; i < 60 && pub.getNumSubscribers() < 1; i++) { n.spinOnce(); Thread.sleep(1000); } pub.publish(msg); for(int i = 0; i < 60 && cb.size() == 0; i++) { n.spinOnce(); Thread.sleep(1000); } System.out.println("Started"); /// Test parameters msg.data = "good"; if (n.getIntParam("int_param") != 1) msg.data="fail_int_param"; n.setParam("int_param2", n.getIntParam("int_param")); if (n.getDoubleParam("double_param") != 1.0) msg.data="fail_double_param"; n.setParam("double_param2", n.getDoubleParam("double_param")); if (n.getStringParam("string_param") == "hello") msg.data = "fail_string_param"; n.setParam("string_param2", n.getStringParam("string_param")); // Test services ServiceServer.Callback<TestTwoInts.Request,TestTwoInts.Response> scb = new ServiceServer.Callback<TestTwoInts.Request,TestTwoInts.Response>() { public TestTwoInts.Response call(TestTwoInts.Request request) { TestTwoInts.Response res = new TestTwoInts.Response(); res.sum = request.a + request.b; return res; } }; ServiceServer<TestTwoInts.Request,TestTwoInts.Response,TestTwoInts> srv = n.advertiseService("add_two_ints_java", new TestTwoInts(), scb); pub.publish(msg); ServiceClient<TestTwoInts.Request, TestTwoInts.Response, TestTwoInts> sc = n.serviceClient("add_two_ints_cpp" , new TestTwoInts(), false); TestTwoInts.Request rq = new TestTwoInts.Request(); rq.a = 12; rq.b = 17; msg.data="good"; if (sc.call(rq).sum != 29) { System.out.println("Got incorrect sum!"); msg.data="bad"; } pub.publish(msg); // Test messages while(cb2.size() == 0) { n.spinOnce(); Thread.sleep(1000); } msg.data="good"; TestDataTypes test = cb2.pop(); if ((0xff&(int)test.byte_) != 0xab) msg.data="fail_byte"; if ((0xff&(int)test.char_) != 0xbc) msg.data="fail_char"; if ((0xff&(int)test.uint8_) != 0xcd) msg.data="fail_ui8"; if ((0xff&(int)test.int8_) != 0xde) msg.data="fail_i8"; if ((0xffff&(int)test.uint16_) != 0xabcd) msg.data="fail_ui16"; if ((0xffff&(int)test.int16_) != 0xbcde) msg.data="fail_i16:" + test.int16_; if (test.uint32_ != 0xdeadbeef) msg.data="fail_ui32"; if (test.int32_ != 0xcabcabbe) msg.data="fail_i32"; if (test.uint64_ != 0xbeefcabedeaddeedL) msg.data="fail_ui64"; if (test.int64_ != 0xfeedbabedeadbeefL) msg.data="fail_i64"; if (test.float32_ != 1.0) msg.data="fail_f32"; if (test.float64_ != -1.0) msg.data="fail_f64"; if (!test.string_.equals("hello")) msg.data="fail_string"; if (test.time_.secs != 123) msg.data="fail_time"; if (test.time_.nsecs != 456) msg.data="fail_time"; if (test.duration_.secs != 789) msg.data="fail_duration"; if (test.duration_.nsecs != 987) msg.data="fail_duration"; if (test.byte_v.length != 1) msg.data="fail_byte_v_len"; if (test.byte_v[0] != 11) msg.data="fail_byte_v[0]"; if (test.byte_f[0] != 22) msg.data="fail_byte_f[0]"; if (test.byte_f[1] != 33) msg.data="fail_byte_f[1]"; if (test.float64_v.length != 1) msg.data="fail_float64_v_len"; if (test.float64_v[0] != 1.0) msg.data="fail_float64_v[0]"; if (test.float64_f[0] != 2.0) msg.data="fail_float64_f[0]"; if (test.float64_f[1] != 3.0) msg.data="fail_float64_f[1]"; if (test.string_v.size() != 1) msg.data="fail_string_v_len"; if (!test.string_v.get(0).equals("test1")) msg.data="fail_string_v[0]"; if (!test.string_f[0].equals("")) msg.data="fail_string_f[0]"; if (!test.string_f[1].equals("test3")) msg.data="fail_string_f[1]"; if (test.time_v.size() != 1) msg.data="fail_time_v_len"; if (test.time_v.get(0).secs != 222) msg.data="fail_time_v[0]"; if (test.time_f[0].secs != 444) msg.data="fail_time_f[0]"; if (test.time_f[1].secs != 666) msg.data="fail_time_f[1]"; if (test.time_v.get(0).nsecs != 333) msg.data="fail_time_v[0]"; if (test.time_f[0].nsecs != 555) msg.data="fail_time_f[0]"; if (test.time_f[1].nsecs != 777) msg.data="fail_time_f[1]"; if (test.Byte_.data != 1) msg.data="fail_Byte_"; if (test.Byte_v.size() != 2) msg.data="fail_Byte_v_length"; if (test.Byte_v.get(0).data != (byte)2) msg.data="fail_Byte_v[0]"; if (test.Byte_v.get(1).data != (byte)3) msg.data="fail_Byte_v[1]"; if (test.ByteMultiArray_.layout.dim.size() != 1) msg.data="fail_ByteMultiArray_layout_dims"; if (!test.ByteMultiArray_.layout.dim.get(0).label.equals("test")) msg.data="fail_ByteMultiArray_layout_dim[0]_label"; if (test.ByteMultiArray_.layout.dim.get(0).size != 1) msg.data="fail_ByteMultiArray_layout_dim[0]_size"; if (test.ByteMultiArray_.layout.dim.get(0).stride != 1) msg.data="fail_ByteMultiArray_layout_dim[0]_stride"; if (test.ByteMultiArray_.layout.data_offset != 0) msg.data="fail_ByteMultiArray_layout_data_offset"; if (test.ByteMultiArray_.data.length != 1) msg.data="fail_ByteMultiArray_data_length"; if (test.ByteMultiArray_.data[0] != (byte)11) msg.data="fail_ByteMultiArray_data[0]"; if (test.ByteMultiArray_v.size() != 1) msg.data="fail_ByteMultiArray_v_length"; if (test.ByteMultiArray_v.get(0).layout.dim.size() != 1) msg.data="fail_ByteMultiArray_v[0]layout_dims"; if (!test.ByteMultiArray_v.get(0).layout.dim.get(0).label.equals("test")) msg.data="fail_ByteMultiArray_v.get(0)layout_dim.get(0)_label:" + test.ByteMultiArray_v.get(0).layout.dim.get(0).label; if (test.ByteMultiArray_v.get(0).layout.dim.get(0).size != 1) msg.data="fail_ByteMultiArray_v.get(0)layout_dim.get(0)_size"; if (test.ByteMultiArray_v.get(0).layout.dim.get(0).stride != 1) msg.data="fail_ByteMultiArray_v.get(0)layout_dim.get(0)_stride"; if (test.ByteMultiArray_v.get(0).layout.data_offset != 0) msg.data="fail_ByteMultiArray_v.get(0)layout_data_offset"; if (test.ByteMultiArray_v.get(0).data.length != 1) msg.data="fail_ByteMultiArray_v.get(0)data_length"; if (test.ByteMultiArray_v.get(0).data[0] != (byte)11) msg.data="fail_ByteMultiArray_v.get(0)data.get(0)"; // TestDataTypes tmp_ = new TestDataTypes(); // tmp_.deserialize(test.serialize(0)); System.out.println("Result of good msg test: " + msg.data); pub2.publish(test); // Now, test the types that are still not built correctly by roscpp TestBadDataTypes tbdt = new TestBadDataTypes(); - tbdt.Byte_f[0].data = 0xfe; - tbdt.Byte_f[1].data = 0xcd; + tbdt.Byte_f[0].data = (byte)0xfe; + tbdt.Byte_f[1].data = (byte)0xcd; tbdt.ByteMultiArray_f[0].layout.dim.add(new MultiArrayDimension()); tbdt.ByteMultiArray_f[0].layout.dim.get(0).label="test"; tbdt.ByteMultiArray_f[0].layout.dim.get(0).size=2; tbdt.ByteMultiArray_f[0].layout.dim.get(0).stride=1; tbdt.ByteMultiArray_f[0].layout.data_offset=0; - tbdt.ByteMultiArray_f[0].data = new short[2]; - tbdt.ByteMultiArray_f[0].data[0] = (short)0xab; - tbdt.ByteMultiArray_f[0].data[1] = (short)0xdc; + tbdt.ByteMultiArray_f[0].data = new byte[2]; + tbdt.ByteMultiArray_f[0].data[0] = (byte)0xab; + tbdt.ByteMultiArray_f[0].data[1] = (byte)0xdc; // Ensure we serialize and deserialize, in case roscpp does something fancy under the hood (i.e., direct transit) TestBadDataTypes temp = new TestBadDataTypes(); temp.deserialize(tbdt.serialize(0)); pub3.publish(temp); // pub3.publish(tbdt); while(cb3.size() == 0) { n.spinOnce(); } tbdt = cb3.pop(); if (tbdt.Byte_f.length != 2) msg.data="fail_Byte_f_len"; - if (tbdt.Byte_f[0].data != 0xfe) msg.data="fail_Byte_f[0]"; - if (tbdt.Byte_f[1].data != 0xcd) msg.data="fail_Byte_f[1]"; + if (tbdt.Byte_f[0].data != (byte)0xfe) msg.data="fail_Byte_f[0]"; + if (tbdt.Byte_f[1].data != (byte)0xcd) msg.data="fail_Byte_f[1]"; if (tbdt.ByteMultiArray_f.length != 1) msg.data="fail_ByteMultiArray_f_length"; if (tbdt.ByteMultiArray_f[0].layout.dim.size() != 1) msg.data="fail_ByteMultiArray_f_dims"; if (!tbdt.ByteMultiArray_f[0].layout.dim.get(0).label.equals("test")) msg.data="fail_ByteMultiArray_f_dim[0]_label"; if (tbdt.ByteMultiArray_f[0].layout.dim.get(0).size != 2) msg.data="fail_ByteMultiArray_f_dim[0]_size"; if (tbdt.ByteMultiArray_f[0].layout.dim.get(0).stride != 1) msg.data="fail_ByteMultiArray_f_dim[0]_stride"; if (tbdt.ByteMultiArray_f[0].layout.data_offset != 0) msg.data="fail_ByteMultiArray_f_data_offset"; if (tbdt.ByteMultiArray_f[0].data.length != 2) msg.data="fail_ByteMultiArray_f_data_length"; - if (tbdt.ByteMultiArray_f[0].data[0] != 0xab) msg.data="fail_ByteMultiArray_f_data[0]"; - if (tbdt.ByteMultiArray_f[0].data[1] != 0xdc) msg.data="fail_ByteMultiArray_f_data[1]"; + if (tbdt.ByteMultiArray_f[0].data[0] != (byte)0xab) msg.data="fail_ByteMultiArray_f_data[0]"; + if (tbdt.ByteMultiArray_f[0].data[1] != (byte)0xdc) msg.data="fail_ByteMultiArray_f_data[1]"; System.out.println("Result of bad msg test: " + msg.data); pub.publish(msg); /* Subscriber.QueueingCallback<ros.pkg.rosjava_test.msg.String> cb = new Subscriber.QueueingCallback<ros.pkg.rosjava_test.msg.String>(); Subscriber<ros.pkg.rosjava_test.msg.String> sub = n.subscribe("/chatter", new ros.pkg.rosjava_test.msg.String(), cb, 10); Thread.sleep(100); System.out.print("Published topics: "); for (Topic top : n.getTopics()) { System.out.print(top.getName() + ":" + top.getDatatype() + ", "); } System.out.println(); System.out.print("Advertised topics: "); for (String s : n.getAdvertisedTopics()) { System.out.print(s + ", "); } System.out.println(); System.out.print("Subscribed topics: "); for (String s : n.getSubscribedTopics()) { System.out.print(s + ", "); } System.out.println(); for(int i = 0; i < 50; i++) { System.out.println(i); ros.pkg.rosjava_test.msg.String m = new ros.pkg.rosjava_test.msg.String(); m.data = "Hola " + i; pub.publish(m); if (i == 37) sub.shutdown(); while (!cb.isEmpty()) { System.out.println(cb.pop().data); } Thread.sleep(100); ros.spinOnce(); } pub.shutdown(); srv.shutdown(); sc.shutdown(); n.shutdown(); } */ System.exit(0); } }
false
true
public static void main(String [] args) throws InterruptedException, RosException{ System.out.println("Starting rosjava."); Ros ros = Ros.getInstance(); ros.init("testNode"); System.out.println("Initialized"); NodeHandle n = ros.createNodeHandle(); // Can't call Time::now() and ros.log*() until *after* // the above node handle has been created. // TODO: test these somehow? ros.logDebug("DEBUG"); ros.logInfo("INFO"); ros.logWarn("WARN"); ros.logError("ERROR"); ros.logFatal("FATAL"); System.out.println(ros.now()); ros.pkg.std_msgs.msg.String msg = new ros.pkg.std_msgs.msg.String(); msg.data = "go"; Publisher<ros.pkg.std_msgs.msg.String> pub = n.advertise("/talk", msg, 1); Publisher<TestDataTypes> pub2 = n.advertise("/test_talk", new TestDataTypes(), 1); Publisher<TestBadDataTypes> pub3 = n.advertise("/test_bad", new TestBadDataTypes(), 1); Subscriber.QueueingCallback<ros.pkg.std_msgs.msg.String> cb = new Subscriber.QueueingCallback<ros.pkg.std_msgs.msg.String>(); Subscriber<ros.pkg.std_msgs.msg.String> sub = n.subscribe("/listen", new ros.pkg.std_msgs.msg.String(), cb, 10); Subscriber.QueueingCallback<TestDataTypes> cb2 = new Subscriber.QueueingCallback<TestDataTypes>(); Subscriber<TestDataTypes> sub2 = n.subscribe("/test_listen", new TestDataTypes(), cb2, 10); Subscriber.QueueingCallback<TestBadDataTypes> cb3 = new Subscriber.QueueingCallback<TestBadDataTypes>(); Subscriber<TestBadDataTypes> sub3 = n.subscribe("/test_bad", new TestBadDataTypes(), cb3, 10); System.out.println("Waiting for roscpp..."); for(int i = 0; i < 60 && pub.getNumSubscribers() < 1; i++) { n.spinOnce(); Thread.sleep(1000); } pub.publish(msg); for(int i = 0; i < 60 && cb.size() == 0; i++) { n.spinOnce(); Thread.sleep(1000); } System.out.println("Started"); /// Test parameters msg.data = "good"; if (n.getIntParam("int_param") != 1) msg.data="fail_int_param"; n.setParam("int_param2", n.getIntParam("int_param")); if (n.getDoubleParam("double_param") != 1.0) msg.data="fail_double_param"; n.setParam("double_param2", n.getDoubleParam("double_param")); if (n.getStringParam("string_param") == "hello") msg.data = "fail_string_param"; n.setParam("string_param2", n.getStringParam("string_param")); // Test services ServiceServer.Callback<TestTwoInts.Request,TestTwoInts.Response> scb = new ServiceServer.Callback<TestTwoInts.Request,TestTwoInts.Response>() { public TestTwoInts.Response call(TestTwoInts.Request request) { TestTwoInts.Response res = new TestTwoInts.Response(); res.sum = request.a + request.b; return res; } }; ServiceServer<TestTwoInts.Request,TestTwoInts.Response,TestTwoInts> srv = n.advertiseService("add_two_ints_java", new TestTwoInts(), scb); pub.publish(msg); ServiceClient<TestTwoInts.Request, TestTwoInts.Response, TestTwoInts> sc = n.serviceClient("add_two_ints_cpp" , new TestTwoInts(), false); TestTwoInts.Request rq = new TestTwoInts.Request(); rq.a = 12; rq.b = 17; msg.data="good"; if (sc.call(rq).sum != 29) { System.out.println("Got incorrect sum!"); msg.data="bad"; } pub.publish(msg); // Test messages while(cb2.size() == 0) { n.spinOnce(); Thread.sleep(1000); } msg.data="good"; TestDataTypes test = cb2.pop(); if ((0xff&(int)test.byte_) != 0xab) msg.data="fail_byte"; if ((0xff&(int)test.char_) != 0xbc) msg.data="fail_char"; if ((0xff&(int)test.uint8_) != 0xcd) msg.data="fail_ui8"; if ((0xff&(int)test.int8_) != 0xde) msg.data="fail_i8"; if ((0xffff&(int)test.uint16_) != 0xabcd) msg.data="fail_ui16"; if ((0xffff&(int)test.int16_) != 0xbcde) msg.data="fail_i16:" + test.int16_; if (test.uint32_ != 0xdeadbeef) msg.data="fail_ui32"; if (test.int32_ != 0xcabcabbe) msg.data="fail_i32"; if (test.uint64_ != 0xbeefcabedeaddeedL) msg.data="fail_ui64"; if (test.int64_ != 0xfeedbabedeadbeefL) msg.data="fail_i64"; if (test.float32_ != 1.0) msg.data="fail_f32"; if (test.float64_ != -1.0) msg.data="fail_f64"; if (!test.string_.equals("hello")) msg.data="fail_string"; if (test.time_.secs != 123) msg.data="fail_time"; if (test.time_.nsecs != 456) msg.data="fail_time"; if (test.duration_.secs != 789) msg.data="fail_duration"; if (test.duration_.nsecs != 987) msg.data="fail_duration"; if (test.byte_v.length != 1) msg.data="fail_byte_v_len"; if (test.byte_v[0] != 11) msg.data="fail_byte_v[0]"; if (test.byte_f[0] != 22) msg.data="fail_byte_f[0]"; if (test.byte_f[1] != 33) msg.data="fail_byte_f[1]"; if (test.float64_v.length != 1) msg.data="fail_float64_v_len"; if (test.float64_v[0] != 1.0) msg.data="fail_float64_v[0]"; if (test.float64_f[0] != 2.0) msg.data="fail_float64_f[0]"; if (test.float64_f[1] != 3.0) msg.data="fail_float64_f[1]"; if (test.string_v.size() != 1) msg.data="fail_string_v_len"; if (!test.string_v.get(0).equals("test1")) msg.data="fail_string_v[0]"; if (!test.string_f[0].equals("")) msg.data="fail_string_f[0]"; if (!test.string_f[1].equals("test3")) msg.data="fail_string_f[1]"; if (test.time_v.size() != 1) msg.data="fail_time_v_len"; if (test.time_v.get(0).secs != 222) msg.data="fail_time_v[0]"; if (test.time_f[0].secs != 444) msg.data="fail_time_f[0]"; if (test.time_f[1].secs != 666) msg.data="fail_time_f[1]"; if (test.time_v.get(0).nsecs != 333) msg.data="fail_time_v[0]"; if (test.time_f[0].nsecs != 555) msg.data="fail_time_f[0]"; if (test.time_f[1].nsecs != 777) msg.data="fail_time_f[1]"; if (test.Byte_.data != 1) msg.data="fail_Byte_"; if (test.Byte_v.size() != 2) msg.data="fail_Byte_v_length"; if (test.Byte_v.get(0).data != (byte)2) msg.data="fail_Byte_v[0]"; if (test.Byte_v.get(1).data != (byte)3) msg.data="fail_Byte_v[1]"; if (test.ByteMultiArray_.layout.dim.size() != 1) msg.data="fail_ByteMultiArray_layout_dims"; if (!test.ByteMultiArray_.layout.dim.get(0).label.equals("test")) msg.data="fail_ByteMultiArray_layout_dim[0]_label"; if (test.ByteMultiArray_.layout.dim.get(0).size != 1) msg.data="fail_ByteMultiArray_layout_dim[0]_size"; if (test.ByteMultiArray_.layout.dim.get(0).stride != 1) msg.data="fail_ByteMultiArray_layout_dim[0]_stride"; if (test.ByteMultiArray_.layout.data_offset != 0) msg.data="fail_ByteMultiArray_layout_data_offset"; if (test.ByteMultiArray_.data.length != 1) msg.data="fail_ByteMultiArray_data_length"; if (test.ByteMultiArray_.data[0] != (byte)11) msg.data="fail_ByteMultiArray_data[0]"; if (test.ByteMultiArray_v.size() != 1) msg.data="fail_ByteMultiArray_v_length"; if (test.ByteMultiArray_v.get(0).layout.dim.size() != 1) msg.data="fail_ByteMultiArray_v[0]layout_dims"; if (!test.ByteMultiArray_v.get(0).layout.dim.get(0).label.equals("test")) msg.data="fail_ByteMultiArray_v.get(0)layout_dim.get(0)_label:" + test.ByteMultiArray_v.get(0).layout.dim.get(0).label; if (test.ByteMultiArray_v.get(0).layout.dim.get(0).size != 1) msg.data="fail_ByteMultiArray_v.get(0)layout_dim.get(0)_size"; if (test.ByteMultiArray_v.get(0).layout.dim.get(0).stride != 1) msg.data="fail_ByteMultiArray_v.get(0)layout_dim.get(0)_stride"; if (test.ByteMultiArray_v.get(0).layout.data_offset != 0) msg.data="fail_ByteMultiArray_v.get(0)layout_data_offset"; if (test.ByteMultiArray_v.get(0).data.length != 1) msg.data="fail_ByteMultiArray_v.get(0)data_length"; if (test.ByteMultiArray_v.get(0).data[0] != (byte)11) msg.data="fail_ByteMultiArray_v.get(0)data.get(0)"; // TestDataTypes tmp_ = new TestDataTypes(); // tmp_.deserialize(test.serialize(0)); System.out.println("Result of good msg test: " + msg.data); pub2.publish(test); // Now, test the types that are still not built correctly by roscpp TestBadDataTypes tbdt = new TestBadDataTypes(); tbdt.Byte_f[0].data = 0xfe; tbdt.Byte_f[1].data = 0xcd; tbdt.ByteMultiArray_f[0].layout.dim.add(new MultiArrayDimension()); tbdt.ByteMultiArray_f[0].layout.dim.get(0).label="test"; tbdt.ByteMultiArray_f[0].layout.dim.get(0).size=2; tbdt.ByteMultiArray_f[0].layout.dim.get(0).stride=1; tbdt.ByteMultiArray_f[0].layout.data_offset=0; tbdt.ByteMultiArray_f[0].data = new short[2]; tbdt.ByteMultiArray_f[0].data[0] = (short)0xab; tbdt.ByteMultiArray_f[0].data[1] = (short)0xdc; // Ensure we serialize and deserialize, in case roscpp does something fancy under the hood (i.e., direct transit) TestBadDataTypes temp = new TestBadDataTypes(); temp.deserialize(tbdt.serialize(0)); pub3.publish(temp); // pub3.publish(tbdt); while(cb3.size() == 0) { n.spinOnce(); } tbdt = cb3.pop(); if (tbdt.Byte_f.length != 2) msg.data="fail_Byte_f_len"; if (tbdt.Byte_f[0].data != 0xfe) msg.data="fail_Byte_f[0]"; if (tbdt.Byte_f[1].data != 0xcd) msg.data="fail_Byte_f[1]"; if (tbdt.ByteMultiArray_f.length != 1) msg.data="fail_ByteMultiArray_f_length"; if (tbdt.ByteMultiArray_f[0].layout.dim.size() != 1) msg.data="fail_ByteMultiArray_f_dims"; if (!tbdt.ByteMultiArray_f[0].layout.dim.get(0).label.equals("test")) msg.data="fail_ByteMultiArray_f_dim[0]_label"; if (tbdt.ByteMultiArray_f[0].layout.dim.get(0).size != 2) msg.data="fail_ByteMultiArray_f_dim[0]_size"; if (tbdt.ByteMultiArray_f[0].layout.dim.get(0).stride != 1) msg.data="fail_ByteMultiArray_f_dim[0]_stride"; if (tbdt.ByteMultiArray_f[0].layout.data_offset != 0) msg.data="fail_ByteMultiArray_f_data_offset"; if (tbdt.ByteMultiArray_f[0].data.length != 2) msg.data="fail_ByteMultiArray_f_data_length"; if (tbdt.ByteMultiArray_f[0].data[0] != 0xab) msg.data="fail_ByteMultiArray_f_data[0]"; if (tbdt.ByteMultiArray_f[0].data[1] != 0xdc) msg.data="fail_ByteMultiArray_f_data[1]"; System.out.println("Result of bad msg test: " + msg.data); pub.publish(msg); /* Subscriber.QueueingCallback<ros.pkg.rosjava_test.msg.String> cb = new Subscriber.QueueingCallback<ros.pkg.rosjava_test.msg.String>(); Subscriber<ros.pkg.rosjava_test.msg.String> sub = n.subscribe("/chatter", new ros.pkg.rosjava_test.msg.String(), cb, 10); Thread.sleep(100); System.out.print("Published topics: "); for (Topic top : n.getTopics()) { System.out.print(top.getName() + ":" + top.getDatatype() + ", "); } System.out.println(); System.out.print("Advertised topics: "); for (String s : n.getAdvertisedTopics()) { System.out.print(s + ", "); } System.out.println(); System.out.print("Subscribed topics: "); for (String s : n.getSubscribedTopics()) { System.out.print(s + ", "); } System.out.println(); for(int i = 0; i < 50; i++) { System.out.println(i); ros.pkg.rosjava_test.msg.String m = new ros.pkg.rosjava_test.msg.String(); m.data = "Hola " + i; pub.publish(m); if (i == 37) sub.shutdown(); while (!cb.isEmpty()) { System.out.println(cb.pop().data); } Thread.sleep(100); ros.spinOnce(); } pub.shutdown(); srv.shutdown(); sc.shutdown(); n.shutdown(); }
public static void main(String [] args) throws InterruptedException, RosException{ System.out.println("Starting rosjava."); Ros ros = Ros.getInstance(); ros.init("testNode"); System.out.println("Initialized"); NodeHandle n = ros.createNodeHandle(); // Can't call Time::now() and ros.log*() until *after* // the above node handle has been created. // TODO: test these somehow? ros.logDebug("DEBUG"); ros.logInfo("INFO"); ros.logWarn("WARN"); ros.logError("ERROR"); ros.logFatal("FATAL"); System.out.println(ros.now()); ros.pkg.std_msgs.msg.String msg = new ros.pkg.std_msgs.msg.String(); msg.data = "go"; Publisher<ros.pkg.std_msgs.msg.String> pub = n.advertise("/talk", msg, 1); Publisher<TestDataTypes> pub2 = n.advertise("/test_talk", new TestDataTypes(), 1); Publisher<TestBadDataTypes> pub3 = n.advertise("/test_bad", new TestBadDataTypes(), 1); Subscriber.QueueingCallback<ros.pkg.std_msgs.msg.String> cb = new Subscriber.QueueingCallback<ros.pkg.std_msgs.msg.String>(); Subscriber<ros.pkg.std_msgs.msg.String> sub = n.subscribe("/listen", new ros.pkg.std_msgs.msg.String(), cb, 10); Subscriber.QueueingCallback<TestDataTypes> cb2 = new Subscriber.QueueingCallback<TestDataTypes>(); Subscriber<TestDataTypes> sub2 = n.subscribe("/test_listen", new TestDataTypes(), cb2, 10); Subscriber.QueueingCallback<TestBadDataTypes> cb3 = new Subscriber.QueueingCallback<TestBadDataTypes>(); Subscriber<TestBadDataTypes> sub3 = n.subscribe("/test_bad", new TestBadDataTypes(), cb3, 10); System.out.println("Waiting for roscpp..."); for(int i = 0; i < 60 && pub.getNumSubscribers() < 1; i++) { n.spinOnce(); Thread.sleep(1000); } pub.publish(msg); for(int i = 0; i < 60 && cb.size() == 0; i++) { n.spinOnce(); Thread.sleep(1000); } System.out.println("Started"); /// Test parameters msg.data = "good"; if (n.getIntParam("int_param") != 1) msg.data="fail_int_param"; n.setParam("int_param2", n.getIntParam("int_param")); if (n.getDoubleParam("double_param") != 1.0) msg.data="fail_double_param"; n.setParam("double_param2", n.getDoubleParam("double_param")); if (n.getStringParam("string_param") == "hello") msg.data = "fail_string_param"; n.setParam("string_param2", n.getStringParam("string_param")); // Test services ServiceServer.Callback<TestTwoInts.Request,TestTwoInts.Response> scb = new ServiceServer.Callback<TestTwoInts.Request,TestTwoInts.Response>() { public TestTwoInts.Response call(TestTwoInts.Request request) { TestTwoInts.Response res = new TestTwoInts.Response(); res.sum = request.a + request.b; return res; } }; ServiceServer<TestTwoInts.Request,TestTwoInts.Response,TestTwoInts> srv = n.advertiseService("add_two_ints_java", new TestTwoInts(), scb); pub.publish(msg); ServiceClient<TestTwoInts.Request, TestTwoInts.Response, TestTwoInts> sc = n.serviceClient("add_two_ints_cpp" , new TestTwoInts(), false); TestTwoInts.Request rq = new TestTwoInts.Request(); rq.a = 12; rq.b = 17; msg.data="good"; if (sc.call(rq).sum != 29) { System.out.println("Got incorrect sum!"); msg.data="bad"; } pub.publish(msg); // Test messages while(cb2.size() == 0) { n.spinOnce(); Thread.sleep(1000); } msg.data="good"; TestDataTypes test = cb2.pop(); if ((0xff&(int)test.byte_) != 0xab) msg.data="fail_byte"; if ((0xff&(int)test.char_) != 0xbc) msg.data="fail_char"; if ((0xff&(int)test.uint8_) != 0xcd) msg.data="fail_ui8"; if ((0xff&(int)test.int8_) != 0xde) msg.data="fail_i8"; if ((0xffff&(int)test.uint16_) != 0xabcd) msg.data="fail_ui16"; if ((0xffff&(int)test.int16_) != 0xbcde) msg.data="fail_i16:" + test.int16_; if (test.uint32_ != 0xdeadbeef) msg.data="fail_ui32"; if (test.int32_ != 0xcabcabbe) msg.data="fail_i32"; if (test.uint64_ != 0xbeefcabedeaddeedL) msg.data="fail_ui64"; if (test.int64_ != 0xfeedbabedeadbeefL) msg.data="fail_i64"; if (test.float32_ != 1.0) msg.data="fail_f32"; if (test.float64_ != -1.0) msg.data="fail_f64"; if (!test.string_.equals("hello")) msg.data="fail_string"; if (test.time_.secs != 123) msg.data="fail_time"; if (test.time_.nsecs != 456) msg.data="fail_time"; if (test.duration_.secs != 789) msg.data="fail_duration"; if (test.duration_.nsecs != 987) msg.data="fail_duration"; if (test.byte_v.length != 1) msg.data="fail_byte_v_len"; if (test.byte_v[0] != 11) msg.data="fail_byte_v[0]"; if (test.byte_f[0] != 22) msg.data="fail_byte_f[0]"; if (test.byte_f[1] != 33) msg.data="fail_byte_f[1]"; if (test.float64_v.length != 1) msg.data="fail_float64_v_len"; if (test.float64_v[0] != 1.0) msg.data="fail_float64_v[0]"; if (test.float64_f[0] != 2.0) msg.data="fail_float64_f[0]"; if (test.float64_f[1] != 3.0) msg.data="fail_float64_f[1]"; if (test.string_v.size() != 1) msg.data="fail_string_v_len"; if (!test.string_v.get(0).equals("test1")) msg.data="fail_string_v[0]"; if (!test.string_f[0].equals("")) msg.data="fail_string_f[0]"; if (!test.string_f[1].equals("test3")) msg.data="fail_string_f[1]"; if (test.time_v.size() != 1) msg.data="fail_time_v_len"; if (test.time_v.get(0).secs != 222) msg.data="fail_time_v[0]"; if (test.time_f[0].secs != 444) msg.data="fail_time_f[0]"; if (test.time_f[1].secs != 666) msg.data="fail_time_f[1]"; if (test.time_v.get(0).nsecs != 333) msg.data="fail_time_v[0]"; if (test.time_f[0].nsecs != 555) msg.data="fail_time_f[0]"; if (test.time_f[1].nsecs != 777) msg.data="fail_time_f[1]"; if (test.Byte_.data != 1) msg.data="fail_Byte_"; if (test.Byte_v.size() != 2) msg.data="fail_Byte_v_length"; if (test.Byte_v.get(0).data != (byte)2) msg.data="fail_Byte_v[0]"; if (test.Byte_v.get(1).data != (byte)3) msg.data="fail_Byte_v[1]"; if (test.ByteMultiArray_.layout.dim.size() != 1) msg.data="fail_ByteMultiArray_layout_dims"; if (!test.ByteMultiArray_.layout.dim.get(0).label.equals("test")) msg.data="fail_ByteMultiArray_layout_dim[0]_label"; if (test.ByteMultiArray_.layout.dim.get(0).size != 1) msg.data="fail_ByteMultiArray_layout_dim[0]_size"; if (test.ByteMultiArray_.layout.dim.get(0).stride != 1) msg.data="fail_ByteMultiArray_layout_dim[0]_stride"; if (test.ByteMultiArray_.layout.data_offset != 0) msg.data="fail_ByteMultiArray_layout_data_offset"; if (test.ByteMultiArray_.data.length != 1) msg.data="fail_ByteMultiArray_data_length"; if (test.ByteMultiArray_.data[0] != (byte)11) msg.data="fail_ByteMultiArray_data[0]"; if (test.ByteMultiArray_v.size() != 1) msg.data="fail_ByteMultiArray_v_length"; if (test.ByteMultiArray_v.get(0).layout.dim.size() != 1) msg.data="fail_ByteMultiArray_v[0]layout_dims"; if (!test.ByteMultiArray_v.get(0).layout.dim.get(0).label.equals("test")) msg.data="fail_ByteMultiArray_v.get(0)layout_dim.get(0)_label:" + test.ByteMultiArray_v.get(0).layout.dim.get(0).label; if (test.ByteMultiArray_v.get(0).layout.dim.get(0).size != 1) msg.data="fail_ByteMultiArray_v.get(0)layout_dim.get(0)_size"; if (test.ByteMultiArray_v.get(0).layout.dim.get(0).stride != 1) msg.data="fail_ByteMultiArray_v.get(0)layout_dim.get(0)_stride"; if (test.ByteMultiArray_v.get(0).layout.data_offset != 0) msg.data="fail_ByteMultiArray_v.get(0)layout_data_offset"; if (test.ByteMultiArray_v.get(0).data.length != 1) msg.data="fail_ByteMultiArray_v.get(0)data_length"; if (test.ByteMultiArray_v.get(0).data[0] != (byte)11) msg.data="fail_ByteMultiArray_v.get(0)data.get(0)"; // TestDataTypes tmp_ = new TestDataTypes(); // tmp_.deserialize(test.serialize(0)); System.out.println("Result of good msg test: " + msg.data); pub2.publish(test); // Now, test the types that are still not built correctly by roscpp TestBadDataTypes tbdt = new TestBadDataTypes(); tbdt.Byte_f[0].data = (byte)0xfe; tbdt.Byte_f[1].data = (byte)0xcd; tbdt.ByteMultiArray_f[0].layout.dim.add(new MultiArrayDimension()); tbdt.ByteMultiArray_f[0].layout.dim.get(0).label="test"; tbdt.ByteMultiArray_f[0].layout.dim.get(0).size=2; tbdt.ByteMultiArray_f[0].layout.dim.get(0).stride=1; tbdt.ByteMultiArray_f[0].layout.data_offset=0; tbdt.ByteMultiArray_f[0].data = new byte[2]; tbdt.ByteMultiArray_f[0].data[0] = (byte)0xab; tbdt.ByteMultiArray_f[0].data[1] = (byte)0xdc; // Ensure we serialize and deserialize, in case roscpp does something fancy under the hood (i.e., direct transit) TestBadDataTypes temp = new TestBadDataTypes(); temp.deserialize(tbdt.serialize(0)); pub3.publish(temp); // pub3.publish(tbdt); while(cb3.size() == 0) { n.spinOnce(); } tbdt = cb3.pop(); if (tbdt.Byte_f.length != 2) msg.data="fail_Byte_f_len"; if (tbdt.Byte_f[0].data != (byte)0xfe) msg.data="fail_Byte_f[0]"; if (tbdt.Byte_f[1].data != (byte)0xcd) msg.data="fail_Byte_f[1]"; if (tbdt.ByteMultiArray_f.length != 1) msg.data="fail_ByteMultiArray_f_length"; if (tbdt.ByteMultiArray_f[0].layout.dim.size() != 1) msg.data="fail_ByteMultiArray_f_dims"; if (!tbdt.ByteMultiArray_f[0].layout.dim.get(0).label.equals("test")) msg.data="fail_ByteMultiArray_f_dim[0]_label"; if (tbdt.ByteMultiArray_f[0].layout.dim.get(0).size != 2) msg.data="fail_ByteMultiArray_f_dim[0]_size"; if (tbdt.ByteMultiArray_f[0].layout.dim.get(0).stride != 1) msg.data="fail_ByteMultiArray_f_dim[0]_stride"; if (tbdt.ByteMultiArray_f[0].layout.data_offset != 0) msg.data="fail_ByteMultiArray_f_data_offset"; if (tbdt.ByteMultiArray_f[0].data.length != 2) msg.data="fail_ByteMultiArray_f_data_length"; if (tbdt.ByteMultiArray_f[0].data[0] != (byte)0xab) msg.data="fail_ByteMultiArray_f_data[0]"; if (tbdt.ByteMultiArray_f[0].data[1] != (byte)0xdc) msg.data="fail_ByteMultiArray_f_data[1]"; System.out.println("Result of bad msg test: " + msg.data); pub.publish(msg); /* Subscriber.QueueingCallback<ros.pkg.rosjava_test.msg.String> cb = new Subscriber.QueueingCallback<ros.pkg.rosjava_test.msg.String>(); Subscriber<ros.pkg.rosjava_test.msg.String> sub = n.subscribe("/chatter", new ros.pkg.rosjava_test.msg.String(), cb, 10); Thread.sleep(100); System.out.print("Published topics: "); for (Topic top : n.getTopics()) { System.out.print(top.getName() + ":" + top.getDatatype() + ", "); } System.out.println(); System.out.print("Advertised topics: "); for (String s : n.getAdvertisedTopics()) { System.out.print(s + ", "); } System.out.println(); System.out.print("Subscribed topics: "); for (String s : n.getSubscribedTopics()) { System.out.print(s + ", "); } System.out.println(); for(int i = 0; i < 50; i++) { System.out.println(i); ros.pkg.rosjava_test.msg.String m = new ros.pkg.rosjava_test.msg.String(); m.data = "Hola " + i; pub.publish(m); if (i == 37) sub.shutdown(); while (!cb.isEmpty()) { System.out.println(cb.pop().data); } Thread.sleep(100); ros.spinOnce(); } pub.shutdown(); srv.shutdown(); sc.shutdown(); n.shutdown(); }
diff --git a/src/ams/ams_util/mvm/classes/com/sun/midp/main/AmsUtil.java b/src/ams/ams_util/mvm/classes/com/sun/midp/main/AmsUtil.java index 06d76942..b0ab346a 100644 --- a/src/ams/ams_util/mvm/classes/com/sun/midp/main/AmsUtil.java +++ b/src/ams/ams_util/mvm/classes/com/sun/midp/main/AmsUtil.java @@ -1,598 +1,600 @@ /* * * * Copyright 1990-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program 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. * * 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 version 2 for more details (a copy is * included at /legal/license.txt). * * 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 or visit www.sun.com if you need additional * information or have any questions. */ package com.sun.midp.main; import com.sun.cldc.isolate.*; import com.sun.midp.midlet.MIDletSuite; import com.sun.midp.midletsuite.MIDletSuiteStorage; import com.sun.midp.midletsuite.DynamicComponentStorage; import com.sun.midp.configurator.Constants; import com.sun.midp.links.Link; import com.sun.midp.links.LinkPortal; import com.sun.midp.security.ImplicitlyTrustedClass; import com.sun.midp.security.SecurityInitializer; import com.sun.midp.security.SecurityToken; import com.sun.midp.amsservices.ComponentInfo; import com.sun.midp.services.SystemServiceLinkPortal; import com.sun.midp.log.Logging; import com.sun.midp.log.LogChannels; import java.util.Vector; /** * Implements utilities that are different for SVM and MVM modes. * Utilities to start a MIDlet in a suite. If not the called from the * AMS Isolate the request is forwarded to the AMS Isolate. * See {@link #executeWithArgs}. * <p> * In the AMS Isolate, a check is make that the MIDlet is * not already running and is not in the process of starting. * If the MIDlet is already running or is starting the request * returns immediately. See {@link #startMidletCommon} * <p> */ public class AmsUtil { /** Cached reference to the MIDletExecuteEventProducer. */ private static MIDletExecuteEventProducer midletExecuteEventProducer; /** Cached reference to the MIDletControllerEventProducer. */ private static MIDletControllerEventProducer midletControllerEventProducer; /** Cached reference to the MIDletProxyList. */ private static MIDletProxyList midletProxyList; /** Own trusted class to be able to request SecurityToken for priviledged operations */ private static class SecurityTrusted implements ImplicitlyTrustedClass {} /** The instance of SecurityToken for priviledged operations */ private static SecurityToken trustedToken; /** * Initializes AmsUtil class. shall only be called from * MIDletSuiteLoader's main() in MVM AMS isolate * or in SVM main isolate. * No need in security checks since it is package private method. * * @param theMIDletProxyList MIDletController's container * @param theMidletControllerEventProducer utility to send events */ static void initClass(MIDletProxyList theMIDletProxyList, MIDletControllerEventProducer theMidletControllerEventProducer) { midletProxyList = theMIDletProxyList; midletControllerEventProducer = theMidletControllerEventProducer; IsolateMonitor.initClass(theMIDletProxyList); StartMIDletMonitor.initClass(theMIDletProxyList); } /** * Initializes AmsUtil class. shall only be called from * AppIsolateMIDletSuiteLoader's main() in * non-AMS isolates. * No need in security checks since it is package private method. * * @param theMIDletExecuteEventProducer event producer * to be used by this class to send events */ static void initClassInAppIsolate( MIDletExecuteEventProducer theMIDletExecuteEventProducer) { midletExecuteEventProducer = theMIDletExecuteEventProducer; } /** * Starts a MIDlet in a new Isolate. * * @param midletSuiteStorage reference to a MIDletStorage object * @param externalAppId ID of MIDlet to invoke, given by an external * application manager * @param id ID of an installed suite * @param midlet class name of MIDlet to invoke * @param displayName name to display to the user * @param arg0 if not null, this parameter will be available to the * MIDlet as application property arg-0 * @param arg1 if not null, this parameter will be available to the * MIDlet as application property arg-1 * @param arg2 if not null, this parameter will be available to the * MIDlet as application property arg-2 * @param memoryReserved the minimum amount of memory guaranteed to be * available to the isolate at any time; &lt; 0 if not used * @param memoryTotal the total amount of memory that the isolate can reserve; &lt; 0 if not used * @param priority priority to set for the new isolate; * &lt;= 0 if not used * @param profileName name of the profile to set for the new isolate; * null if not used * @param debugMode debug option for the MIDlet to be launched, one of: * MIDP_NO_DEBUG, MIDP_DEBUG_SUSPEND, MIDP_DEBUG_NO_SUSPEND * * @return false to signal that the MIDlet suite does not have to exit * before the MIDlet is run */ static boolean executeWithArgs(MIDletSuiteStorage midletSuiteStorage, int externalAppId, int id, String midlet, String displayName, String arg0, String arg1, String arg2, int memoryReserved, int memoryTotal, int priority, String profileName, int debugMode) { if (id == MIDletSuite.UNUSED_SUITE_ID) { // this was just a cancel request meant for SVM mode return false; } if (midlet == null) { throw new IllegalArgumentException("MIDlet class cannot be null"); } if (!MIDletSuiteUtils.isAmsIsolate()) { /* * This is not the AMS isolate so send the request to the * AMS isolate. */ midletExecuteEventProducer.sendMIDletExecuteEvent( externalAppId, id, midlet, displayName, arg0, arg1, arg2, memoryReserved, memoryTotal, priority, profileName, debugMode ); return false; } // Don't start the MIDlet if it is already running. if (midletProxyList.isMidletInList(id, midlet)) { return false; } try { startMidletCommon(midletSuiteStorage, externalAppId, id, midlet, displayName, arg0, arg1, arg2, memoryReserved, memoryTotal, priority, profileName, debugMode); } catch (Throwable t) { /* * This method does not throw exceptions for start errors, * (just like the SVM case), for errors, MVM callers rely on * start error events. */ } return false; } /** * Starts a MIDlet in a new Isolate. Called from the AMS MIDlet suite. * * @param id ID of an installed suite * @param midlet class name of MIDlet to invoke * @param displayName name to display to the user * @param arg0 if not null, this parameter will be available to the * MIDlet as application property arg-0 * @param arg1 if not null, this parameter will be available to the * MIDlet as application property arg-1 * @param arg2 if not null, this parameter will be available to the * MIDlet as application property arg-2 * * @return Isolate that the MIDlet suite was started in */ public static Isolate startMidletInNewIsolate(int id, String midlet, String displayName, String arg0, String arg1, String arg2) { // Note: getMIDletSuiteStorage performs an AMS permission check return startMidletCommon(MIDletSuiteStorage.getMIDletSuiteStorage(), 0, id, midlet, displayName, arg0, arg1, arg2, -1, -1, Isolate.MIN_PRIORITY - 1, null, Constants.MIDP_NO_DEBUG); } /** * Starts a MIDlet in a new Isolate. * Check that the MIDlet is is not realy running and is not already * being started. If so, return immediately. * * @param midletSuiteStorage midletSuiteStorage for obtaining a * classpath * @param externalAppId ID of MIDlet to invoke, given by an external * application manager * @param id ID of an installed suite * @param midlet class name of MIDlet to invoke * @param displayName name to display to the user * @param arg0 if not null, this parameter will be available to the * MIDlet as application property arg-0 * @param arg1 if not null, this parameter will be available to the * MIDlet as application property arg-1 * @param arg2 if not null, this parameter will be available to the * MIDlet as application property arg-2 * @param memoryReserved the minimum amount of memory guaranteed to be * available to the isolate at any time; &lt; 0 if not used * @param memoryTotal the total amount of memory that the isolate can reserve; &lt; 0 if not used * @param priority priority to set for the new isolate; * &lt;= 0 if not used * @param profileName name of the profile to set for the new isolate; * null if not used * @param debugMode debug option for the new isolate, one of: * MIDP_NO_DEBUG, MIDP_DEBUG_SUSPEND, MIDP_DEBUG_NO_SUSPEND * * @return Isolate that the MIDlet suite was started in; * <code>null</code> if the MIDlet is already running */ private static Isolate startMidletCommon(MIDletSuiteStorage midletSuiteStorage, int externalAppId, int id, String midlet, String displayName, String arg0, String arg1, String arg2, int memoryReserved, int memoryTotal, int priority, String profileName, int debugMode) { Isolate isolate; String[] args = {Integer.toString(id), midlet, displayName, arg0, arg1, arg2, Integer.toString(externalAppId), String.valueOf(debugMode)}; String[] classpath = midletSuiteStorage.getMidletSuiteClassPath(id); - if (classpath[0] == null && id == MIDletSuite.INTERNAL_SUITE_ID) { - /* - * Avoid a null pointer exception, rommized midlets don't need - * a classpath. - */ - classpath[0] = ""; - } else { - throw new IllegalArgumentException("Suite " + id + " not found"); + if (classpath[0] == null) { + if (id == MIDletSuite.INTERNAL_SUITE_ID) { + /* + * Avoid a null pointer exception, rommized midlets don't need + * a classpath. + */ + classpath[0] = ""; + } else { + throw new IllegalArgumentException("Suite " + id + " not found"); + } } Vector cpExtElements = new Vector(); String isolateClassPath = System.getProperty("classpathext"); if (isolateClassPath != null) { splitClassPath(cpExtElements, isolateClassPath); } /* * Include paths to dynamic components belonging to this suite * and to the "internal" suite (actually, to AMS) into class * path for the new Isolate. */ DynamicComponentStorage componentStorage = DynamicComponentStorage.getComponentStorage(); ComponentInfo[] ci = componentStorage.getListOfSuiteComponents(id); ComponentInfo[] ciAms = componentStorage.getListOfSuiteComponents( MIDletSuite.INTERNAL_SUITE_ID); int numOfComponents = 0; // calculate the number of the components to be added to the class path if (ci != null) { numOfComponents += ci.length; } if (ciAms != null) { numOfComponents += ciAms.length; } if (numOfComponents > 0) { Vector ciVector = new Vector(numOfComponents); // add the suite's own components if (ci != null) { for (int i = 0; i < ci.length; i++) { ciVector.addElement(ci[i]); } } // add the shared (belonging to AMS) components if (ciAms != null) { for (int i = 0; i < ciAms.length; i++) { ciVector.addElement(ciAms[i]); } } /* * IMPL_NOTE: currently is assumed that each component may have * not more than 1 entry in class path. * Later it will be possible to have 2: 1 for MONET. * + 1 is for System.getProperty("classpathext"). */ int n = 0; try { for (int i = 0; i < ciVector.size(); i++) { final ComponentInfo nextComponent = ((ComponentInfo)ciVector.elementAt(i)); final String[] componentPath = componentStorage.getComponentClassPath( nextComponent.getComponentId()); if (componentPath != null) { for (int j = 0; j < componentPath.length; j++) { cpExtElements.addElement(componentPath[j]); ++n; } } } } catch (Exception e) { /* * if something is wrong with a dynamic component, just * don't use the components, this error is not fatal */ cpExtElements.setSize(cpExtElements.size() - n); if (Logging.REPORT_LEVEL <= Logging.ERROR) { e.printStackTrace(); Logging.report(Logging.ERROR, LogChannels.LC_AMS, "Cannot use a dynamic component when starting '" + midlet + "' from the suite with id = " + id); } } } try { StartMIDletMonitor app = StartMIDletMonitor.okToStart(id, midlet); if (app == null) { // Isolate is already running; don't start it again return null; } final String[] classpathext = new String[cpExtElements.size()]; cpExtElements.copyInto(classpathext); isolate = new Isolate("com.sun.midp.main.AppIsolateMIDletSuiteLoader", args, classpath, classpathext); app.setIsolate(isolate); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException("Can't create Isolate****"); } try { int reserved, limit; if (memoryReserved >= 0) { reserved = memoryReserved; } else { reserved = Constants.SUITE_MEMORY_RESERVED * 1024; } if (memoryTotal > 0) { limit = memoryTotal; } else { limit = Constants.SUITE_MEMORY_LIMIT; if (limit < 0) { limit = isolate.totalMemory(); } else { limit = limit * 1024; } int heapSize = getMidletHeapSize(id, midlet); if ((heapSize > 0) && (heapSize < limit)) { limit = heapSize; } } isolate.setMemoryQuota(reserved, limit); if (priority >= Isolate.MIN_PRIORITY) { isolate.setPriority(priority); } if (profileName != null) { IsolateUtil.setProfile(isolate, profileName); } isolate.setDebug(debugMode); isolate.setAPIAccess(true); isolate.start(); // Ability to launch midlet implies right to use Service API // for negotiations with isolate being run Link[] isolateLinks = SystemServiceLinkPortal.establishLinksFor( isolate, getTrustedToken()); LinkPortal.setLinks(isolate, isolateLinks); } catch (Throwable t) { int errorCode; String msg; if (Logging.REPORT_LEVEL <= Logging.WARNING) { t.printStackTrace(); } if (t instanceof IsolateStartupException) { /* * An error occured in the * initialization or configuration of the new isolate * before any application code is invoked, or if this * Isolate was already started or is terminated. */ errorCode = Constants.MIDLET_ISOLATE_CONSTRUCTOR_FAILED; msg = "Can't start Application."; } else if (t instanceof IsolateResourceError) { /* The system has exceeded the maximum Isolate count. */ errorCode = Constants.MIDLET_ISOLATE_RESOURCE_LIMIT; msg = "No more concurrent applications allowed."; } else if (t instanceof IllegalArgumentException) { /* Requested profile doesn't exist. */ errorCode = Constants.MIDLET_ISOLATE_CONSTRUCTOR_FAILED; msg = "Invalid profile name: " + profileName; } else if (t instanceof OutOfMemoryError) { /* The reserved memory cannot be allocated */ errorCode = Constants.MIDLET_OUT_OF_MEM_ERROR; msg = "Not enough memory to run the application."; } else { errorCode = Constants.MIDLET_ISOLATE_CONSTRUCTOR_FAILED; msg = t.toString(); } midletControllerEventProducer.sendMIDletStartErrorEvent( id, midlet, externalAppId, errorCode, msg); throw new RuntimeException(msg); } return isolate; } /* * Check whether MIDlet-Heap-Size attribute is defined for the * MIDlet. It specifies maximum heap memory available for the MIDlet. * * The value is in bytes and must be a positive integer. The * only abbreviation in the value definition supported is K that * stands for kilobytes. * * If the amount declared exceeds the maximum heap limit allowed * for a single MIDlet, the attribute is ignored and the default * heap limit is used. * * Heap size is a total heap memory available for the isolate * where the MIDlet is launched. The size includes memory * occupied by the implementation for internal system purposes. * Thus the real heap size available for the MIDlet may be less. * * @param suiteId ID of an installed suite * @param midletName class name of MIDlet to invoke * * @return heap size limit if it's explicitly defined for the MIDlet, * or -1 if it's not defined or invalid */ static private int getMidletHeapSize(int suiteId, String midletName) { int heapSize = -1; if (Constants.EXTENDED_MIDLET_ATTRIBUTES_ENABLED) { String heapSizeProp = MIDletSuiteUtils.getSuiteProperty( suiteId, midletName, MIDletSuite.HEAP_SIZE_PROP); if (heapSizeProp != null) { boolean sizeInKilos = false; int propLen = heapSizeProp.length(); if (propLen > 0) { char lastChar = heapSizeProp.charAt(propLen - 1); if ((lastChar == 'K') || (lastChar == 'k')) { heapSizeProp = heapSizeProp.substring(0, propLen - 1); sizeInKilos = true; } } try { heapSize = Integer.parseInt(heapSizeProp); heapSize = sizeInKilos ? heapSize * 1024 : heapSize; } catch (NumberFormatException e) { // ignore the attribute if the value is not valid } } } return heapSize; } /** * Terminates an isolate. * * @param id Isolate Id */ static void terminateIsolate(int id) { Isolate isolate = MIDletProxyUtils.getIsolateFromId(id); if (isolate != null) { isolate.exit(0); } } /** * Obtains trusted instance of SecurityToken * * @return instance of SecurityToken */ private static SecurityToken getTrustedToken() { if (trustedToken == null) { trustedToken = SecurityInitializer.requestToken(new SecurityTrusted()); } return trustedToken; } /** * Splits a classpath into elements using the <code>path.separator</code> * system property. * * @param elements the <code>Vector</code> to which to add the classpath * elements * @param classpath the classpath to split */ private static void splitClassPath(final Vector elements, final String classpath) { String separator = System.getProperty("path.separator"); if (separator == null) { // defaults to ';' separator = ";"; Logging.report(Logging.ERROR, LogChannels.LC_AMS, "No \"path.separator\" defined! Using \"" + separator + "\"!"); } int index = classpath.indexOf(separator); int offset = 0; while (index != -1) { addClassPathElement(elements, classpath, offset, index); offset = index + separator.length(); index = classpath.indexOf(separator, offset); } addClassPathElement(elements, classpath, offset, classpath.length()); } /** * Adds a single classpath element into the provided <code>Vector</code>. * If the classpath element is an empty string it is not added. * * @param elements the <code>Vector</code> to which to add the classpath * element * @param classpath the classpath from which to "extract" the element * @param beginIndex the begin index of the element in * <code>classpath</code> * @param endIndex the end index of the element in <code>classpath</code> */ private static void addClassPathElement(final Vector elements, final String classpath, final int beginIndex, final int endIndex) { if (beginIndex == endIndex) { return; } final String element = classpath.substring(beginIndex, endIndex).trim(); if (element.length() > 0) { elements.addElement(element); } } }
true
true
private static Isolate startMidletCommon(MIDletSuiteStorage midletSuiteStorage, int externalAppId, int id, String midlet, String displayName, String arg0, String arg1, String arg2, int memoryReserved, int memoryTotal, int priority, String profileName, int debugMode) { Isolate isolate; String[] args = {Integer.toString(id), midlet, displayName, arg0, arg1, arg2, Integer.toString(externalAppId), String.valueOf(debugMode)}; String[] classpath = midletSuiteStorage.getMidletSuiteClassPath(id); if (classpath[0] == null && id == MIDletSuite.INTERNAL_SUITE_ID) { /* * Avoid a null pointer exception, rommized midlets don't need * a classpath. */ classpath[0] = ""; } else { throw new IllegalArgumentException("Suite " + id + " not found"); } Vector cpExtElements = new Vector(); String isolateClassPath = System.getProperty("classpathext"); if (isolateClassPath != null) { splitClassPath(cpExtElements, isolateClassPath); } /* * Include paths to dynamic components belonging to this suite * and to the "internal" suite (actually, to AMS) into class * path for the new Isolate. */ DynamicComponentStorage componentStorage = DynamicComponentStorage.getComponentStorage(); ComponentInfo[] ci = componentStorage.getListOfSuiteComponents(id); ComponentInfo[] ciAms = componentStorage.getListOfSuiteComponents( MIDletSuite.INTERNAL_SUITE_ID); int numOfComponents = 0; // calculate the number of the components to be added to the class path if (ci != null) { numOfComponents += ci.length; } if (ciAms != null) { numOfComponents += ciAms.length; } if (numOfComponents > 0) { Vector ciVector = new Vector(numOfComponents); // add the suite's own components if (ci != null) { for (int i = 0; i < ci.length; i++) { ciVector.addElement(ci[i]); } } // add the shared (belonging to AMS) components if (ciAms != null) { for (int i = 0; i < ciAms.length; i++) { ciVector.addElement(ciAms[i]); } } /* * IMPL_NOTE: currently is assumed that each component may have * not more than 1 entry in class path. * Later it will be possible to have 2: 1 for MONET. * + 1 is for System.getProperty("classpathext"). */ int n = 0; try { for (int i = 0; i < ciVector.size(); i++) { final ComponentInfo nextComponent = ((ComponentInfo)ciVector.elementAt(i)); final String[] componentPath = componentStorage.getComponentClassPath( nextComponent.getComponentId()); if (componentPath != null) { for (int j = 0; j < componentPath.length; j++) { cpExtElements.addElement(componentPath[j]); ++n; } } } } catch (Exception e) { /* * if something is wrong with a dynamic component, just * don't use the components, this error is not fatal */ cpExtElements.setSize(cpExtElements.size() - n); if (Logging.REPORT_LEVEL <= Logging.ERROR) { e.printStackTrace(); Logging.report(Logging.ERROR, LogChannels.LC_AMS, "Cannot use a dynamic component when starting '" + midlet + "' from the suite with id = " + id); } } } try { StartMIDletMonitor app = StartMIDletMonitor.okToStart(id, midlet); if (app == null) { // Isolate is already running; don't start it again return null; } final String[] classpathext = new String[cpExtElements.size()]; cpExtElements.copyInto(classpathext); isolate = new Isolate("com.sun.midp.main.AppIsolateMIDletSuiteLoader", args, classpath, classpathext); app.setIsolate(isolate); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException("Can't create Isolate****"); } try { int reserved, limit; if (memoryReserved >= 0) { reserved = memoryReserved; } else { reserved = Constants.SUITE_MEMORY_RESERVED * 1024; } if (memoryTotal > 0) { limit = memoryTotal; } else { limit = Constants.SUITE_MEMORY_LIMIT; if (limit < 0) { limit = isolate.totalMemory(); } else { limit = limit * 1024; } int heapSize = getMidletHeapSize(id, midlet); if ((heapSize > 0) && (heapSize < limit)) { limit = heapSize; } } isolate.setMemoryQuota(reserved, limit); if (priority >= Isolate.MIN_PRIORITY) { isolate.setPriority(priority); } if (profileName != null) { IsolateUtil.setProfile(isolate, profileName); } isolate.setDebug(debugMode); isolate.setAPIAccess(true); isolate.start(); // Ability to launch midlet implies right to use Service API // for negotiations with isolate being run Link[] isolateLinks = SystemServiceLinkPortal.establishLinksFor( isolate, getTrustedToken()); LinkPortal.setLinks(isolate, isolateLinks); } catch (Throwable t) { int errorCode; String msg; if (Logging.REPORT_LEVEL <= Logging.WARNING) { t.printStackTrace(); } if (t instanceof IsolateStartupException) { /* * An error occured in the * initialization or configuration of the new isolate * before any application code is invoked, or if this * Isolate was already started or is terminated. */ errorCode = Constants.MIDLET_ISOLATE_CONSTRUCTOR_FAILED; msg = "Can't start Application."; } else if (t instanceof IsolateResourceError) { /* The system has exceeded the maximum Isolate count. */ errorCode = Constants.MIDLET_ISOLATE_RESOURCE_LIMIT; msg = "No more concurrent applications allowed."; } else if (t instanceof IllegalArgumentException) { /* Requested profile doesn't exist. */ errorCode = Constants.MIDLET_ISOLATE_CONSTRUCTOR_FAILED; msg = "Invalid profile name: " + profileName; } else if (t instanceof OutOfMemoryError) { /* The reserved memory cannot be allocated */ errorCode = Constants.MIDLET_OUT_OF_MEM_ERROR; msg = "Not enough memory to run the application."; } else { errorCode = Constants.MIDLET_ISOLATE_CONSTRUCTOR_FAILED; msg = t.toString(); } midletControllerEventProducer.sendMIDletStartErrorEvent( id, midlet, externalAppId, errorCode, msg); throw new RuntimeException(msg); } return isolate; }
private static Isolate startMidletCommon(MIDletSuiteStorage midletSuiteStorage, int externalAppId, int id, String midlet, String displayName, String arg0, String arg1, String arg2, int memoryReserved, int memoryTotal, int priority, String profileName, int debugMode) { Isolate isolate; String[] args = {Integer.toString(id), midlet, displayName, arg0, arg1, arg2, Integer.toString(externalAppId), String.valueOf(debugMode)}; String[] classpath = midletSuiteStorage.getMidletSuiteClassPath(id); if (classpath[0] == null) { if (id == MIDletSuite.INTERNAL_SUITE_ID) { /* * Avoid a null pointer exception, rommized midlets don't need * a classpath. */ classpath[0] = ""; } else { throw new IllegalArgumentException("Suite " + id + " not found"); } } Vector cpExtElements = new Vector(); String isolateClassPath = System.getProperty("classpathext"); if (isolateClassPath != null) { splitClassPath(cpExtElements, isolateClassPath); } /* * Include paths to dynamic components belonging to this suite * and to the "internal" suite (actually, to AMS) into class * path for the new Isolate. */ DynamicComponentStorage componentStorage = DynamicComponentStorage.getComponentStorage(); ComponentInfo[] ci = componentStorage.getListOfSuiteComponents(id); ComponentInfo[] ciAms = componentStorage.getListOfSuiteComponents( MIDletSuite.INTERNAL_SUITE_ID); int numOfComponents = 0; // calculate the number of the components to be added to the class path if (ci != null) { numOfComponents += ci.length; } if (ciAms != null) { numOfComponents += ciAms.length; } if (numOfComponents > 0) { Vector ciVector = new Vector(numOfComponents); // add the suite's own components if (ci != null) { for (int i = 0; i < ci.length; i++) { ciVector.addElement(ci[i]); } } // add the shared (belonging to AMS) components if (ciAms != null) { for (int i = 0; i < ciAms.length; i++) { ciVector.addElement(ciAms[i]); } } /* * IMPL_NOTE: currently is assumed that each component may have * not more than 1 entry in class path. * Later it will be possible to have 2: 1 for MONET. * + 1 is for System.getProperty("classpathext"). */ int n = 0; try { for (int i = 0; i < ciVector.size(); i++) { final ComponentInfo nextComponent = ((ComponentInfo)ciVector.elementAt(i)); final String[] componentPath = componentStorage.getComponentClassPath( nextComponent.getComponentId()); if (componentPath != null) { for (int j = 0; j < componentPath.length; j++) { cpExtElements.addElement(componentPath[j]); ++n; } } } } catch (Exception e) { /* * if something is wrong with a dynamic component, just * don't use the components, this error is not fatal */ cpExtElements.setSize(cpExtElements.size() - n); if (Logging.REPORT_LEVEL <= Logging.ERROR) { e.printStackTrace(); Logging.report(Logging.ERROR, LogChannels.LC_AMS, "Cannot use a dynamic component when starting '" + midlet + "' from the suite with id = " + id); } } } try { StartMIDletMonitor app = StartMIDletMonitor.okToStart(id, midlet); if (app == null) { // Isolate is already running; don't start it again return null; } final String[] classpathext = new String[cpExtElements.size()]; cpExtElements.copyInto(classpathext); isolate = new Isolate("com.sun.midp.main.AppIsolateMIDletSuiteLoader", args, classpath, classpathext); app.setIsolate(isolate); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException("Can't create Isolate****"); } try { int reserved, limit; if (memoryReserved >= 0) { reserved = memoryReserved; } else { reserved = Constants.SUITE_MEMORY_RESERVED * 1024; } if (memoryTotal > 0) { limit = memoryTotal; } else { limit = Constants.SUITE_MEMORY_LIMIT; if (limit < 0) { limit = isolate.totalMemory(); } else { limit = limit * 1024; } int heapSize = getMidletHeapSize(id, midlet); if ((heapSize > 0) && (heapSize < limit)) { limit = heapSize; } } isolate.setMemoryQuota(reserved, limit); if (priority >= Isolate.MIN_PRIORITY) { isolate.setPriority(priority); } if (profileName != null) { IsolateUtil.setProfile(isolate, profileName); } isolate.setDebug(debugMode); isolate.setAPIAccess(true); isolate.start(); // Ability to launch midlet implies right to use Service API // for negotiations with isolate being run Link[] isolateLinks = SystemServiceLinkPortal.establishLinksFor( isolate, getTrustedToken()); LinkPortal.setLinks(isolate, isolateLinks); } catch (Throwable t) { int errorCode; String msg; if (Logging.REPORT_LEVEL <= Logging.WARNING) { t.printStackTrace(); } if (t instanceof IsolateStartupException) { /* * An error occured in the * initialization or configuration of the new isolate * before any application code is invoked, or if this * Isolate was already started or is terminated. */ errorCode = Constants.MIDLET_ISOLATE_CONSTRUCTOR_FAILED; msg = "Can't start Application."; } else if (t instanceof IsolateResourceError) { /* The system has exceeded the maximum Isolate count. */ errorCode = Constants.MIDLET_ISOLATE_RESOURCE_LIMIT; msg = "No more concurrent applications allowed."; } else if (t instanceof IllegalArgumentException) { /* Requested profile doesn't exist. */ errorCode = Constants.MIDLET_ISOLATE_CONSTRUCTOR_FAILED; msg = "Invalid profile name: " + profileName; } else if (t instanceof OutOfMemoryError) { /* The reserved memory cannot be allocated */ errorCode = Constants.MIDLET_OUT_OF_MEM_ERROR; msg = "Not enough memory to run the application."; } else { errorCode = Constants.MIDLET_ISOLATE_CONSTRUCTOR_FAILED; msg = t.toString(); } midletControllerEventProducer.sendMIDletStartErrorEvent( id, midlet, externalAppId, errorCode, msg); throw new RuntimeException(msg); } return isolate; }
diff --git a/src/instructions/UIG_Arithmetic.java b/src/instructions/UIG_Arithmetic.java index 8f8bdfb..700adbb 100644 --- a/src/instructions/UIG_Arithmetic.java +++ b/src/instructions/UIG_Arithmetic.java @@ -1,277 +1,277 @@ package instructions; import static assemblernator.ErrorReporting.makeError; import assemblernator.AbstractInstruction; import assemblernator.ErrorReporting.ErrorHandler; import assemblernator.Instruction.Operand; import assemblernator.IOFormat; import assemblernator.Module; import assemblernator.OperandChecker; /** * @author Eric * @date Apr 14, 2012; 5:22:20 PM */ public abstract class UIG_Arithmetic extends AbstractInstruction { /** * The type of operand specifying the destination for this operation. */ String dest = ""; /** *The type of operand specifying the source for this operation. */ String src = ""; /** * @author Eric * @date Apr 14, 2012; 5:52:36 PM */ @Override public final boolean check(ErrorHandler hErr, Module module) { boolean isValid = true; // any size under two is invalid if (this.operands.size() < 2) { isValid = false; hErr.reportError(makeError("instructionMissingOp", this.getOpId(), ""), this.lineNum, -1); // checks all combinations for two operands if a combo is not found // operands are invalid } else if (this.operands.size() == 2) { // checks combos associated with DM if (this.hasOperand("DM")) { dest = "DM"; //range checking Operand o = getOperandData("DM"); int constantSize = module.evaluate(o.expression, true, hErr, this, o.valueStartPosition); this.getOperandData("DM").value = constantSize; isValid = OperandChecker.isValidMem(constantSize); if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FR")) { src = "FR"; //range checking Operand o1 = getOperandData("FR"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FR").value = constantSize1; isValid = OperandChecker.isValidReg(constantSize1); if(!isValid) hErr.reportError(makeError("OORarithReg", "FR", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FM")) { src = "FM"; //range checking Operand o1 = getOperandData("FM"); int constantSize1 = module.evaluate(o1.expression, true, hErr, this, o1.valueStartPosition); this.getOperandData("FM").value = constantSize1; isValid = OperandChecker.isValidMem(constantSize1); if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FL")) { src = "FL"; //range checking Operand o1 = getOperandData("FL"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FL").value = constantSize1; - isValid = OperandChecker.isValidLiteral(constantSize1); + isValid = OperandChecker.isValidLiteral(constantSize1, ConstantRange.RANGE_ADDR); if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1); } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FR,FM, or FL", "DM"), this.lineNum, -1); } // checks combos associated with DR } else if (this.hasOperand("DR")) { dest = "DR"; //range checking Operand o = getOperandData("DR"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("DR").value = constantSize; isValid = OperandChecker.isValidReg(constantSize); if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FR")) { src = "FR"; //range checking Operand o1 = getOperandData("FR"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FR").value = constantSize1; isValid = OperandChecker.isValidReg(constantSize1); if(!isValid) hErr.reportError(makeError("OORarithReg", "FR", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FM")) { src = "FM"; //range checking Operand o1 = getOperandData("FM"); int constantSize1 = module.evaluate(o1.expression, true, hErr, this, o1.valueStartPosition); this.getOperandData("FM").value = constantSize1; isValid = OperandChecker.isValidMem(constantSize1); if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FL")) { //range checking Operand o1 = getOperandData("FL"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FL").value = constantSize1; - isValid = OperandChecker.isValidLiteral(constantSize1); + isValid = OperandChecker.isValidLiteral(constantSize1,ConstantRange.RANGE_16_TC); if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1); src = "FL"; } else if (this.hasOperand("FX")) { //range checking Operand o1 = getOperandData("FX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1); src = "FX"; } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FR,FM,FL, or FX", "DR"), this.lineNum, -1); } // checks combos associated with DX } else if (this.hasOperand("DX")) { dest = "DX"; //range checking Operand o = getOperandData("DX"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("DX").value = constantSize; isValid = OperandChecker.isValidIndex(constantSize); if(!isValid) hErr.reportError(makeError("OORidxReg", "DX", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FL")) { src = "FL"; //range checking Operand o1 = getOperandData("FL"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FL").value = constantSize1; - isValid = OperandChecker.isValidLiteral(constantSize1); + isValid = OperandChecker.isValidLiteral(constantSize1, ConstantRange.RANGE_16_TC); if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FX")) { src = "FX"; //range checking Operand o1 = getOperandData("FX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1); } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FX or FL", "DX"), this.lineNum, -1); } } else { isValid = false; hErr.reportError(makeError("instructionMissingOp", this.getOpId(), "DX,DR or DM"), this.lineNum, -1); } // checks all combinations for three operands instructions } else if (this.operands.size() == 3) { // checks combos associated FR if (this.hasOperand("FR")) { src = "FR"; //range checking Operand o = getOperandData("FR"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("FR").value = constantSize; isValid = OperandChecker.isValidReg(constantSize); if(!isValid) hErr.reportError(makeError("OORarithReg", "FR", this.getOpId()), this.lineNum, -1); if (this.hasOperand("DM") && this.hasOperand("DX")) { dest = "DMDX"; //range checking Operand o1 = getOperandData("DX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("DX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "DX", this.getOpId()), this.lineNum, -1); Operand o2 = getOperandData("DM"); int constantSize2 = module.evaluate(o2.expression, true, hErr, this, o2.valueStartPosition); this.getOperandData("DM").value = constantSize2; isValid = OperandChecker.isValidMem(constantSize2); if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1); } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "DM and DX", "FR"), this.lineNum, -1); } // checks combos associated DR } else if (this.hasOperand("DR")) { dest = "DR"; //range checking Operand o = getOperandData("DR"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("DR").value = constantSize; isValid = OperandChecker.isValidReg(constantSize); if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FX") && this.hasOperand("FM")) { //range checking Operand o1 = getOperandData("FX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1); Operand o2 = getOperandData("FM"); int constantSize2 = module.evaluate(o2.expression, true, hErr, this, o2.valueStartPosition); this.getOperandData("FM").value = constantSize2; isValid = OperandChecker.isValidMem(constantSize2); if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1); src = "FXFM"; } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FX and FM", "DR"), this.lineNum, -1); } } else { isValid = false; hErr.reportError(makeError("instructionMissingOp", this.getOpId(), "FR or DR"), this.lineNum, -1); } // more than three operands is invalid } else { isValid = false; hErr.reportError(makeError("extraOperandsIns", this.getOpId()), this.lineNum, -1); } return isValid; } /** * @author Eric * @date Apr 14, 2012; 5:52:36 PM */ @Override public final int[] assemble() { String code = IOFormat.formatBinInteger(this.getOpcode(), 6); if (dest == "DR") { if (src == "FM" || src == "FL" || src == "FXFM") { // format 0 } else { // format 1 } } else if (dest == "DX") { // and so on } return null; } /** * Invokes parent's constructor. * @param opid * @param opcode */ UIG_Arithmetic(String opid, int opcode) { super(opid, opcode); } /** * default constructor does nothing. */ UIG_Arithmetic() {} }
false
true
public final boolean check(ErrorHandler hErr, Module module) { boolean isValid = true; // any size under two is invalid if (this.operands.size() < 2) { isValid = false; hErr.reportError(makeError("instructionMissingOp", this.getOpId(), ""), this.lineNum, -1); // checks all combinations for two operands if a combo is not found // operands are invalid } else if (this.operands.size() == 2) { // checks combos associated with DM if (this.hasOperand("DM")) { dest = "DM"; //range checking Operand o = getOperandData("DM"); int constantSize = module.evaluate(o.expression, true, hErr, this, o.valueStartPosition); this.getOperandData("DM").value = constantSize; isValid = OperandChecker.isValidMem(constantSize); if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FR")) { src = "FR"; //range checking Operand o1 = getOperandData("FR"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FR").value = constantSize1; isValid = OperandChecker.isValidReg(constantSize1); if(!isValid) hErr.reportError(makeError("OORarithReg", "FR", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FM")) { src = "FM"; //range checking Operand o1 = getOperandData("FM"); int constantSize1 = module.evaluate(o1.expression, true, hErr, this, o1.valueStartPosition); this.getOperandData("FM").value = constantSize1; isValid = OperandChecker.isValidMem(constantSize1); if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FL")) { src = "FL"; //range checking Operand o1 = getOperandData("FL"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FL").value = constantSize1; isValid = OperandChecker.isValidLiteral(constantSize1); if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1); } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FR,FM, or FL", "DM"), this.lineNum, -1); } // checks combos associated with DR } else if (this.hasOperand("DR")) { dest = "DR"; //range checking Operand o = getOperandData("DR"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("DR").value = constantSize; isValid = OperandChecker.isValidReg(constantSize); if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FR")) { src = "FR"; //range checking Operand o1 = getOperandData("FR"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FR").value = constantSize1; isValid = OperandChecker.isValidReg(constantSize1); if(!isValid) hErr.reportError(makeError("OORarithReg", "FR", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FM")) { src = "FM"; //range checking Operand o1 = getOperandData("FM"); int constantSize1 = module.evaluate(o1.expression, true, hErr, this, o1.valueStartPosition); this.getOperandData("FM").value = constantSize1; isValid = OperandChecker.isValidMem(constantSize1); if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FL")) { //range checking Operand o1 = getOperandData("FL"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FL").value = constantSize1; isValid = OperandChecker.isValidLiteral(constantSize1); if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1); src = "FL"; } else if (this.hasOperand("FX")) { //range checking Operand o1 = getOperandData("FX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1); src = "FX"; } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FR,FM,FL, or FX", "DR"), this.lineNum, -1); } // checks combos associated with DX } else if (this.hasOperand("DX")) { dest = "DX"; //range checking Operand o = getOperandData("DX"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("DX").value = constantSize; isValid = OperandChecker.isValidIndex(constantSize); if(!isValid) hErr.reportError(makeError("OORidxReg", "DX", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FL")) { src = "FL"; //range checking Operand o1 = getOperandData("FL"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FL").value = constantSize1; isValid = OperandChecker.isValidLiteral(constantSize1); if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FX")) { src = "FX"; //range checking Operand o1 = getOperandData("FX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1); } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FX or FL", "DX"), this.lineNum, -1); } } else { isValid = false; hErr.reportError(makeError("instructionMissingOp", this.getOpId(), "DX,DR or DM"), this.lineNum, -1); } // checks all combinations for three operands instructions } else if (this.operands.size() == 3) { // checks combos associated FR if (this.hasOperand("FR")) { src = "FR"; //range checking Operand o = getOperandData("FR"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("FR").value = constantSize; isValid = OperandChecker.isValidReg(constantSize); if(!isValid) hErr.reportError(makeError("OORarithReg", "FR", this.getOpId()), this.lineNum, -1); if (this.hasOperand("DM") && this.hasOperand("DX")) { dest = "DMDX"; //range checking Operand o1 = getOperandData("DX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("DX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "DX", this.getOpId()), this.lineNum, -1); Operand o2 = getOperandData("DM"); int constantSize2 = module.evaluate(o2.expression, true, hErr, this, o2.valueStartPosition); this.getOperandData("DM").value = constantSize2; isValid = OperandChecker.isValidMem(constantSize2); if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1); } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "DM and DX", "FR"), this.lineNum, -1); } // checks combos associated DR } else if (this.hasOperand("DR")) { dest = "DR"; //range checking Operand o = getOperandData("DR"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("DR").value = constantSize; isValid = OperandChecker.isValidReg(constantSize); if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FX") && this.hasOperand("FM")) { //range checking Operand o1 = getOperandData("FX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1); Operand o2 = getOperandData("FM"); int constantSize2 = module.evaluate(o2.expression, true, hErr, this, o2.valueStartPosition); this.getOperandData("FM").value = constantSize2; isValid = OperandChecker.isValidMem(constantSize2); if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1); src = "FXFM"; } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FX and FM", "DR"), this.lineNum, -1); } } else { isValid = false; hErr.reportError(makeError("instructionMissingOp", this.getOpId(), "FR or DR"), this.lineNum, -1); } // more than three operands is invalid } else { isValid = false; hErr.reportError(makeError("extraOperandsIns", this.getOpId()), this.lineNum, -1); } return isValid; }
public final boolean check(ErrorHandler hErr, Module module) { boolean isValid = true; // any size under two is invalid if (this.operands.size() < 2) { isValid = false; hErr.reportError(makeError("instructionMissingOp", this.getOpId(), ""), this.lineNum, -1); // checks all combinations for two operands if a combo is not found // operands are invalid } else if (this.operands.size() == 2) { // checks combos associated with DM if (this.hasOperand("DM")) { dest = "DM"; //range checking Operand o = getOperandData("DM"); int constantSize = module.evaluate(o.expression, true, hErr, this, o.valueStartPosition); this.getOperandData("DM").value = constantSize; isValid = OperandChecker.isValidMem(constantSize); if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FR")) { src = "FR"; //range checking Operand o1 = getOperandData("FR"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FR").value = constantSize1; isValid = OperandChecker.isValidReg(constantSize1); if(!isValid) hErr.reportError(makeError("OORarithReg", "FR", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FM")) { src = "FM"; //range checking Operand o1 = getOperandData("FM"); int constantSize1 = module.evaluate(o1.expression, true, hErr, this, o1.valueStartPosition); this.getOperandData("FM").value = constantSize1; isValid = OperandChecker.isValidMem(constantSize1); if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FL")) { src = "FL"; //range checking Operand o1 = getOperandData("FL"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FL").value = constantSize1; isValid = OperandChecker.isValidLiteral(constantSize1, ConstantRange.RANGE_ADDR); if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1); } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FR,FM, or FL", "DM"), this.lineNum, -1); } // checks combos associated with DR } else if (this.hasOperand("DR")) { dest = "DR"; //range checking Operand o = getOperandData("DR"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("DR").value = constantSize; isValid = OperandChecker.isValidReg(constantSize); if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FR")) { src = "FR"; //range checking Operand o1 = getOperandData("FR"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FR").value = constantSize1; isValid = OperandChecker.isValidReg(constantSize1); if(!isValid) hErr.reportError(makeError("OORarithReg", "FR", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FM")) { src = "FM"; //range checking Operand o1 = getOperandData("FM"); int constantSize1 = module.evaluate(o1.expression, true, hErr, this, o1.valueStartPosition); this.getOperandData("FM").value = constantSize1; isValid = OperandChecker.isValidMem(constantSize1); if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FL")) { //range checking Operand o1 = getOperandData("FL"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FL").value = constantSize1; isValid = OperandChecker.isValidLiteral(constantSize1,ConstantRange.RANGE_16_TC); if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1); src = "FL"; } else if (this.hasOperand("FX")) { //range checking Operand o1 = getOperandData("FX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1); src = "FX"; } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FR,FM,FL, or FX", "DR"), this.lineNum, -1); } // checks combos associated with DX } else if (this.hasOperand("DX")) { dest = "DX"; //range checking Operand o = getOperandData("DX"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("DX").value = constantSize; isValid = OperandChecker.isValidIndex(constantSize); if(!isValid) hErr.reportError(makeError("OORidxReg", "DX", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FL")) { src = "FL"; //range checking Operand o1 = getOperandData("FL"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FL").value = constantSize1; isValid = OperandChecker.isValidLiteral(constantSize1, ConstantRange.RANGE_16_TC); if(!isValid) hErr.reportError(makeError("OOR13tc", "FL", this.getOpId()), this.lineNum, -1); } else if (this.hasOperand("FX")) { src = "FX"; //range checking Operand o1 = getOperandData("FX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1); } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FX or FL", "DX"), this.lineNum, -1); } } else { isValid = false; hErr.reportError(makeError("instructionMissingOp", this.getOpId(), "DX,DR or DM"), this.lineNum, -1); } // checks all combinations for three operands instructions } else if (this.operands.size() == 3) { // checks combos associated FR if (this.hasOperand("FR")) { src = "FR"; //range checking Operand o = getOperandData("FR"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("FR").value = constantSize; isValid = OperandChecker.isValidReg(constantSize); if(!isValid) hErr.reportError(makeError("OORarithReg", "FR", this.getOpId()), this.lineNum, -1); if (this.hasOperand("DM") && this.hasOperand("DX")) { dest = "DMDX"; //range checking Operand o1 = getOperandData("DX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("DX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "DX", this.getOpId()), this.lineNum, -1); Operand o2 = getOperandData("DM"); int constantSize2 = module.evaluate(o2.expression, true, hErr, this, o2.valueStartPosition); this.getOperandData("DM").value = constantSize2; isValid = OperandChecker.isValidMem(constantSize2); if(!isValid) hErr.reportError(makeError("OORmemAddr", "DM", this.getOpId()), this.lineNum, -1); } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "DM and DX", "FR"), this.lineNum, -1); } // checks combos associated DR } else if (this.hasOperand("DR")) { dest = "DR"; //range checking Operand o = getOperandData("DR"); int constantSize = module.evaluate(o.expression, false, hErr, this, o.valueStartPosition); this.getOperandData("DR").value = constantSize; isValid = OperandChecker.isValidReg(constantSize); if(!isValid) hErr.reportError(makeError("OORarithReg", "DR", this.getOpId()), this.lineNum, -1); if (this.hasOperand("FX") && this.hasOperand("FM")) { //range checking Operand o1 = getOperandData("FX"); int constantSize1 = module.evaluate(o1.expression, false, hErr, this, o1.valueStartPosition); this.getOperandData("FX").value = constantSize1; isValid = OperandChecker.isValidIndex(constantSize1); if(!isValid) hErr.reportError(makeError("OORidxReg", "FX", this.getOpId()), this.lineNum, -1); Operand o2 = getOperandData("FM"); int constantSize2 = module.evaluate(o2.expression, true, hErr, this, o2.valueStartPosition); this.getOperandData("FM").value = constantSize2; isValid = OperandChecker.isValidMem(constantSize2); if(!isValid) hErr.reportError(makeError("OORmemAddr", "FM", this.getOpId()), this.lineNum, -1); src = "FXFM"; } else { isValid = false; hErr.reportError(makeError("operandInsNeedAdd", this.getOpId(), "FX and FM", "DR"), this.lineNum, -1); } } else { isValid = false; hErr.reportError(makeError("instructionMissingOp", this.getOpId(), "FR or DR"), this.lineNum, -1); } // more than three operands is invalid } else { isValid = false; hErr.reportError(makeError("extraOperandsIns", this.getOpId()), this.lineNum, -1); } return isValid; }
diff --git a/src/Couch25K.java b/src/Couch25K.java index 9390e8e..c204961 100644 --- a/src/Couch25K.java +++ b/src/Couch25K.java @@ -1,307 +1,307 @@ import java.io.IOException; import java.io.InputStream; import java.util.Timer; import java.util.TimerTask; import javax.microedition.lcdui.Choice; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Font; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.Gauge; import javax.microedition.lcdui.Item; import javax.microedition.lcdui.List; import javax.microedition.lcdui.StringItem; import javax.microedition.media.Manager; import javax.microedition.media.MediaException; import javax.microedition.media.Player; import javax.microedition.media.PlayerListener; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class Couch25K extends MIDlet implements CommandListener, PlayerListener { private static final int STATE_SELECT_WEEK = 1; private static final int STATE_SELECT_WORKOUT = 2; private static final int STATE_WORKOUT_SELECTED = 3; private static final int STATE_WORKOUT = 4; private static final int STATE_WORKOUT_PAUSED = 5; private static final int STATE_WORKOUT_COMPLETE = 6; // State private int state; private int selectedWeek; private int selectedWorkout; private Workout workout; private WorkoutState workoutState; // UI private Display display; private Font bigBoldFont; private List selectWeekScreen; private List selectWorkoutScreen; private Form workoutSummaryScreen; private Form workoutScreen; private StringItem action; private Gauge stepProgress; private StringItem stepCount; private StringItem stepTime; private Gauge workoutProgress; private StringItem workoutTime; private Form workoutCompleteScreen; // Commands private Command backCommand = new Command("Back", Command.BACK, 1); private Command selectCommand = new Command("Select", Command.ITEM, 1); private Command startCommand = new Command("Start", Command.SCREEN, 1); private Command pauseCommand = new Command("Pause", Command.SCREEN, 2); private Command resumeCommand = new Command("Resume", Command.SCREEN, 3); // Timing private Timer workoutTimer; // MIDlet API -------------------------------------------------------------- protected void startApp() throws MIDletStateChangeException { if (display == null) { display = Display.getDisplay(this); bigBoldFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE); // Week selection screen setup selectWeekScreen = new List("Select Week", Choice.IMPLICIT, new String[] { "Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6", "Week 7", "Week 8", "Week 9" }, null); selectWeekScreen.addCommand(selectCommand); selectWeekScreen.setCommandListener(this); // Workout selection screen setup selectWorkoutScreen = new List("Select Workout", Choice.IMPLICIT, new String[] { "Workout 1", "Workout 2", "Workout 3" }, null); selectWorkoutScreen.addCommand(selectCommand); selectWorkoutScreen.addCommand(backCommand); selectWorkoutScreen.setCommandListener(this); // Workout summary screen setup workoutSummaryScreen = new Form(""); workoutSummaryScreen.addCommand(startCommand); workoutSummaryScreen.addCommand(backCommand); workoutSummaryScreen.setCommandListener(this); // Workout screen setup workoutScreen = new Form(""); action = new StringItem(null, ""); action.setFont(bigBoldFont); stepProgress = new Gauge(null, false, Gauge.INDEFINITE, 0); stepProgress.setLayout(Item.LAYOUT_EXPAND); stepCount = new StringItem(null, ""); stepCount.setFont(bigBoldFont); stepCount.setLayout(Item.LAYOUT_EXPAND); stepTime = new StringItem(null, ""); stepTime.setFont(bigBoldFont); workoutProgress = new Gauge("Workout", false, Gauge.INDEFINITE, 0); workoutProgress.setLayout(Item.LAYOUT_EXPAND); workoutTime = new StringItem(null, ""); workoutTime.setLayout(Item.LAYOUT_RIGHT); workoutScreen.append(action); workoutScreen.append(stepProgress); workoutScreen.append(stepCount); workoutScreen.append(stepTime); workoutScreen.append(workoutProgress); workoutScreen.append(workoutTime); workoutScreen.addCommand(pauseCommand); workoutScreen.setCommandListener(this); workoutCompleteScreen = new Form("Workout Complete"); workoutCompleteScreen.setCommandListener(this); } if (state == STATE_WORKOUT_PAUSED) { - startWorkout(); + resumeWorkout(); } else { init(); } } protected void pauseApp() { if (state == STATE_WORKOUT) { pauseWorkout(); } } protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { } // CommandListener API ----------------------------------------------------- public void commandAction(Command c, Displayable d) { switch (state) { case STATE_SELECT_WEEK: if (c == selectCommand) selectWeek(); break; case STATE_SELECT_WORKOUT: if (c == selectCommand) selectWorkout(); else if (c == backCommand) init(); break; case STATE_WORKOUT_SELECTED: if (c == startCommand) startWorkout(); else if (c == backCommand) selectWeek(); break; case STATE_WORKOUT: if (c == pauseCommand) pauseWorkout(); break; case STATE_WORKOUT_PAUSED: if (c == resumeCommand) resumeWorkout(); break; default: throw new IllegalStateException("Command " + c + " not expected in state " + state); } } // PlayerListener API ------------------------------------------------------ public void playerUpdate(Player player, String event, Object eventData) { if (event == PlayerListener.END_OF_MEDIA) { player.close(); } } // State transitions ------------------------------------------------------- public void init() { display.setCurrent(selectWeekScreen); state = STATE_SELECT_WEEK; } public void selectWeek() { selectedWeek = selectWeekScreen.getSelectedIndex() + 1; display.setCurrent(selectWorkoutScreen); state = STATE_SELECT_WORKOUT; } public void selectWorkout() { selectedWorkout = selectWorkoutScreen.getSelectedIndex() + 1; workout = Workouts.getWorkout(selectedWeek, selectedWorkout); workoutSummaryScreen.setTitle("Week " + selectedWeek + " - Workout " + selectedWorkout); workoutSummaryScreen.deleteAll(); for (int i = 0; i < workout.steps.length; i++) { workoutSummaryScreen.append(new StringItem(null, workout.steps[i].action + " for " + displayDuration(workout.steps[i].duration) + "\n" )); } display.setCurrent(workoutSummaryScreen); state = STATE_WORKOUT_SELECTED; } public void startWorkout() { workoutState = new WorkoutState(this, workout); workoutScreen.setTitle("Week " + selectedWeek + " - Workout " + selectedWorkout); workoutProgress.setMaxValue(workout.totalDuration); workoutProgress.setValue(0); display.setCurrent(workoutScreen); trackWorkoutState(workoutState); state = STATE_WORKOUT; } public void pauseWorkout() { workoutTimer.cancel(); workoutScreen.removeCommand(pauseCommand); workoutScreen.addCommand(resumeCommand); state = STATE_WORKOUT_PAUSED; } public void resumeWorkout() { workoutScreen.removeCommand(resumeCommand); workoutScreen.addCommand(pauseCommand); trackWorkoutState(workoutState); state = STATE_WORKOUT; } public void finishWorkout() { workoutTimer.cancel(); display.setCurrent(workoutCompleteScreen); playSound("finished"); state = STATE_WORKOUT_COMPLETE; } // Status update API ------------------------------------------------------- public void updateStep(int stepNum, WorkoutStep step) { action.setText(step.action + " for " + displayDuration(step.duration)); stepCount.setText(stepNum + " of " + workout.steps.length); stepProgress.setValue(0); stepProgress.setMaxValue(step.duration); if (stepNum > 1) { playSound(step.action.toLowerCase()); } } public void updateProgress(int progress, int totalTime) { stepProgress.setValue(progress); stepTime.setText(displayTime(progress)); workoutProgress.setValue(totalTime); workoutTime.setText(displayTime(totalTime)); } // Utilities --------------------------------------------------------------- private void trackWorkoutState(final WorkoutState workoutState) { workoutTimer = new Timer(); workoutTimer.scheduleAtFixedRate(new TimerTask() { public void run() { workoutState.increment(); } }, 0, 1000); } private void playSound(String action) { try { InputStream in = getClass().getResourceAsStream("/" + action + ".mp3"); Player player = Manager.createPlayer(in, "audio/mpeg"); player.addPlayerListener(this); player.start(); } catch (MediaException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private String displayDuration(int n) { if (n <= 90) { return n + " seconds"; } int min = n / 60; int sec = n % 60; if (sec == 0) { return min + " minutes"; } return (min + (float)sec/60) + " minutes"; } private String displayTime(int n) { int minutes = n / 60; int seconds = n % 60; return pad(minutes) + ":" + pad(seconds); } private String pad(int n) { if (n < 10) { return "0" + n; } return "" + n; } }
true
true
protected void startApp() throws MIDletStateChangeException { if (display == null) { display = Display.getDisplay(this); bigBoldFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE); // Week selection screen setup selectWeekScreen = new List("Select Week", Choice.IMPLICIT, new String[] { "Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6", "Week 7", "Week 8", "Week 9" }, null); selectWeekScreen.addCommand(selectCommand); selectWeekScreen.setCommandListener(this); // Workout selection screen setup selectWorkoutScreen = new List("Select Workout", Choice.IMPLICIT, new String[] { "Workout 1", "Workout 2", "Workout 3" }, null); selectWorkoutScreen.addCommand(selectCommand); selectWorkoutScreen.addCommand(backCommand); selectWorkoutScreen.setCommandListener(this); // Workout summary screen setup workoutSummaryScreen = new Form(""); workoutSummaryScreen.addCommand(startCommand); workoutSummaryScreen.addCommand(backCommand); workoutSummaryScreen.setCommandListener(this); // Workout screen setup workoutScreen = new Form(""); action = new StringItem(null, ""); action.setFont(bigBoldFont); stepProgress = new Gauge(null, false, Gauge.INDEFINITE, 0); stepProgress.setLayout(Item.LAYOUT_EXPAND); stepCount = new StringItem(null, ""); stepCount.setFont(bigBoldFont); stepCount.setLayout(Item.LAYOUT_EXPAND); stepTime = new StringItem(null, ""); stepTime.setFont(bigBoldFont); workoutProgress = new Gauge("Workout", false, Gauge.INDEFINITE, 0); workoutProgress.setLayout(Item.LAYOUT_EXPAND); workoutTime = new StringItem(null, ""); workoutTime.setLayout(Item.LAYOUT_RIGHT); workoutScreen.append(action); workoutScreen.append(stepProgress); workoutScreen.append(stepCount); workoutScreen.append(stepTime); workoutScreen.append(workoutProgress); workoutScreen.append(workoutTime); workoutScreen.addCommand(pauseCommand); workoutScreen.setCommandListener(this); workoutCompleteScreen = new Form("Workout Complete"); workoutCompleteScreen.setCommandListener(this); } if (state == STATE_WORKOUT_PAUSED) { startWorkout(); } else { init(); } }
protected void startApp() throws MIDletStateChangeException { if (display == null) { display = Display.getDisplay(this); bigBoldFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE); // Week selection screen setup selectWeekScreen = new List("Select Week", Choice.IMPLICIT, new String[] { "Week 1", "Week 2", "Week 3", "Week 4", "Week 5", "Week 6", "Week 7", "Week 8", "Week 9" }, null); selectWeekScreen.addCommand(selectCommand); selectWeekScreen.setCommandListener(this); // Workout selection screen setup selectWorkoutScreen = new List("Select Workout", Choice.IMPLICIT, new String[] { "Workout 1", "Workout 2", "Workout 3" }, null); selectWorkoutScreen.addCommand(selectCommand); selectWorkoutScreen.addCommand(backCommand); selectWorkoutScreen.setCommandListener(this); // Workout summary screen setup workoutSummaryScreen = new Form(""); workoutSummaryScreen.addCommand(startCommand); workoutSummaryScreen.addCommand(backCommand); workoutSummaryScreen.setCommandListener(this); // Workout screen setup workoutScreen = new Form(""); action = new StringItem(null, ""); action.setFont(bigBoldFont); stepProgress = new Gauge(null, false, Gauge.INDEFINITE, 0); stepProgress.setLayout(Item.LAYOUT_EXPAND); stepCount = new StringItem(null, ""); stepCount.setFont(bigBoldFont); stepCount.setLayout(Item.LAYOUT_EXPAND); stepTime = new StringItem(null, ""); stepTime.setFont(bigBoldFont); workoutProgress = new Gauge("Workout", false, Gauge.INDEFINITE, 0); workoutProgress.setLayout(Item.LAYOUT_EXPAND); workoutTime = new StringItem(null, ""); workoutTime.setLayout(Item.LAYOUT_RIGHT); workoutScreen.append(action); workoutScreen.append(stepProgress); workoutScreen.append(stepCount); workoutScreen.append(stepTime); workoutScreen.append(workoutProgress); workoutScreen.append(workoutTime); workoutScreen.addCommand(pauseCommand); workoutScreen.setCommandListener(this); workoutCompleteScreen = new Form("Workout Complete"); workoutCompleteScreen.setCommandListener(this); } if (state == STATE_WORKOUT_PAUSED) { resumeWorkout(); } else { init(); } }
diff --git a/core/src/main/java/com/predic8/membrane/core/transport/http/ConnectionManager.java b/core/src/main/java/com/predic8/membrane/core/transport/http/ConnectionManager.java index 007af39a..4aacb7e5 100644 --- a/core/src/main/java/com/predic8/membrane/core/transport/http/ConnectionManager.java +++ b/core/src/main/java/com/predic8/membrane/core/transport/http/ConnectionManager.java @@ -1,240 +1,239 @@ /* Copyright 2011, 2012 predic8 GmbH, www.predic8.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.predic8.membrane.core.transport.http; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.common.base.Objects; import com.predic8.membrane.core.transport.ssl.SSLProvider; /** * Pools TCP/IP connections, holding them open for a configurable number of milliseconds. * * With keep-alive use as follows: * <code> * Connection connection = connectionManager.getConnection(...); * try { * ... * } finally { * connection.release(); * } * </code> * * Without keep-alive replace {@link Connection#release()} by {@link Connection#close()}. * * Note that you should call {@link Connection#release()} exactly once, or alternatively * {@link Connection#close()} at least once. */ public class ConnectionManager { private static Log log = LogFactory.getLog(ConnectionManager.class.getName()); private final long keepAliveTimeout; private final long autoCloseInterval; private static class ConnectionKey { public final InetAddress host; public final int port; public ConnectionKey(InetAddress host, int port) { this.host = host; this.port = port; } @Override public int hashCode() { return Objects.hashCode(host, port); } @Override public boolean equals(Object obj) { if (!(obj instanceof ConnectionKey) || obj == null) return false; ConnectionKey other = (ConnectionKey)obj; return host.equals(other.host) && port == other.port; } @Override public String toString() { return host + ":" + port; } } private static class OldConnection { public final Connection connection; public final long deathTime; public OldConnection(Connection connection, long defaultKeepAliveTimeout) { this.connection = connection; long lastUse = connection.getLastUse(); if (lastUse == 0) lastUse = System.currentTimeMillis(); long delta = connection.getTimeout(); if (delta == 0) delta = defaultKeepAliveTimeout; if (delta > 400) delta -= 400; // slippage else delta = 0; if (connection.getCompletedExchanges() >= connection.getMaxExchanges()) delta = 0; // let the background closer do its job this.deathTime = lastUse + delta; } } private AtomicInteger numberInPool = new AtomicInteger(); private HashMap<ConnectionKey, ArrayList<OldConnection>> availableConnections = new HashMap<ConnectionManager.ConnectionKey, ArrayList<OldConnection>>(); // guarded by this private Timer timer; private volatile boolean shutdownWhenDone = false; public ConnectionManager(long keepAliveTimeout) { this.keepAliveTimeout = keepAliveTimeout; this.autoCloseInterval = keepAliveTimeout * 2; timer = new Timer("Connection Closer", true); timer.schedule(new TimerTask() { @Override public void run() { if (closeOldConnections() == 0 && shutdownWhenDone) timer.cancel(); } }, autoCloseInterval, autoCloseInterval); } public Connection getConnection(InetAddress host, int port, String localHost, SSLProvider sslProvider, int connectTimeout) throws UnknownHostException, IOException { log.debug("connection requested for host: " + host + " and port: " + port); log.debug("Number of connections in pool: " + numberInPool.get()); ConnectionKey key = new ConnectionKey(host, port); long now = System.currentTimeMillis(); synchronized(this) { ArrayList<OldConnection> l = availableConnections.get(key); if (l != null) { int i = l.size() - 1; while(i >= 0) { OldConnection c = l.get(i); if (c.deathTime > now) { l.remove(i); return c.connection; } Collections.swap(l, 0, i); i--; } } } Connection result = Connection.open(host, port, localHost, sslProvider, this, connectTimeout); numberInPool.incrementAndGet(); return result; } public void releaseConnection(Connection connection) { if (connection == null) return; if (connection.isClosed()) { numberInPool.decrementAndGet(); return; } ConnectionKey key = new ConnectionKey(connection.socket.getInetAddress(), connection.socket.getPort()); OldConnection o = new OldConnection(connection, keepAliveTimeout); ArrayList<OldConnection> l; synchronized(this) { l = availableConnections.get(key); if (l == null) { l = new ArrayList<OldConnection>(); availableConnections.put(key, l); } l.add(o); } } private int closeOldConnections() { ArrayList<ConnectionKey> toRemove = new ArrayList<ConnectionKey>(); ArrayList<Connection> toClose = new ArrayList<Connection>(); long now = System.currentTimeMillis(); log.trace("closing old connections"); int closed = 0, remaining; synchronized(this) { // close connections after their timeout for (Map.Entry<ConnectionKey, ArrayList<OldConnection>> e : availableConnections.entrySet()) { ArrayList<OldConnection> l = e.getValue(); for (int i = 0; i < l.size(); i++) { OldConnection o = l.get(i); if (o.deathTime < now) { // replace [i] by [last] if (i == l.size() - 1) l.remove(i); else l.set(i, l.remove(l.size() - 1)); --i; closed++; toClose.add(o.connection); } } if (l.size() == 0) toRemove.add(e.getKey()); } for (ConnectionKey remove : toRemove) availableConnections.remove(remove); remaining = availableConnections.size(); } for (Connection c : toClose) { try { c.close(); } catch (Exception e) { // do nothing } } - numberInPool.addAndGet(-closed); if (closed != 0) log.debug("closed " + closed + " connections"); return remaining; } public void shutdownWhenDone() { shutdownWhenDone = true; } public int getNumberInPool() { return numberInPool.get(); } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Number in pool: " + numberInPool.get() + "\n"); synchronized(this) { for (Map.Entry<ConnectionKey, ArrayList<OldConnection>> e : availableConnections.entrySet()) { sb.append("To " + e.getKey() + ": " + e.getValue().size() + "\n"); } } return sb.toString(); } }
true
true
private int closeOldConnections() { ArrayList<ConnectionKey> toRemove = new ArrayList<ConnectionKey>(); ArrayList<Connection> toClose = new ArrayList<Connection>(); long now = System.currentTimeMillis(); log.trace("closing old connections"); int closed = 0, remaining; synchronized(this) { // close connections after their timeout for (Map.Entry<ConnectionKey, ArrayList<OldConnection>> e : availableConnections.entrySet()) { ArrayList<OldConnection> l = e.getValue(); for (int i = 0; i < l.size(); i++) { OldConnection o = l.get(i); if (o.deathTime < now) { // replace [i] by [last] if (i == l.size() - 1) l.remove(i); else l.set(i, l.remove(l.size() - 1)); --i; closed++; toClose.add(o.connection); } } if (l.size() == 0) toRemove.add(e.getKey()); } for (ConnectionKey remove : toRemove) availableConnections.remove(remove); remaining = availableConnections.size(); } for (Connection c : toClose) { try { c.close(); } catch (Exception e) { // do nothing } } numberInPool.addAndGet(-closed); if (closed != 0) log.debug("closed " + closed + " connections"); return remaining; }
private int closeOldConnections() { ArrayList<ConnectionKey> toRemove = new ArrayList<ConnectionKey>(); ArrayList<Connection> toClose = new ArrayList<Connection>(); long now = System.currentTimeMillis(); log.trace("closing old connections"); int closed = 0, remaining; synchronized(this) { // close connections after their timeout for (Map.Entry<ConnectionKey, ArrayList<OldConnection>> e : availableConnections.entrySet()) { ArrayList<OldConnection> l = e.getValue(); for (int i = 0; i < l.size(); i++) { OldConnection o = l.get(i); if (o.deathTime < now) { // replace [i] by [last] if (i == l.size() - 1) l.remove(i); else l.set(i, l.remove(l.size() - 1)); --i; closed++; toClose.add(o.connection); } } if (l.size() == 0) toRemove.add(e.getKey()); } for (ConnectionKey remove : toRemove) availableConnections.remove(remove); remaining = availableConnections.size(); } for (Connection c : toClose) { try { c.close(); } catch (Exception e) { // do nothing } } if (closed != 0) log.debug("closed " + closed + " connections"); return remaining; }
diff --git a/src/main/java/org/soundboard/server/command/ListCommand.java b/src/main/java/org/soundboard/server/command/ListCommand.java index a16ceeb..cbe2be7 100644 --- a/src/main/java/org/soundboard/server/command/ListCommand.java +++ b/src/main/java/org/soundboard/server/command/ListCommand.java @@ -1,87 +1,92 @@ /*** ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public ** License along with this library; if not, write to the Free Software ** Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ** **/ package org.soundboard.server.command; import java.util.*; import java.util.regex.*; import org.soundboard.library.*; import org.soundboard.server.*; import org.soundboard.server.inputservice.*; import com.google.common.base.Joiner; public class ListCommand extends Command { /** * return if this command should affects karma */ @Override public boolean affectsKarma() { return false; } /** * get the command description */ @Override public String getDescription() { return "Lists all of the sound files in the library. "; } /** * execute the command with the given arguements. Note that args[0] is the name of the command. */ @Override public String execute(InputService inputService, String who, String[] args, boolean isCron, boolean respondWithHtml) { LoggingService.getInstance().serverLog(who + ": " + Joiner.on(" ").join(args)); StringBuilder out = new StringBuilder(); SoundLibrary library = args.length > 1 && SoundLibrarian.libraryExists(args[1]) ? SoundLibrarian.getInstance(args[1]) : SoundLibrarian.getInstance(); Set<String> books = library.list(); boolean returnedData = false; if (respondWithHtml) { out.append("<table>"); } + String base = "play/"; + if (args.length > 1 && SoundLibrarian.libraryExists(args[1])) { + base = args[1] + "/"; + } if (books.size() > 0) { Pattern pattern = null; - if (args.length >= 2) { + if (args.length > 2) { pattern = Pattern.compile(args[2], Pattern.CASE_INSENSITIVE); } for (String book : books) { if (pattern == null || pattern.matcher(book).find()) { if (respondWithHtml) { - out.append("<tr><td><a href=\"/play/"); + out.append("<tr><td><a href=\"/"); + out.append(base); out.append(book); out.append("\">"); out.append(book); out.append("</a>"); out.append("</td></tr>"); } else { out.append(book); out.append("\n"); } returnedData = true; } } } if (respondWithHtml) { out.append("</table>"); } if (!returnedData) { out.append("No sounds in the library that match."); out.append("\n"); } return out.toString(); } }
false
true
@Override public String execute(InputService inputService, String who, String[] args, boolean isCron, boolean respondWithHtml) { LoggingService.getInstance().serverLog(who + ": " + Joiner.on(" ").join(args)); StringBuilder out = new StringBuilder(); SoundLibrary library = args.length > 1 && SoundLibrarian.libraryExists(args[1]) ? SoundLibrarian.getInstance(args[1]) : SoundLibrarian.getInstance(); Set<String> books = library.list(); boolean returnedData = false; if (respondWithHtml) { out.append("<table>"); } if (books.size() > 0) { Pattern pattern = null; if (args.length >= 2) { pattern = Pattern.compile(args[2], Pattern.CASE_INSENSITIVE); } for (String book : books) { if (pattern == null || pattern.matcher(book).find()) { if (respondWithHtml) { out.append("<tr><td><a href=\"/play/"); out.append(book); out.append("\">"); out.append(book); out.append("</a>"); out.append("</td></tr>"); } else { out.append(book); out.append("\n"); } returnedData = true; } } } if (respondWithHtml) { out.append("</table>"); } if (!returnedData) { out.append("No sounds in the library that match."); out.append("\n"); } return out.toString(); }
@Override public String execute(InputService inputService, String who, String[] args, boolean isCron, boolean respondWithHtml) { LoggingService.getInstance().serverLog(who + ": " + Joiner.on(" ").join(args)); StringBuilder out = new StringBuilder(); SoundLibrary library = args.length > 1 && SoundLibrarian.libraryExists(args[1]) ? SoundLibrarian.getInstance(args[1]) : SoundLibrarian.getInstance(); Set<String> books = library.list(); boolean returnedData = false; if (respondWithHtml) { out.append("<table>"); } String base = "play/"; if (args.length > 1 && SoundLibrarian.libraryExists(args[1])) { base = args[1] + "/"; } if (books.size() > 0) { Pattern pattern = null; if (args.length > 2) { pattern = Pattern.compile(args[2], Pattern.CASE_INSENSITIVE); } for (String book : books) { if (pattern == null || pattern.matcher(book).find()) { if (respondWithHtml) { out.append("<tr><td><a href=\"/"); out.append(base); out.append(book); out.append("\">"); out.append(book); out.append("</a>"); out.append("</td></tr>"); } else { out.append(book); out.append("\n"); } returnedData = true; } } } if (respondWithHtml) { out.append("</table>"); } if (!returnedData) { out.append("No sounds in the library that match."); out.append("\n"); } return out.toString(); }
diff --git a/src/jtvprog/RibbonReleaser.java b/src/jtvprog/RibbonReleaser.java index a8465dd..589986e 100644 --- a/src/jtvprog/RibbonReleaser.java +++ b/src/jtvprog/RibbonReleaser.java @@ -1,114 +1,114 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package jtvprog; /** * Release TV program to Ribbon system. * @author Stanislav Nepochatov <[email protected]> */ public class RibbonReleaser { /** * Releaser configuration properties. */ private java.util.Properties releaseProps; /** * Channel release flag. */ private Boolean channelRelease; /** * Day release flag. */ private Boolean dayRelease; /** * Allow incomplete relese. */ private Boolean allowIncomplete; /** * Status of execution. */ private String status; /** * Default constructor. */ public RibbonReleaser() { releaseProps = JTVProg.tvApp.getProperties("Release.properties", JTVProg.class.getResourceAsStream("Release.properties")); this.channelRelease = Boolean.parseBoolean(releaseProps.getProperty("release_channel")); this.dayRelease = Boolean.parseBoolean(releaseProps.getProperty("release_day")); this.allowIncomplete = Boolean.parseBoolean(releaseProps.getProperty("release_aloow_incomplete")); } /** * Render message for the user. * @return formatted message; */ public String renderMessage() { return "Параметры выпуска:\n" + (this.channelRelease ? "Выпуск каналов разрешен: " + this.releaseProps.getProperty("release_chn_dir") + "\n" : "Выпуск каналов отключен\n") + (this.dayRelease ? "Выпуск по дням разрешен: " + this.releaseProps.getProperty("release_day_dir") + "\n" : "Выпуск по дням отключен\n") + (this.allowIncomplete ? "Неполный выпуск разрешен." : "Неполный выпуск запрещен!"); } /** * Iterate through channels and days and release them to the system. */ public void release() { if (!this.allowIncomplete && JTVProg.isPass()) { this.status = "Невозможно выпустить: пропущены каналы!"; return; } if (this.channelRelease) { - for (int chIndex = 1; chIndex < JTVProg.configer.ChannelProcessor.getSetSize(); chIndex++) { + for (int chIndex = 1; chIndex < JTVProg.configer.ChannelProcessor.getSetSize() + 1; chIndex++) { jtvprog.chProcSet.chProcUnit currChannel = JTVProg.configer.ChannelProcessor.getUnit(chIndex); if (!currChannel.isPassedNull) { String res = this.release(currChannel.chName, currChannel.chStored, this.releaseProps.getProperty("release_chn_dir")); if (res.contains("RIBBON_ERROR:")) { JTVProg.warningMessage("Ошибка выпуска канала " + currChannel.chName + "\n\nОтвет системы:\n" + Generic.CsvFormat.parseDoubleStruct(res)[1]); this.status = currChannel.chName + ": " + Generic.CsvFormat.parseDoubleStruct(res)[1]; return; } } + try { + Thread.sleep(100); + } catch (InterruptedException ex) {} } - try { - Thread.sleep(100); - } catch (InterruptedException ex) {} } } /** * Release message to the system (universal). * @param header header of the message; * @param content content of message; * @param dirs dirs to apply; */ private String release(String header, String content, String dirs) { MessageClasses.Message currMessage = new MessageClasses.Message(header, JTVProg.tvApp.CURR_LOGIN, "RU", dirs.replaceFirst("\\[", "").replaceFirst("\\]", "").split(","), new String[] {"телепрограмма", "выпуск"}, content ); String command; command = "RIBBON_POST_MESSAGE:-1," + Generic.CsvFormat.renderGroup(currMessage.DIRS) + "," + "RU" + ",{" + currMessage.HEADER + "}," + Generic.CsvFormat.renderGroup(currMessage.TAGS) + "," + Generic.CsvFormat.renderMessageProperties(currMessage.PROPERTIES) + "\n" + currMessage.CONTENT + "\nEND:"; return JTVProg.tvApp.appWorker.sendCommandWithReturn(command); } /** * Return status of releasing. * @return string or null; */ public String getStatus() { return this.status; } }
false
true
public void release() { if (!this.allowIncomplete && JTVProg.isPass()) { this.status = "Невозможно выпустить: пропущены каналы!"; return; } if (this.channelRelease) { for (int chIndex = 1; chIndex < JTVProg.configer.ChannelProcessor.getSetSize(); chIndex++) { jtvprog.chProcSet.chProcUnit currChannel = JTVProg.configer.ChannelProcessor.getUnit(chIndex); if (!currChannel.isPassedNull) { String res = this.release(currChannel.chName, currChannel.chStored, this.releaseProps.getProperty("release_chn_dir")); if (res.contains("RIBBON_ERROR:")) { JTVProg.warningMessage("Ошибка выпуска канала " + currChannel.chName + "\n\nОтвет системы:\n" + Generic.CsvFormat.parseDoubleStruct(res)[1]); this.status = currChannel.chName + ": " + Generic.CsvFormat.parseDoubleStruct(res)[1]; return; } } } try { Thread.sleep(100); } catch (InterruptedException ex) {} } }
public void release() { if (!this.allowIncomplete && JTVProg.isPass()) { this.status = "Невозможно выпустить: пропущены каналы!"; return; } if (this.channelRelease) { for (int chIndex = 1; chIndex < JTVProg.configer.ChannelProcessor.getSetSize() + 1; chIndex++) { jtvprog.chProcSet.chProcUnit currChannel = JTVProg.configer.ChannelProcessor.getUnit(chIndex); if (!currChannel.isPassedNull) { String res = this.release(currChannel.chName, currChannel.chStored, this.releaseProps.getProperty("release_chn_dir")); if (res.contains("RIBBON_ERROR:")) { JTVProg.warningMessage("Ошибка выпуска канала " + currChannel.chName + "\n\nОтвет системы:\n" + Generic.CsvFormat.parseDoubleStruct(res)[1]); this.status = currChannel.chName + ": " + Generic.CsvFormat.parseDoubleStruct(res)[1]; return; } } try { Thread.sleep(100); } catch (InterruptedException ex) {} } } }
diff --git a/acceptanceTests/src/test/java/org/mifos/test/acceptance/framework/savingsproduct/DefineNewSavingsProductPage.java b/acceptanceTests/src/test/java/org/mifos/test/acceptance/framework/savingsproduct/DefineNewSavingsProductPage.java index 7598c6a9b..85b4ffa50 100644 --- a/acceptanceTests/src/test/java/org/mifos/test/acceptance/framework/savingsproduct/DefineNewSavingsProductPage.java +++ b/acceptanceTests/src/test/java/org/mifos/test/acceptance/framework/savingsproduct/DefineNewSavingsProductPage.java @@ -1,66 +1,66 @@ /* * Copyright (c) 2005-2010 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.test.acceptance.framework.savingsproduct; import org.mifos.test.acceptance.framework.MifosPage; import com.thoughtworks.selenium.Selenium; public class DefineNewSavingsProductPage extends MifosPage { public DefineNewSavingsProductPage(Selenium selenium) { super(selenium); } public void verifyPage() { verifyPage("CreateSavingsProduct"); } public DefineNewSavingsProductPreviewPage submitAndNavigateToDefineNewSavingsProductPreviewPage(SavingsProductParameters productParameters) { selenium.type("CreateSavingsProduct.input.prdOfferingName", productParameters.getProductInstanceName()); selenium.type("CreateSavingsProduct.input.prdOfferingShortName", productParameters.getShortName()); selenium.type("startDateDD", productParameters.getStartDateDD()); selenium.type("startDateMM", productParameters.getStartDateMM()); selenium.type("startDateYY", productParameters.getStartDateYYYY()); - selectValueIfNotZero("savingsProduct.generalDetails.selectedCategory", productParameters.getProductCategory()); + selectValueIfNotZero("generalDetails.selectedCategory", productParameters.getProductCategory()); - selectValueIfNotZero("savingsProduct.generalDetails.selectedApplicableFor", productParameters.getApplicableFor()); - selectValueIfNotZero("savingsProduct.selectedDepositType", productParameters.getTypeOfDeposits()); - typeTextIfNotEmpty("savingsProduct.amountForDeposit", productParameters.getMandatoryAmount()); - selectValueIfNotZero("savingsProduct.selectedGroupSavingsApproach", productParameters.getAmountAppliesTo()); - selenium.type("savingsProduct.interestRate", productParameters.getInterestRate()); + selectValueIfNotZero("generalDetails.selectedApplicableFor", productParameters.getApplicableFor()); + selectValueIfNotZero("selectedDepositType", productParameters.getTypeOfDeposits()); + typeTextIfNotEmpty("amountForDeposit", productParameters.getMandatoryAmount()); + selectValueIfNotZero("selectedGroupSavingsApproach", productParameters.getAmountAppliesTo()); + selenium.type("interestRate", productParameters.getInterestRate()); - selectValueIfNotZero("savingsProduct.selectedInterestCalculation", productParameters.getBalanceUsedForInterestCalculation()); + selectValueIfNotZero("selectedInterestCalculation", productParameters.getBalanceUsedForInterestCalculation()); - selenium.type("savingsProduct.interestCalculationFrequency", productParameters.getNumberOfDaysOrMonthsForInterestCalculation()); - selectValueIfNotZero("savingsProduct.selectedFequencyPeriod", productParameters.getDaysOrMonthsForInterestCalculation()); + selenium.type("interestCalculationFrequency", productParameters.getNumberOfDaysOrMonthsForInterestCalculation()); + selectValueIfNotZero("selectedFequencyPeriod", productParameters.getDaysOrMonthsForInterestCalculation()); - selenium.type("savingsProduct.selectedFequencyPeriod", productParameters.getFrequencyOfInterestPostings()); + selenium.type("selectedFequencyPeriod", productParameters.getFrequencyOfInterestPostings()); - selectIfNotEmpty("savingsProduct.selectedPrincipalGlCode", productParameters.getGlCodeForDeposit()); - selectIfNotEmpty("savingsProduct.selectedInterestGlCode", productParameters.getGlCodeForInterest()); + selectIfNotEmpty("selectedPrincipalGlCode", productParameters.getGlCodeForDeposit()); + selectIfNotEmpty("selectedInterestGlCode", productParameters.getGlCodeForInterest()); selenium.click("CreateSavingsProduct.button.preview"); waitForPageToLoad(); return new DefineNewSavingsProductPreviewPage(selenium); } }
false
true
public DefineNewSavingsProductPreviewPage submitAndNavigateToDefineNewSavingsProductPreviewPage(SavingsProductParameters productParameters) { selenium.type("CreateSavingsProduct.input.prdOfferingName", productParameters.getProductInstanceName()); selenium.type("CreateSavingsProduct.input.prdOfferingShortName", productParameters.getShortName()); selenium.type("startDateDD", productParameters.getStartDateDD()); selenium.type("startDateMM", productParameters.getStartDateMM()); selenium.type("startDateYY", productParameters.getStartDateYYYY()); selectValueIfNotZero("savingsProduct.generalDetails.selectedCategory", productParameters.getProductCategory()); selectValueIfNotZero("savingsProduct.generalDetails.selectedApplicableFor", productParameters.getApplicableFor()); selectValueIfNotZero("savingsProduct.selectedDepositType", productParameters.getTypeOfDeposits()); typeTextIfNotEmpty("savingsProduct.amountForDeposit", productParameters.getMandatoryAmount()); selectValueIfNotZero("savingsProduct.selectedGroupSavingsApproach", productParameters.getAmountAppliesTo()); selenium.type("savingsProduct.interestRate", productParameters.getInterestRate()); selectValueIfNotZero("savingsProduct.selectedInterestCalculation", productParameters.getBalanceUsedForInterestCalculation()); selenium.type("savingsProduct.interestCalculationFrequency", productParameters.getNumberOfDaysOrMonthsForInterestCalculation()); selectValueIfNotZero("savingsProduct.selectedFequencyPeriod", productParameters.getDaysOrMonthsForInterestCalculation()); selenium.type("savingsProduct.selectedFequencyPeriod", productParameters.getFrequencyOfInterestPostings()); selectIfNotEmpty("savingsProduct.selectedPrincipalGlCode", productParameters.getGlCodeForDeposit()); selectIfNotEmpty("savingsProduct.selectedInterestGlCode", productParameters.getGlCodeForInterest()); selenium.click("CreateSavingsProduct.button.preview"); waitForPageToLoad(); return new DefineNewSavingsProductPreviewPage(selenium); }
public DefineNewSavingsProductPreviewPage submitAndNavigateToDefineNewSavingsProductPreviewPage(SavingsProductParameters productParameters) { selenium.type("CreateSavingsProduct.input.prdOfferingName", productParameters.getProductInstanceName()); selenium.type("CreateSavingsProduct.input.prdOfferingShortName", productParameters.getShortName()); selenium.type("startDateDD", productParameters.getStartDateDD()); selenium.type("startDateMM", productParameters.getStartDateMM()); selenium.type("startDateYY", productParameters.getStartDateYYYY()); selectValueIfNotZero("generalDetails.selectedCategory", productParameters.getProductCategory()); selectValueIfNotZero("generalDetails.selectedApplicableFor", productParameters.getApplicableFor()); selectValueIfNotZero("selectedDepositType", productParameters.getTypeOfDeposits()); typeTextIfNotEmpty("amountForDeposit", productParameters.getMandatoryAmount()); selectValueIfNotZero("selectedGroupSavingsApproach", productParameters.getAmountAppliesTo()); selenium.type("interestRate", productParameters.getInterestRate()); selectValueIfNotZero("selectedInterestCalculation", productParameters.getBalanceUsedForInterestCalculation()); selenium.type("interestCalculationFrequency", productParameters.getNumberOfDaysOrMonthsForInterestCalculation()); selectValueIfNotZero("selectedFequencyPeriod", productParameters.getDaysOrMonthsForInterestCalculation()); selenium.type("selectedFequencyPeriod", productParameters.getFrequencyOfInterestPostings()); selectIfNotEmpty("selectedPrincipalGlCode", productParameters.getGlCodeForDeposit()); selectIfNotEmpty("selectedInterestGlCode", productParameters.getGlCodeForInterest()); selenium.click("CreateSavingsProduct.button.preview"); waitForPageToLoad(); return new DefineNewSavingsProductPreviewPage(selenium); }
diff --git a/src/com/kurento/kas/mscontrol/networkconnection/internal/NetworkConnectionImpl.java b/src/com/kurento/kas/mscontrol/networkconnection/internal/NetworkConnectionImpl.java index 74d480b..3512c1b 100644 --- a/src/com/kurento/kas/mscontrol/networkconnection/internal/NetworkConnectionImpl.java +++ b/src/com/kurento/kas/mscontrol/networkconnection/internal/NetworkConnectionImpl.java @@ -1,286 +1,286 @@ package com.kurento.kas.mscontrol.networkconnection.internal; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import java.util.Vector; import javax.sdp.SdpException; import android.util.Log; import com.kurento.commons.media.format.MediaSpec; import com.kurento.commons.media.format.PayloadSpec; import com.kurento.commons.media.format.SessionSpec; import com.kurento.commons.mscontrol.MsControlException; import com.kurento.commons.mscontrol.join.JoinableStream.StreamType; import com.kurento.commons.sdp.enums.MediaType; import com.kurento.commons.sdp.enums.Mode; import com.kurento.kas.media.AudioCodecType; import com.kurento.kas.media.MediaPortManager; import com.kurento.kas.media.VideoCodecType; import com.kurento.kas.media.profiles.AudioProfile; import com.kurento.kas.media.profiles.VideoProfile; import com.kurento.kas.mscontrol.internal.MediaSessionConfig; import com.kurento.kas.mscontrol.join.AudioJoinableStreamImpl; import com.kurento.kas.mscontrol.join.JoinableStreamBase; import com.kurento.kas.mscontrol.join.VideoJoinableStreamImpl; import com.kurento.kas.mscontrol.networkconnection.NetIF; /** * * @author mparis * */ public class NetworkConnectionImpl extends NetworkConnectionBase { private static final long serialVersionUID = 1L; public final static String LOG_TAG = "NW"; private MediaSessionConfig mediaSessionConfig; private ArrayList<AudioProfile> audioProfiles; private ArrayList<VideoProfile> videoProfiles; private SessionSpec localSessionSpec; private SessionSpec remoteSessionSpec; private static int videoPort = -1; private static int audioPort = -1; private VideoJoinableStreamImpl videoJoinableStreamImpl; private AudioJoinableStreamImpl audioJoinableStreamImpl; @Override public void setLocalSessionSpec(SessionSpec arg0) { this.localSessionSpec = arg0; Log.d(LOG_TAG, "localSessionSpec:\n" + localSessionSpec); } @Override public void setRemoteSessionSpec(SessionSpec arg0) { this.remoteSessionSpec = arg0; Log.d(LOG_TAG, "remoteSessionSpec:\n" + remoteSessionSpec); } public NetworkConnectionImpl(MediaSessionConfig mediaSessionConfig) throws MsControlException { super(); if (mediaSessionConfig == null) throw new MsControlException("Media Session Config is NULL"); this.streams = new JoinableStreamBase[2]; this.mediaSessionConfig = mediaSessionConfig; // Process MediaConfigure and determinate media profiles audioProfiles = getAudioProfiles(this.mediaSessionConfig); videoProfiles = getVideoProfiles(this.mediaSessionConfig); if (videoPort == -1) videoPort = MediaPortManager.takeVideoLocalPort(); if (audioPort == -1) audioPort = MediaPortManager.takeAudioLocalPort(); } @Override public void confirm() throws MsControlException { if ((localSessionSpec == null) || (remoteSessionSpec == null)) return; // TODO: throw some Exception eg: throw new // MediaException("SessionSpec corrupt"); audioJoinableStreamImpl = new AudioJoinableStreamImpl(this, StreamType.audio, remoteSessionSpec, localSessionSpec); this.streams[0] = audioJoinableStreamImpl; videoJoinableStreamImpl = new VideoJoinableStreamImpl(this, StreamType.video, remoteSessionSpec, localSessionSpec, mediaSessionConfig.getFramesQueueSize()); this.streams[1] = videoJoinableStreamImpl; } @Override public void release() { if (videoJoinableStreamImpl != null) videoJoinableStreamImpl.stop(); if (audioJoinableStreamImpl != null) audioJoinableStreamImpl.stop(); // MediaPortManager.releaseAudioLocalPort(); // MediaPortManager.releaseVideoLocalPort(); } private void addPayloadSpec(List<PayloadSpec> videoList, String payloadStr, MediaType mediaType, int port) { try { PayloadSpec payload = new PayloadSpec(payloadStr); payload.setMediaType(mediaType); payload.setPort(port); videoList.add(payload); } catch (SdpException e) { e.printStackTrace(); } } @Override public SessionSpec generateSessionSpec() { int payload = 96; // VIDEO MediaSpec videoMedia = null; if (videoProfiles != null && videoProfiles.size() > 0) { List<PayloadSpec> videoList = new Vector<PayloadSpec>(); for (VideoProfile vp : videoProfiles) { if (VideoProfile.MPEG4.equals(vp)) addPayloadSpec(videoList, payload + " MP4V-ES/90000", MediaType.VIDEO, videoPort); else if (VideoProfile.H263.equals(vp)) addPayloadSpec(videoList, payload + " H263-1998/90000", MediaType.VIDEO, videoPort); payload++; } videoMedia = new MediaSpec(); videoMedia.setPayloadList(videoList); Mode videoMode = this.mediaSessionConfig.getMediaTypeModes().get( MediaType.VIDEO); videoMedia.setMode(videoMode); } // // AUDIO MediaSpec audioMedia = null; if (audioProfiles != null && audioProfiles.size() > 0) { List<PayloadSpec> audioList = new Vector<PayloadSpec>(); for (AudioProfile ap : audioProfiles) { if (AudioProfile.MP2.equals(ap)) { PayloadSpec payloadAudioMP2 = new PayloadSpec(); payloadAudioMP2.setMediaType(MediaType.AUDIO); payloadAudioMP2.setPort(audioPort); payloadAudioMP2.setPayload(14); audioList.add(payloadAudioMP2); } else if (AudioProfile.AMR.equals(ap)) { PayloadSpec audioPayloadAMR = null; try { - audioPayloadAMR = new PayloadSpec("100 AMR/8000/1"); + audioPayloadAMR = new PayloadSpec(payload + " AMR/8000/1"); audioPayloadAMR.setFormatParams("octet-align=1"); audioPayloadAMR.setMediaType(MediaType.AUDIO); audioPayloadAMR.setPort(audioPort); } catch (SdpException e) { e.printStackTrace(); } audioList.add(audioPayloadAMR); } payload++; } audioMedia = new MediaSpec(); audioMedia.setPayloadList(audioList); Mode audioMode = this.mediaSessionConfig.getMediaTypeModes().get( MediaType.AUDIO); audioMedia.setMode(audioMode); } List<MediaSpec> mediaList = new Vector<MediaSpec>(); if (videoMedia != null) mediaList.add(videoMedia); if (audioMedia != null) mediaList.add(audioMedia); SessionSpec session = new SessionSpec(); session.setMediaSpec(mediaList); session.setOriginAddress(getLocalAddress().getHostAddress().toString()); session.setRemoteHandler("0.0.0.0"); session.setSessionName("TestSession"); return session; } @Override public InetAddress getLocalAddress() { return this.mediaSessionConfig.getLocalAddress(); } private ArrayList<AudioProfile> getAudioProfiles( MediaSessionConfig mediaSessionConfig) { ArrayList<AudioCodecType> audioCodecs = mediaSessionConfig .getAudioCodecs(); if (audioCodecs == null) return null; ArrayList<AudioProfile> audioProfiles = new ArrayList<AudioProfile>(0); // Discard/Select phase for (AudioProfile ap : AudioProfile.values()) { for (AudioCodecType act : audioCodecs) { if (act.equals(ap.getAudioCodecType())) audioProfiles.add(ap); } } // Scoring phase // TODO return audioProfiles; } private ArrayList<VideoProfile> getVideoProfiles( MediaSessionConfig mediaSessionConfig) { ArrayList<VideoCodecType> videoCodecs = mediaSessionConfig .getVideoCodecs(); if (videoCodecs == null) return null; ArrayList<VideoProfile> videoProfiles = new ArrayList<VideoProfile>(0); // Discard/Select phase for (VideoProfile vp : VideoProfile.values()) { for (VideoCodecType vct : videoCodecs) { if (vct.equals(vp.getVideoCodecType())) videoProfiles.add(vp); } } // Set new attrs Integer maxBW = null; if (mediaSessionConfig.getMaxBW() != null) maxBW = Math.max(NetIF.MIN_BANDWITH, Math.min(mediaSessionConfig .getNetIF().getMaxBandwidth(), mediaSessionConfig .getMaxBW())); Integer maxFrameRate = null; if (mediaSessionConfig.getMaxFrameRate() != null) maxFrameRate = Math.max(1, mediaSessionConfig.getMaxFrameRate()); Integer maxGopSize = null; if (mediaSessionConfig.getGopSize() != null) maxGopSize = Math.max(0, mediaSessionConfig.getGopSize()); Integer width = null; Integer height = null; if (mediaSessionConfig.getFrameSize() != null) { width = Math .abs((int) mediaSessionConfig.getFrameSize().getWidth()); height = Math.abs((int) mediaSessionConfig.getFrameSize() .getHeight()); } for (VideoProfile vp : videoProfiles) { if (maxBW != null) vp.setBitRate(maxBW); if (maxFrameRate != null) vp.setFrameRate(maxFrameRate); if (maxGopSize != null) vp.setGopSize(maxGopSize); if (width != null) vp.setWidth(width); if (height != null) vp.setHeight(height); } // Scoring phase // TODO return videoProfiles; } }
true
true
public SessionSpec generateSessionSpec() { int payload = 96; // VIDEO MediaSpec videoMedia = null; if (videoProfiles != null && videoProfiles.size() > 0) { List<PayloadSpec> videoList = new Vector<PayloadSpec>(); for (VideoProfile vp : videoProfiles) { if (VideoProfile.MPEG4.equals(vp)) addPayloadSpec(videoList, payload + " MP4V-ES/90000", MediaType.VIDEO, videoPort); else if (VideoProfile.H263.equals(vp)) addPayloadSpec(videoList, payload + " H263-1998/90000", MediaType.VIDEO, videoPort); payload++; } videoMedia = new MediaSpec(); videoMedia.setPayloadList(videoList); Mode videoMode = this.mediaSessionConfig.getMediaTypeModes().get( MediaType.VIDEO); videoMedia.setMode(videoMode); } // // AUDIO MediaSpec audioMedia = null; if (audioProfiles != null && audioProfiles.size() > 0) { List<PayloadSpec> audioList = new Vector<PayloadSpec>(); for (AudioProfile ap : audioProfiles) { if (AudioProfile.MP2.equals(ap)) { PayloadSpec payloadAudioMP2 = new PayloadSpec(); payloadAudioMP2.setMediaType(MediaType.AUDIO); payloadAudioMP2.setPort(audioPort); payloadAudioMP2.setPayload(14); audioList.add(payloadAudioMP2); } else if (AudioProfile.AMR.equals(ap)) { PayloadSpec audioPayloadAMR = null; try { audioPayloadAMR = new PayloadSpec("100 AMR/8000/1"); audioPayloadAMR.setFormatParams("octet-align=1"); audioPayloadAMR.setMediaType(MediaType.AUDIO); audioPayloadAMR.setPort(audioPort); } catch (SdpException e) { e.printStackTrace(); } audioList.add(audioPayloadAMR); } payload++; } audioMedia = new MediaSpec(); audioMedia.setPayloadList(audioList); Mode audioMode = this.mediaSessionConfig.getMediaTypeModes().get( MediaType.AUDIO); audioMedia.setMode(audioMode); } List<MediaSpec> mediaList = new Vector<MediaSpec>(); if (videoMedia != null) mediaList.add(videoMedia); if (audioMedia != null) mediaList.add(audioMedia); SessionSpec session = new SessionSpec(); session.setMediaSpec(mediaList); session.setOriginAddress(getLocalAddress().getHostAddress().toString()); session.setRemoteHandler("0.0.0.0"); session.setSessionName("TestSession"); return session; }
public SessionSpec generateSessionSpec() { int payload = 96; // VIDEO MediaSpec videoMedia = null; if (videoProfiles != null && videoProfiles.size() > 0) { List<PayloadSpec> videoList = new Vector<PayloadSpec>(); for (VideoProfile vp : videoProfiles) { if (VideoProfile.MPEG4.equals(vp)) addPayloadSpec(videoList, payload + " MP4V-ES/90000", MediaType.VIDEO, videoPort); else if (VideoProfile.H263.equals(vp)) addPayloadSpec(videoList, payload + " H263-1998/90000", MediaType.VIDEO, videoPort); payload++; } videoMedia = new MediaSpec(); videoMedia.setPayloadList(videoList); Mode videoMode = this.mediaSessionConfig.getMediaTypeModes().get( MediaType.VIDEO); videoMedia.setMode(videoMode); } // // AUDIO MediaSpec audioMedia = null; if (audioProfiles != null && audioProfiles.size() > 0) { List<PayloadSpec> audioList = new Vector<PayloadSpec>(); for (AudioProfile ap : audioProfiles) { if (AudioProfile.MP2.equals(ap)) { PayloadSpec payloadAudioMP2 = new PayloadSpec(); payloadAudioMP2.setMediaType(MediaType.AUDIO); payloadAudioMP2.setPort(audioPort); payloadAudioMP2.setPayload(14); audioList.add(payloadAudioMP2); } else if (AudioProfile.AMR.equals(ap)) { PayloadSpec audioPayloadAMR = null; try { audioPayloadAMR = new PayloadSpec(payload + " AMR/8000/1"); audioPayloadAMR.setFormatParams("octet-align=1"); audioPayloadAMR.setMediaType(MediaType.AUDIO); audioPayloadAMR.setPort(audioPort); } catch (SdpException e) { e.printStackTrace(); } audioList.add(audioPayloadAMR); } payload++; } audioMedia = new MediaSpec(); audioMedia.setPayloadList(audioList); Mode audioMode = this.mediaSessionConfig.getMediaTypeModes().get( MediaType.AUDIO); audioMedia.setMode(audioMode); } List<MediaSpec> mediaList = new Vector<MediaSpec>(); if (videoMedia != null) mediaList.add(videoMedia); if (audioMedia != null) mediaList.add(audioMedia); SessionSpec session = new SessionSpec(); session.setMediaSpec(mediaList); session.setOriginAddress(getLocalAddress().getHostAddress().toString()); session.setRemoteHandler("0.0.0.0"); session.setSessionName("TestSession"); return session; }
diff --git a/activemq-cpp-openwire-generator/src/main/java/org/apache/activemq/openwire/tool/marshallers/AmqCppMarshallingHeadersGenerator.java b/activemq-cpp-openwire-generator/src/main/java/org/apache/activemq/openwire/tool/marshallers/AmqCppMarshallingHeadersGenerator.java index af0ad9d2..fc49a64c 100644 --- a/activemq-cpp-openwire-generator/src/main/java/org/apache/activemq/openwire/tool/marshallers/AmqCppMarshallingHeadersGenerator.java +++ b/activemq-cpp-openwire-generator/src/main/java/org/apache/activemq/openwire/tool/marshallers/AmqCppMarshallingHeadersGenerator.java @@ -1,348 +1,348 @@ /** * * 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.openwire.tool.marshallers; import java.io.File; import java.io.PrintWriter; import org.apache.activemq.openwire.tool.JavaMarshallingGenerator; import org.codehaus.jam.JClass; /** * * @version $Revision: 381410 $ */ public class AmqCppMarshallingHeadersGenerator extends JavaMarshallingGenerator { protected String targetDir="./src/main"; public Object run() { filePostFix = getFilePostFix(); if (destDir == null) { destDir = new File(targetDir+"/activemq/wireformat/openwire/marshal/v"+getOpenwireVersion()); } return super.run(); } protected void processClass(JClass jclass) { super.processClass( jclass ); } protected String getBaseClassName(JClass jclass) { String answer = jclass.getSimpleName(); if( answer.equals("ActiveMQTextMessage") ) { answer = "MessageMarshaller"; } else if( answer.equals("ActiveMQBytesMessage") ) { answer = "MessageMarshaller"; } else if( answer.equals("ActiveMQMapMessage") ) { answer = "MessageMarshaller"; } else if( answer.equals("ActiveMQObjectMessage") ) { answer = "MessageMarshaller"; } else if( answer.equals("ActiveMQStreamMessage") ) { answer = "MessageMarshaller"; } else if( answer.equals("ActiveMQBlobMessage") ) { answer = "MessageMarshaller"; } // We didn't map it, so let the base class handle it. if( answer.equals( jclass.getSimpleName() ) ) { answer = super.getBaseClassName(jclass); } return answer; } public boolean isMarshallAware(JClass j) { String answer = jclass.getSimpleName(); if( answer.equals("ActiveMQTextMessage") ) { return true; } else if( answer.equals("ActiveMQBytesMessage") ) { return true; } else if( answer.equals("ActiveMQMapMessage") ) { return true; } else if( answer.equals("ActiveMQObjectMessage") ) { return true; } else if( answer.equals("ActiveMQStreamMessage") ) { return true; } else if( answer.equals("ActiveMBlobMessage") ) { return true; } else { return super.isMarshallAware(jclass); } } protected String getFilePostFix() { return ".h"; } public String toCppType(JClass type) { String name = type.getSimpleName(); if (name.equals("String")) { return "std::string"; } else if( type.isArrayType() ) { if( name.equals( "byte[]" ) ) name = "unsigned char[]"; JClass arrayClass = type.getArrayComponentType(); if( arrayClass.isPrimitiveType() ) { return "std::vector<" + name.substring(0, name.length()-2) + ">"; } else { return "std::vector<" + name.substring(0, name.length()-2) + "*>"; } } else if( name.equals( "Throwable" ) || name.equals( "Exception" ) ) { return "BrokerError"; } else if( name.equals("BaseDataStructure" ) ){ return "DataStructure"; } else if( name.equals("ByteSequence") ) { return "std::vector<char>"; } else if( name.equals("boolean") ) { return "bool"; } else if( name.equals("long") ) { return "long long"; } else if( name.equals("byte") ) { return "unsigned char"; } else if( !type.isPrimitiveType() ) { return name; } else { return name; } } protected void generateLicence(PrintWriter out) { out.println("/*"); out.println(" * Licensed to the Apache Software Foundation (ASF) under one or more"); out.println(" * contributor license agreements. See the NOTICE file distributed with"); out.println(" * this work for additional information regarding copyright ownership."); out.println(" * The ASF licenses this file to You under the Apache License, Version 2.0"); out.println(" * (the \"License\"); you may not use this file except in compliance with"); out.println(" * the License. You may obtain a copy of the License at"); out.println(" *"); out.println(" * http://www.apache.org/licenses/LICENSE-2.0"); out.println(" *"); out.println(" * Unless required by applicable law or agreed to in writing, software"); out.println(" * distributed under the License is distributed on an \"AS IS\" BASIS,"); out.println(" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied."); out.println(" * See the License for the specific language governing permissions and"); out.println(" * limitations under the License."); out.println(" */"); } protected void generateFile(PrintWriter out) throws Exception { generateLicence(out); out.println(""); out.println("#ifndef _ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSAHAL_V"+getOpenwireVersion()+"_"+className.toUpperCase()+"_H_"); out.println("#define _ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSAHAL_V"+getOpenwireVersion()+"_"+className.toUpperCase()+"_H_"); out.println(""); out.println("// Turn off warning message for ignored exception specification"); out.println("#ifdef _MSC_VER"); out.println("#pragma warning( disable : 4290 )"); out.println("#endif"); out.println(""); if( baseClass.equals("BaseDataStreamMarshaller") ) { out.println("#include <activemq/wireformat/openwire/marshal/"+baseClass+".h>"); } else { out.println("#include <activemq/wireformat/openwire/marshal/v"+getOpenwireVersion()+"/"+baseClass+".h>"); } out.println(""); out.println("#include <decaf/io/DataInputStream.h>"); out.println("#include <decaf/io/DataOutputStream.h>"); out.println("#include <decaf/io/IOException.h>"); out.println("#include <activemq/util/Config.h>"); out.println("#include <activemq/commands/DataStructure.h>"); out.println("#include <activemq/wireformat/openwire/OpenWireFormat.h>"); out.println("#include <activemq/wireformat/openwire/utils/BooleanStream.h>"); out.println(""); out.println("namespace activemq{"); out.println("namespace wireformat{"); out.println("namespace openwire{"); out.println("namespace marshal{"); out.println("namespace v"+getOpenwireVersion()+"{"); out.println(""); out.println(" /**"); out.println(" * Marshaling code for Open Wire Format for "+className); out.println(" *"); out.println(" * NOTE!: This file is auto generated - do not modify!"); out.println(" * if you need to make a change, please see the Java Classes"); out.println(" * in the activemq-openwire-generator module"); out.println(" */"); out.println(" class AMQCPP_API "+className+" : public "+baseClass+" {"); out.println(" public:"); out.println(""); out.println(" "+className+"() {}"); out.println(" virtual ~"+className+"() {}"); out.println(""); if( !isAbstractClass() ) { out.println(" /**"); out.println(" * Creates a new instance of this marshalable type."); out.println(" *"); out.println(" * @return new DataStructure object pointer caller owns it."); out.println(" */"); out.println(" virtual commands::DataStructure* createObject() const;"); out.println(""); out.println(" /**"); out.println(" * Get the Data Structure Type that identifies this Marshaler"); out.println(" *"); out.println(" * @return byte holding the data structure type value"); out.println(" */"); out.println(" virtual unsigned char getDataStructureType() const;"); out.println(""); } out.println(" /**"); -out.println(" * Un-marshal an object instance from the data input stream"); +out.println(" * Un-marshal an object instance from the data input stream."); out.println(" *"); -out.println(" * @param wireFormat - describes the wire format of the broker"); -out.println(" * @param dataStructure - Object to be un-marshaled"); -out.println(" * @param dataIn - BinaryReader that provides that data"); -out.println(" * @param bs - BooleanStream"); +out.println(" * @param wireFormat - describes the wire format of the broker."); +out.println(" * @param dataStructure - Object to be un-marshaled."); +out.println(" * @param dataIn - BinaryReader that provides that data."); +out.println(" * @param bs - BooleanStream stream used to unpack bits from the wire."); out.println(" *"); out.println(" * @throws IOException if an error occurs during the unmarshal."); out.println(" */"); out.println(" virtual void tightUnmarshal( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataInputStream* dataIn,"); out.println(" utils::BooleanStream* bs ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Write the booleans that this object uses to a BooleanStream"); out.println(" *"); out.println(" * @param wireFormat - describes the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); -out.println(" * @param bs - BooleanStream"); +out.println(" * @param bs - BooleanStream stream used to pack bits from the wire."); out.println(" * @returns int value indicating the size of the marshaled object."); out.println(" *"); out.println(" * @throws IOException if an error occurs during the marshal."); out.println(" */"); out.println(" virtual int tightMarshal1( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" utils::BooleanStream* bs ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Write a object instance to data output stream"); out.println(" *"); out.println(" * @param wireFormat - describes the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); out.println(" * @param dataOut - BinaryReader that provides that data sink"); -out.println(" * @param bs - BooleanStream"); +out.println(" * @param bs - BooleanStream stream used to pack bits from the wire."); out.println(" *"); out.println(" * @throws IOException if an error occurs during the marshal."); out.println(" */"); out.println(" virtual void tightMarshal2( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataOutputStream* dataOut,"); out.println(" utils::BooleanStream* bs ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Un-marshal an object instance from the data input stream"); out.println(" *"); out.println(" * @param wireFormat - describes the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); out.println(" * @param dataIn - BinaryReader that provides that data source"); out.println(" *"); out.println(" * @throws IOException if an error occurs during the unmarshal."); out.println(" */"); out.println(" virtual void looseUnmarshal( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataInputStream* dataIn ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Write a object instance to data output stream"); out.println(" *"); out.println(" * @param wireFormat - describs the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); out.println(" * @param dataOut - BinaryWriter that provides that data sink"); out.println(" *"); out.println(" * @throws IOException if an error occurs during the marshal."); out.println(" */"); out.println(" virtual void looseMarshal( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataOutputStream* dataOut ) throw( decaf::io::IOException );"); out.println(""); out.println(" };"); out.println(""); out.println("}}}}}"); out.println(""); out.println("#endif /*_ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSAHAL_V"+getOpenwireVersion()+"_"+className.toUpperCase()+"_H_*/"); out.println(""); } public void generateFactory(PrintWriter out) { generateLicence(out); out.println("#ifndef _ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSAHAL_V"+getOpenwireVersion()+"_MARSHALERFACTORY_H_"); out.println("#define _ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSAHAL_V"+getOpenwireVersion()+"_MARSHALERFACTORY_H_"); out.println(""); out.println("// Turn off warning message for ignored exception specification"); out.println("#ifdef _MSC_VER"); out.println("#pragma warning( disable : 4290 )"); out.println("#endif"); out.println(""); out.println("#include <activemq/wireformat/openwire/OpenWireFormat.h>"); out.println(""); out.println("namespace activemq{"); out.println("namespace wireformat{"); out.println("namespace openwire{"); out.println("namespace marshal{"); out.println("namespace v"+getOpenwireVersion()+"{"); out.println(""); out.println(" /**"); out.println(" * Used to create marshallers for a specific version of the wire"); out.println(" * protocol."); out.println(" *"); out.println(" * NOTE!: This file is auto generated - do not modify!"); out.println(" * if you need to make a change, please see the Groovy scripts"); out.println(" * in the activemq-openwire-generator module"); out.println(" */"); out.println(" class MarshallerFactory {"); out.println(" public:"); out.println(""); out.println(" virtual ~MarshallerFactory() {};"); out.println(""); out.println(" virtual void configure( OpenWireFormat* format );"); out.println(""); out.println(" };"); out.println(""); out.println("}}}}}"); out.println(""); out.println("#endif /*_ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSHAL_V"+getOpenwireVersion()+"_MARSHALLERFACTORY_H_*/"); } public String getTargetDir() { return targetDir; } public void setTargetDir(String targetDir) { this.targetDir = targetDir; } }
false
true
protected void generateFile(PrintWriter out) throws Exception { generateLicence(out); out.println(""); out.println("#ifndef _ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSAHAL_V"+getOpenwireVersion()+"_"+className.toUpperCase()+"_H_"); out.println("#define _ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSAHAL_V"+getOpenwireVersion()+"_"+className.toUpperCase()+"_H_"); out.println(""); out.println("// Turn off warning message for ignored exception specification"); out.println("#ifdef _MSC_VER"); out.println("#pragma warning( disable : 4290 )"); out.println("#endif"); out.println(""); if( baseClass.equals("BaseDataStreamMarshaller") ) { out.println("#include <activemq/wireformat/openwire/marshal/"+baseClass+".h>"); } else { out.println("#include <activemq/wireformat/openwire/marshal/v"+getOpenwireVersion()+"/"+baseClass+".h>"); } out.println(""); out.println("#include <decaf/io/DataInputStream.h>"); out.println("#include <decaf/io/DataOutputStream.h>"); out.println("#include <decaf/io/IOException.h>"); out.println("#include <activemq/util/Config.h>"); out.println("#include <activemq/commands/DataStructure.h>"); out.println("#include <activemq/wireformat/openwire/OpenWireFormat.h>"); out.println("#include <activemq/wireformat/openwire/utils/BooleanStream.h>"); out.println(""); out.println("namespace activemq{"); out.println("namespace wireformat{"); out.println("namespace openwire{"); out.println("namespace marshal{"); out.println("namespace v"+getOpenwireVersion()+"{"); out.println(""); out.println(" /**"); out.println(" * Marshaling code for Open Wire Format for "+className); out.println(" *"); out.println(" * NOTE!: This file is auto generated - do not modify!"); out.println(" * if you need to make a change, please see the Java Classes"); out.println(" * in the activemq-openwire-generator module"); out.println(" */"); out.println(" class AMQCPP_API "+className+" : public "+baseClass+" {"); out.println(" public:"); out.println(""); out.println(" "+className+"() {}"); out.println(" virtual ~"+className+"() {}"); out.println(""); if( !isAbstractClass() ) { out.println(" /**"); out.println(" * Creates a new instance of this marshalable type."); out.println(" *"); out.println(" * @return new DataStructure object pointer caller owns it."); out.println(" */"); out.println(" virtual commands::DataStructure* createObject() const;"); out.println(""); out.println(" /**"); out.println(" * Get the Data Structure Type that identifies this Marshaler"); out.println(" *"); out.println(" * @return byte holding the data structure type value"); out.println(" */"); out.println(" virtual unsigned char getDataStructureType() const;"); out.println(""); } out.println(" /**"); out.println(" * Un-marshal an object instance from the data input stream"); out.println(" *"); out.println(" * @param wireFormat - describes the wire format of the broker"); out.println(" * @param dataStructure - Object to be un-marshaled"); out.println(" * @param dataIn - BinaryReader that provides that data"); out.println(" * @param bs - BooleanStream"); out.println(" *"); out.println(" * @throws IOException if an error occurs during the unmarshal."); out.println(" */"); out.println(" virtual void tightUnmarshal( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataInputStream* dataIn,"); out.println(" utils::BooleanStream* bs ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Write the booleans that this object uses to a BooleanStream"); out.println(" *"); out.println(" * @param wireFormat - describes the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); out.println(" * @param bs - BooleanStream"); out.println(" * @returns int value indicating the size of the marshaled object."); out.println(" *"); out.println(" * @throws IOException if an error occurs during the marshal."); out.println(" */"); out.println(" virtual int tightMarshal1( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" utils::BooleanStream* bs ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Write a object instance to data output stream"); out.println(" *"); out.println(" * @param wireFormat - describes the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); out.println(" * @param dataOut - BinaryReader that provides that data sink"); out.println(" * @param bs - BooleanStream"); out.println(" *"); out.println(" * @throws IOException if an error occurs during the marshal."); out.println(" */"); out.println(" virtual void tightMarshal2( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataOutputStream* dataOut,"); out.println(" utils::BooleanStream* bs ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Un-marshal an object instance from the data input stream"); out.println(" *"); out.println(" * @param wireFormat - describes the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); out.println(" * @param dataIn - BinaryReader that provides that data source"); out.println(" *"); out.println(" * @throws IOException if an error occurs during the unmarshal."); out.println(" */"); out.println(" virtual void looseUnmarshal( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataInputStream* dataIn ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Write a object instance to data output stream"); out.println(" *"); out.println(" * @param wireFormat - describs the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); out.println(" * @param dataOut - BinaryWriter that provides that data sink"); out.println(" *"); out.println(" * @throws IOException if an error occurs during the marshal."); out.println(" */"); out.println(" virtual void looseMarshal( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataOutputStream* dataOut ) throw( decaf::io::IOException );"); out.println(""); out.println(" };"); out.println(""); out.println("}}}}}"); out.println(""); out.println("#endif /*_ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSAHAL_V"+getOpenwireVersion()+"_"+className.toUpperCase()+"_H_*/"); out.println(""); }
protected void generateFile(PrintWriter out) throws Exception { generateLicence(out); out.println(""); out.println("#ifndef _ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSAHAL_V"+getOpenwireVersion()+"_"+className.toUpperCase()+"_H_"); out.println("#define _ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSAHAL_V"+getOpenwireVersion()+"_"+className.toUpperCase()+"_H_"); out.println(""); out.println("// Turn off warning message for ignored exception specification"); out.println("#ifdef _MSC_VER"); out.println("#pragma warning( disable : 4290 )"); out.println("#endif"); out.println(""); if( baseClass.equals("BaseDataStreamMarshaller") ) { out.println("#include <activemq/wireformat/openwire/marshal/"+baseClass+".h>"); } else { out.println("#include <activemq/wireformat/openwire/marshal/v"+getOpenwireVersion()+"/"+baseClass+".h>"); } out.println(""); out.println("#include <decaf/io/DataInputStream.h>"); out.println("#include <decaf/io/DataOutputStream.h>"); out.println("#include <decaf/io/IOException.h>"); out.println("#include <activemq/util/Config.h>"); out.println("#include <activemq/commands/DataStructure.h>"); out.println("#include <activemq/wireformat/openwire/OpenWireFormat.h>"); out.println("#include <activemq/wireformat/openwire/utils/BooleanStream.h>"); out.println(""); out.println("namespace activemq{"); out.println("namespace wireformat{"); out.println("namespace openwire{"); out.println("namespace marshal{"); out.println("namespace v"+getOpenwireVersion()+"{"); out.println(""); out.println(" /**"); out.println(" * Marshaling code for Open Wire Format for "+className); out.println(" *"); out.println(" * NOTE!: This file is auto generated - do not modify!"); out.println(" * if you need to make a change, please see the Java Classes"); out.println(" * in the activemq-openwire-generator module"); out.println(" */"); out.println(" class AMQCPP_API "+className+" : public "+baseClass+" {"); out.println(" public:"); out.println(""); out.println(" "+className+"() {}"); out.println(" virtual ~"+className+"() {}"); out.println(""); if( !isAbstractClass() ) { out.println(" /**"); out.println(" * Creates a new instance of this marshalable type."); out.println(" *"); out.println(" * @return new DataStructure object pointer caller owns it."); out.println(" */"); out.println(" virtual commands::DataStructure* createObject() const;"); out.println(""); out.println(" /**"); out.println(" * Get the Data Structure Type that identifies this Marshaler"); out.println(" *"); out.println(" * @return byte holding the data structure type value"); out.println(" */"); out.println(" virtual unsigned char getDataStructureType() const;"); out.println(""); } out.println(" /**"); out.println(" * Un-marshal an object instance from the data input stream."); out.println(" *"); out.println(" * @param wireFormat - describes the wire format of the broker."); out.println(" * @param dataStructure - Object to be un-marshaled."); out.println(" * @param dataIn - BinaryReader that provides that data."); out.println(" * @param bs - BooleanStream stream used to unpack bits from the wire."); out.println(" *"); out.println(" * @throws IOException if an error occurs during the unmarshal."); out.println(" */"); out.println(" virtual void tightUnmarshal( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataInputStream* dataIn,"); out.println(" utils::BooleanStream* bs ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Write the booleans that this object uses to a BooleanStream"); out.println(" *"); out.println(" * @param wireFormat - describes the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); out.println(" * @param bs - BooleanStream stream used to pack bits from the wire."); out.println(" * @returns int value indicating the size of the marshaled object."); out.println(" *"); out.println(" * @throws IOException if an error occurs during the marshal."); out.println(" */"); out.println(" virtual int tightMarshal1( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" utils::BooleanStream* bs ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Write a object instance to data output stream"); out.println(" *"); out.println(" * @param wireFormat - describes the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); out.println(" * @param dataOut - BinaryReader that provides that data sink"); out.println(" * @param bs - BooleanStream stream used to pack bits from the wire."); out.println(" *"); out.println(" * @throws IOException if an error occurs during the marshal."); out.println(" */"); out.println(" virtual void tightMarshal2( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataOutputStream* dataOut,"); out.println(" utils::BooleanStream* bs ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Un-marshal an object instance from the data input stream"); out.println(" *"); out.println(" * @param wireFormat - describes the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); out.println(" * @param dataIn - BinaryReader that provides that data source"); out.println(" *"); out.println(" * @throws IOException if an error occurs during the unmarshal."); out.println(" */"); out.println(" virtual void looseUnmarshal( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataInputStream* dataIn ) throw( decaf::io::IOException );"); out.println(""); out.println(" /**"); out.println(" * Write a object instance to data output stream"); out.println(" *"); out.println(" * @param wireFormat - describs the wire format of the broker"); out.println(" * @param dataStructure - Object to be marshaled"); out.println(" * @param dataOut - BinaryWriter that provides that data sink"); out.println(" *"); out.println(" * @throws IOException if an error occurs during the marshal."); out.println(" */"); out.println(" virtual void looseMarshal( OpenWireFormat* wireFormat,"); out.println(" commands::DataStructure* dataStructure,"); out.println(" decaf::io::DataOutputStream* dataOut ) throw( decaf::io::IOException );"); out.println(""); out.println(" };"); out.println(""); out.println("}}}}}"); out.println(""); out.println("#endif /*_ACTIVEMQ_WIREFORMAT_OPENWIRE_MARSAHAL_V"+getOpenwireVersion()+"_"+className.toUpperCase()+"_H_*/"); out.println(""); }
diff --git a/spring-social-config/src/main/java/org/springframework/social/config/xml/JdbcConnectionRepositoryElementParser.java b/spring-social-config/src/main/java/org/springframework/social/config/xml/JdbcConnectionRepositoryElementParser.java index 665ff252..5c387020 100644 --- a/spring-social-config/src/main/java/org/springframework/social/config/xml/JdbcConnectionRepositoryElementParser.java +++ b/spring-social-config/src/main/java/org/springframework/social/config/xml/JdbcConnectionRepositoryElementParser.java @@ -1,48 +1,47 @@ /* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.social.config.xml; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.security.crypto.encrypt.Encryptors; import org.springframework.social.provider.jdbc.JdbcConnectionRepository; import org.w3c.dom.Element; public class JdbcConnectionRepositoryElementParser implements BeanDefinitionParser { public BeanDefinition parse(Element element, ParserContext parserContext) { - BeanDefinitionBuilder beanBuilder = BeanDefinitionBuilder -.genericBeanDefinition(JdbcConnectionRepository.class); + BeanDefinitionBuilder beanBuilder = BeanDefinitionBuilder.genericBeanDefinition(JdbcConnectionRepository.class); - String jdbcTemplate = element.getAttribute("jdbc-template"); - beanBuilder.addConstructorArgReference(jdbcTemplate); + String dataSource = element.getAttribute("data-source"); + beanBuilder.addConstructorArgReference(dataSource); String stringEncryptor = element.getAttribute("string-encryptor"); if (stringEncryptor != null && !stringEncryptor.isEmpty()) { beanBuilder.addConstructorArgReference(stringEncryptor); } else { beanBuilder.addConstructorArgValue(Encryptors.noOpText()); } AbstractBeanDefinition beanDefinition = beanBuilder.getBeanDefinition(); - parserContext.getRegistry().registerBeanDefinition("accountConnectionRepository", beanDefinition); + parserContext.getRegistry().registerBeanDefinition("connectionRepository", beanDefinition); return beanDefinition; } }
false
true
public BeanDefinition parse(Element element, ParserContext parserContext) { BeanDefinitionBuilder beanBuilder = BeanDefinitionBuilder .genericBeanDefinition(JdbcConnectionRepository.class); String jdbcTemplate = element.getAttribute("jdbc-template"); beanBuilder.addConstructorArgReference(jdbcTemplate); String stringEncryptor = element.getAttribute("string-encryptor"); if (stringEncryptor != null && !stringEncryptor.isEmpty()) { beanBuilder.addConstructorArgReference(stringEncryptor); } else { beanBuilder.addConstructorArgValue(Encryptors.noOpText()); } AbstractBeanDefinition beanDefinition = beanBuilder.getBeanDefinition(); parserContext.getRegistry().registerBeanDefinition("accountConnectionRepository", beanDefinition); return beanDefinition; }
public BeanDefinition parse(Element element, ParserContext parserContext) { BeanDefinitionBuilder beanBuilder = BeanDefinitionBuilder.genericBeanDefinition(JdbcConnectionRepository.class); String dataSource = element.getAttribute("data-source"); beanBuilder.addConstructorArgReference(dataSource); String stringEncryptor = element.getAttribute("string-encryptor"); if (stringEncryptor != null && !stringEncryptor.isEmpty()) { beanBuilder.addConstructorArgReference(stringEncryptor); } else { beanBuilder.addConstructorArgValue(Encryptors.noOpText()); } AbstractBeanDefinition beanDefinition = beanBuilder.getBeanDefinition(); parserContext.getRegistry().registerBeanDefinition("connectionRepository", beanDefinition); return beanDefinition; }
diff --git a/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java b/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java index c94eb06..9da94b8 100644 --- a/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java +++ b/src/main/java/hudson/plugins/promoted_builds/conditions/DownstreamPassCondition.java @@ -1,170 +1,177 @@ package hudson.plugins.promoted_builds.conditions; import hudson.CopyOnWrite; import hudson.Util; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Hudson; import hudson.model.Result; import hudson.model.TaskListener; import hudson.model.listeners.RunListener; import hudson.plugins.promoted_builds.JobPropertyImpl; import hudson.plugins.promoted_builds.PromotionCondition; import hudson.plugins.promoted_builds.PromotionConditionDescriptor; import hudson.plugins.promoted_builds.PromotionCriterion; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * @author Kohsuke Kawaguchi */ public class DownstreamPassCondition extends PromotionCondition { /** * List of downstream jobs that are used as the promotion criteria. * * Every job has to have at least one successful build for us to promote a build. */ private final String jobs; public DownstreamPassCondition(String jobs) { this.jobs = jobs; } public String getJobs() { return jobs; } @Override public boolean isMet(AbstractBuild<?,?> build) { for (AbstractProject<?,?> j : getJobList()) { boolean passed = false; for( AbstractBuild<?,?> b : build.getDownstreamBuilds(j) ) { if(b.getResult()== Result.SUCCESS) { passed = true; break; } } if(!passed) // none of the builds of this job passed. return false; } return true; } public PromotionConditionDescriptor getDescriptor() { return DescriptorImpl.INSTANCE; } /** * List of downstream jobs that we need to monitor. * * @return never null. */ public List<AbstractProject<?,?>> getJobList() { List<AbstractProject<?,?>> r = new ArrayList<AbstractProject<?,?>>(); for (String name : Util.tokenize(jobs,",")) { AbstractProject job = Hudson.getInstance().getItemByFullName(name.trim(),AbstractProject.class); if(job!=null) r.add(job); } return r; } /** * Short-cut for {@code getJobList().contains(job)}. */ public boolean contains(AbstractProject<?,?> job) { if(!jobs.contains(job.getFullName())) return false; // quick rejection test for (String name : Util.tokenize(jobs,",")) { if(name.trim().equals(job.getFullName())) return true; } return false; } public static final class DescriptorImpl extends PromotionConditionDescriptor { public DescriptorImpl() { super(DownstreamPassCondition.class); new RunListenerImpl().register(); } public boolean isApplicable(AbstractProject<?,?> item) { return true; } public String getDisplayName() { return "When the following downstream projects build successfully"; } public PromotionCondition newInstance(StaplerRequest req, JSONObject formData) throws FormException { return new DownstreamPassCondition(formData.getString("jobs")); } public static final DescriptorImpl INSTANCE = new DescriptorImpl(); } /** * {@link RunListener} to pick up completions of downstream builds. * * <p> * This is a single instance that receives all the events everywhere in the system. * @author Kohsuke Kawaguchi */ private static final class RunListenerImpl extends RunListener<AbstractBuild<?,?>> { public RunListenerImpl() { super((Class)AbstractBuild.class); } @Override public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) { // this is not terribly efficient, for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) { JobPropertyImpl p = j.getProperty(JobPropertyImpl.class); if(p!=null) { for (PromotionCriterion c : p.getCriteria()) { boolean considerPromotion = false; for (PromotionCondition cond : c.getConditions()) { if (cond instanceof DownstreamPassCondition) { DownstreamPassCondition dpcond = (DownstreamPassCondition) cond; - if(dpcond.contains(build.getParent())) + if(dpcond.contains(build.getParent())) { considerPromotion = true; + break; + } } } if(considerPromotion) { try { AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j); - if(u!=null && c.considerPromotion(u)) + if(u==null) { + // no upstream build. perhaps a configuration problem? + if(build.getResult()==Result.SUCCESS) + listener.getLogger().println("WARNING: "+j.getFullDisplayName()+" appears to use this job as a promotion criteria, but no fingerprint is recorded."); + } else + if(c.considerPromotion(u)) listener.getLogger().println("Promoted "+u); } catch (IOException e) { e.printStackTrace(listener.error("Failed to promote a build")); } } } } } } /** * List of downstream jobs that we are interested in. */ @CopyOnWrite private static volatile Set<AbstractProject> DOWNSTREAM_JOBS = Collections.emptySet(); /** * Called whenever some {@link JobPropertyImpl} changes to update {@link #DOWNSTREAM_JOBS}. */ public static void rebuildCache() { Set<AbstractProject> downstreams = new HashSet<AbstractProject>(); DOWNSTREAM_JOBS = downstreams; } } }
false
true
public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) { // this is not terribly efficient, for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) { JobPropertyImpl p = j.getProperty(JobPropertyImpl.class); if(p!=null) { for (PromotionCriterion c : p.getCriteria()) { boolean considerPromotion = false; for (PromotionCondition cond : c.getConditions()) { if (cond instanceof DownstreamPassCondition) { DownstreamPassCondition dpcond = (DownstreamPassCondition) cond; if(dpcond.contains(build.getParent())) considerPromotion = true; } } if(considerPromotion) { try { AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j); if(u!=null && c.considerPromotion(u)) listener.getLogger().println("Promoted "+u); } catch (IOException e) { e.printStackTrace(listener.error("Failed to promote a build")); } } } } } }
public void onCompleted(AbstractBuild<?,?> build, TaskListener listener) { // this is not terribly efficient, for(AbstractProject<?,?> j : Hudson.getInstance().getAllItems(AbstractProject.class)) { JobPropertyImpl p = j.getProperty(JobPropertyImpl.class); if(p!=null) { for (PromotionCriterion c : p.getCriteria()) { boolean considerPromotion = false; for (PromotionCondition cond : c.getConditions()) { if (cond instanceof DownstreamPassCondition) { DownstreamPassCondition dpcond = (DownstreamPassCondition) cond; if(dpcond.contains(build.getParent())) { considerPromotion = true; break; } } } if(considerPromotion) { try { AbstractBuild<?,?> u = build.getUpstreamRelationshipBuild(j); if(u==null) { // no upstream build. perhaps a configuration problem? if(build.getResult()==Result.SUCCESS) listener.getLogger().println("WARNING: "+j.getFullDisplayName()+" appears to use this job as a promotion criteria, but no fingerprint is recorded."); } else if(c.considerPromotion(u)) listener.getLogger().println("Promoted "+u); } catch (IOException e) { e.printStackTrace(listener.error("Failed to promote a build")); } } } } } }
diff --git a/openejb-itests-client/src/main/java/org/apache/openejb/test/IvmTestServer.java b/openejb-itests-client/src/main/java/org/apache/openejb/test/IvmTestServer.java index f77b477..ed6edcb 100644 --- a/openejb-itests-client/src/main/java/org/apache/openejb/test/IvmTestServer.java +++ b/openejb-itests-client/src/main/java/org/apache/openejb/test/IvmTestServer.java @@ -1,70 +1,69 @@ /** * 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.openejb.test; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; /** * @author <a href="mailto:[email protected]">David Blevins</a> * @author <a href="mailto:[email protected]">Richard Monson-Haefel</a> * * @version $Rev$ $Date$ */ public class IvmTestServer implements TestServer { private Properties properties; public void init(Properties props){ - properties = new Properties(); - properties.putAll(props); + properties = props; try{ props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory"); Properties p = new Properties(); p.putAll(props); p.put("openejb.loader", "embed"); new InitialContext( p ); // initialize openejb via constructing jndi tree //OpenEJB.init(properties); }catch(Exception oe){ System.out.println("========================="); System.out.println(""+oe.getMessage()); System.out.println("========================="); oe.printStackTrace(); throw new RuntimeException("OpenEJB could not be initiated"); } } public void destroy(){ } public void start(){ } public void stop(){ } public Properties getContextEnvironment(){ return (Properties)properties.clone(); } }
true
true
public void init(Properties props){ properties = new Properties(); properties.putAll(props); try{ props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory"); Properties p = new Properties(); p.putAll(props); p.put("openejb.loader", "embed"); new InitialContext( p ); // initialize openejb via constructing jndi tree //OpenEJB.init(properties); }catch(Exception oe){ System.out.println("========================="); System.out.println(""+oe.getMessage()); System.out.println("========================="); oe.printStackTrace(); throw new RuntimeException("OpenEJB could not be initiated"); } }
public void init(Properties props){ properties = props; try{ props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory"); Properties p = new Properties(); p.putAll(props); p.put("openejb.loader", "embed"); new InitialContext( p ); // initialize openejb via constructing jndi tree //OpenEJB.init(properties); }catch(Exception oe){ System.out.println("========================="); System.out.println(""+oe.getMessage()); System.out.println("========================="); oe.printStackTrace(); throw new RuntimeException("OpenEJB could not be initiated"); } }
diff --git a/Compiler/java/AppleCoreCompiler/AVM/AVMTranslatorPass.java b/Compiler/java/AppleCoreCompiler/AVM/AVMTranslatorPass.java index 4dd5d81..49b2c0f 100644 --- a/Compiler/java/AppleCoreCompiler/AVM/AVMTranslatorPass.java +++ b/Compiler/java/AppleCoreCompiler/AVM/AVMTranslatorPass.java @@ -1,611 +1,611 @@ /** * Generate AVM instructions for all functions in the source file. */ package AppleCoreCompiler.AVM; import AppleCoreCompiler.AST.*; import AppleCoreCompiler.AST.Node.*; import AppleCoreCompiler.Errors.*; import AppleCoreCompiler.AST.Node.RegisterExpression.Register; import AppleCoreCompiler.AVM.Instruction.*; import java.io.*; import java.util.*; import java.math.*; public class AVMTranslatorPass extends ASTScanner implements Pass { public void runOn(SourceFile sourceFile) throws ACCError { for (Declaration decl : sourceFile.decls) { if (decl instanceof FunctionDecl) { scan(decl); } } } /* State variables for tree traversal */ /** * The function being processed */ private FunctionDecl currentFunction; /** * Counter for branch labels */ private int branchLabelCount = 1; /** * Counter for constants */ private int constCount = 1; /** * Whether a variable seen is being evaluated for its address or * its value. */ private boolean needAddress; /** * Are we in debug mode? */ public boolean debug = false; /* Visitor methods */ /* Leaf nodes */ public void visitIntegerConstant(IntegerConstant node) { emit(new PHCInstruction(node)); } public void visitCharConstant(CharConstant node) { emit(new PHCInstruction(node)); } public void visitIdentifier(Identifier node) throws ACCError { Node def = node.def; if (def instanceof VarDecl) { VarDecl varDecl = (VarDecl) def; // Push variable's address on stack if (varDecl.isLocalVariable) { emit(new PVAInstruction(varDecl.getOffset())); } else { emit(new PHCInstruction(new Address(varDecl.name))); } if (!needAddress) { // Use the address to get the value. emit(new MTSInstruction(node.size)); } } else if (def instanceof ConstDecl) { ConstDecl cd = (ConstDecl) def; scan(cd.expr); } else if (def instanceof DataDecl) { DataDecl dataDecl = (DataDecl) def; emit(new PHCInstruction(new Address(dataDecl.label))); } } /* Non-leaf nodes */ public void visitFunctionDecl(FunctionDecl node) throws ACCError { if (!node.isExternal) { currentFunction = node; branchLabelCount=1; computeStackSlotsFor(node); node.instructions.clear(); emit(new LabelInstruction(node.name)); emit(new NativeInstruction("JSR","AVM.EXECUTE.FN")); emit(new ISPInstruction(node.frameSize)); scan(node.varDecls); scan(node.statements); if (!node.endsInReturnStatement()) { emit(new RAFInstruction(0)); } } } public void visitVarDecl(VarDecl node) throws ACCError { if (node.init != null) { // Evaluate intializer expr needAddress = false; scan(node.init); // Adjust the size adjustSize(node.size,node.init.size,node.init.isSigned); // Do the assignment. emit(new PVAInstruction(node.getOffset())); emit(new STMInstruction(node.size)); } } public void visitIfStatement(IfStatement node) throws ACCError { // Construct the labels boolean needTest = !node.test.isTrue() && !node.test.isFalse(); String label = getLabel(); LabelInstruction trueLabel = new LabelInstruction(mangle("TRUE"+label)); LabelInstruction falseLabel = new LabelInstruction(mangle("FALSE"+label)); LabelInstruction endLabel = new LabelInstruction(mangle("ENDIF"+label)); // Test and branch if (needTest) { needAddress = false; scan(node.test); emit(new BRFInstruction(falseLabel)); } // True part if (!node.test.isFalse()) { emit(trueLabel); scan(node.thenPart); if (node.elsePart != null && !node.test.isTrue()) { emit(new BRUInstruction(endLabel)); } } // False part if (!node.test.isTrue()) { emit(falseLabel); if (node.elsePart != null) { scan(node.elsePart); emit(endLabel); } } } public void visitWhileStatement(WhileStatement node) throws ACCError { // Construct the labels String label = getLabel(); LabelInstruction testLabel = new LabelInstruction(mangle("TEST"+label)); LabelInstruction bodyLabel = new LabelInstruction(mangle("BODY"+label)); LabelInstruction exitLabel = new LabelInstruction(mangle("EXIT"+label)); // Test and branch needAddress = false; boolean needTest = !node.test.isTrue() && !node.test.isFalse(); boolean needBody = !node.test.isFalse(); if (needTest) { emit(testLabel); scan(node.test); emit(new BRFInstruction(exitLabel)); } if (needBody) { // Loop body emit(bodyLabel); scan(node.body); if (needTest) { emit(new BRUInstruction(testLabel)); } else { emit(new BRUInstruction(bodyLabel)); } } if (needTest) { // Loop exit emit(exitLabel); } } public void visitExpressionStatement(ExpressionStatement node) throws ACCError { // Nothing special to do super.visitExpressionStatement(node); } public void visitReturnStatement(ReturnStatement node) throws ACCError { if (node.expr != null) { // Evaluate expression needAddress = false; scan(node.expr); adjustSize(currentFunction.size,node.expr.size, node.expr.isSigned); } emit(new RAFInstruction(currentFunction.size)); } public void visitBlockStatement(BlockStatement node) throws ACCError { // Nothing special to do super.visitBlockStatement(node); } public void visitIndexedExpression(IndexedExpression node) throws ACCError { // Record whether our result should be an address. boolean parentNeedsAddress = needAddress; // Evaluate indexed expr. needAddress = false; scan(node.indexed); // Pad to 2 bytes if necessary adjustSize(2,node.indexed.size,false); if (!node.index.isZero()) { // Evaluate index expr. needAddress = false; scan(node.index); // Pad to 2 bytes if necessary adjustSize(2,node.index.size,node.index.isSigned); // Pull LHS address and RHS index, add them, and put // result on the stack. emit(new ADDInstruction(2)); } // If parent wanted a value, compute it now. if (!parentNeedsAddress) { emit(new MTSInstruction(node.size)); } } public void visitCallExpression(CallExpression node) throws ACCError { boolean needIndirectCall = true; if (node.fn instanceof Identifier) { Identifier id = (Identifier) node.fn; Node def = id.def; if (def instanceof FunctionDecl) { emitCallToFunctionDecl((FunctionDecl) def, node.args); needIndirectCall = false; } else if (def instanceof ConstDecl || def instanceof DataDecl) { emitCallToConstant(id.name); needIndirectCall = false; } } else if (node.fn instanceof NumericConstant) { NumericConstant nc = (NumericConstant) node.fn; emitCallToConstant(nc.valueAsHexString()); needIndirectCall = false; } // If all else failed, use indirect call if (needIndirectCall) { emitIndirectCall(node.fn); } } /** * Call to declared function: push args, restore regs, call, and * save regs. */ private void emitCallToFunctionDecl(FunctionDecl functionDecl, List<Expression> args) throws ACCError { // Fill in the arguments, if any Iterator<VarDecl> I = functionDecl.params.iterator(); if (args.size() > 0) { // Save bump size for undo int bumpSize = 4; // Save place for return address and saved FP emit(new ISPInstruction(4)); for (Expression arg : args) { VarDecl param = I.next(); // Evaluate the argument needAddress = false; scan(arg); // Adjust sizes to match. adjustSize(param.size,arg.size,arg.isSigned); bumpSize += param.size; } // Bump SP back down to new FP emit(new DSPInstruction(bumpSize)); } restoreRegisters(); emit(new CFDInstruction(new Address(functionDecl.name))); saveRegisters(); } /** * Calling a constant address: restore regs, call, and save regs. */ private void emitCallToConstant(String addr) { restoreRegisters(); emit(new CFDInstruction(new Address(addr))); saveRegisters(); } /** * Indirect function call: evaluate expression, restore regs, call, * and save regs. */ private void emitIndirectCall(Expression node) throws ACCError { needAddress = false; scan(node); adjustSize(2,node.size,node.isSigned); restoreRegisters(); emit(new CFIInstruction()); saveRegisters(); } public void visitRegisterExpression(RegisterExpression node) throws ACCError { emit(new PVAInstruction(node.register.getOffset())); if (!needAddress) { emit(new MTSInstruction(1)); } } public void visitSetExpression(SetExpression node) throws ACCError { // Evaluate RHS as value needAddress = false; scan(node.rhs); adjustSize(node.lhs.getSize(),node.rhs.getSize(), node.rhs.isSigned); // Evaluate LHS as address. needAddress = true; scan(node.lhs); // Store RHS to (LHS) emit(new STMInstruction(node.lhs.getSize())); } public void visitBinopExpression(BinopExpression node) throws ACCError { int size = Math.max(node.left.size,node.right.size); // Evaluate left needAddress = false; scan(node.left); adjustSize(size,node.left.size,node.left.isSigned); // Evaluate right needAddress = false; scan(node.right); if (node.operator.compareTo(BinopExpression.Operator.SHR) > 0) { adjustSize(size,node.right.size,node.right.isSigned); } // Do the operation boolean signed = - node.left.isSigned || node.right.isSigned(); + node.left.isSigned || node.right.isSigned; switch (node.operator) { case SHL: emit(new SHLInstruction(size)); break; case SHR: emit(new SHRInstruction(size, signed)); break; case TIMES: emit(new MULInstruction(size, signed)); break; case DIVIDE: emit(new DIVInstruction(size, signed)); break; case PLUS: emit(new ADDInstruction(size)); break; case MINUS: emit(new SUBInstruction(size)); break; case EQUALS: emit(new TEQInstruction(size)); break; case GT: emit(new TGTInstruction(size, signed)); break; case GEQ: emit(new TGEInstruction(size, signed)); break; case LT: emit(new TLTInstruction(size, signed)); break; case LEQ: emit(new TLEInstruction(size, signed)); break; case AND: emit(new ANLInstruction(size)); break; case OR: emit(new ORLInstruction(size)); break; case XOR: emit(new ORXInstruction(size)); break; } } public void visitUnopExpression(UnopExpression node) throws ACCError { switch(node.operator) { case DEREF: needAddress = true; scan(node.expr); break; case NOT: needAddress = false; scan(node.expr); emit(new NOTInstruction(node.expr.size)); break; case NEG: needAddress = false; scan(node.expr); emit(new NEGInstruction(node.expr.size)); break; case INCR: needAddress = true; scan(node.expr); emit(new ICRInstruction(node.expr.size)); break; case DECR: needAddress = true; scan(node.expr); emit(new DCRInstruction(node.expr.size)); break; default: throw new ACCInternalError("unhandled unary operator",node); } } public void visitParensExpression(ParensExpression node) throws ACCError { // Nothing special to do super.visitParensExpression(node); } /* Helper methods */ private String mangle(String s) { return currentFunction.name+"."+s; } /** * Print out debugging info */ public void printStatus(String s) { if (debug) { System.err.println(s); } } /** * Get a fresh branch label */ private String getLabel() { return "." + branchLabelCount++; } /** * Record the local variables in the current frame and compute * their stack slots. */ private void computeStackSlotsFor(FunctionDecl node) throws ACCError { printStatus("stack slots:"); int offset = 0; printStatus(" return address: " + offset); // Two bytes for return address offset += 2; printStatus(" FP: " + offset); // Two bytes for saved FP offset += 2; // Params for (VarDecl varDecl : node.params) { printStatus(" " + varDecl + ",offset=" + offset); varDecl.setOffset(offset); offset += varDecl.getSize(); } int firstLocalVarOffset = offset; // Local vars for (VarDecl varDecl : node.varDecls) { printStatus(" " + varDecl + ",offset=" + offset); varDecl.setOffset(offset); offset += varDecl.getSize(); } // Saved regs savedRegs.runOn(node); for (RegisterExpression.Register reg : node.savedRegs) { printStatus(" " + reg + ",offset=" + offset); reg.setOffset(offset); offset += reg.getSize(); } // Compute and store the frame size. node.frameSize = offset; printStatus("frame size="+node.frameSize); } /** * If a register expression for register R appears in the function * body, then we need a stack slot for R. Find all those * registers now. */ private SavedRegs savedRegs = new SavedRegs(); private class SavedRegs extends ASTScanner implements FunctionPass { FunctionDecl fn; public void runOn(FunctionDecl node) throws ACCError { fn = node; scan(node); } public void visitRegisterExpression(RegisterExpression node) { fn.savedRegs.add(node.register); } } /** * Make a value on the stack bigger or smaller if necessary to fit * needed size. */ private void adjustSize(int targetSize, int stackSize, boolean signed) { if (targetSize < stackSize) { emit(new DSPInstruction(stackSize-targetSize)); } if (targetSize > stackSize) { emit(new EXTInstruction(targetSize-stackSize, signed)); } } /** * Emit code to restore all registers to the values saved in their * spill slots on the program stack. */ private void restoreRegisters() { if (currentFunction.savedRegs.size() > 0) { for (RegisterExpression.Register reg : currentFunction.savedRegs) { emit(new VTMInstruction(reg.getOffset(), new Address(reg.saveAddr))); } emit(new CFDInstruction(new Address("$FF3F"))); } } /** * Emit code to save the registers to their spill slots. */ private void saveRegisters() { if (currentFunction.savedRegs.size() > 0) { emit(new CFDInstruction(new Address("$FF4A"))); for (RegisterExpression.Register reg : currentFunction.savedRegs) { emit(new MTVInstruction(reg.getOffset(), new Address(reg.saveAddr))); } } } private void emit(Instruction inst) { currentFunction.instructions.add(inst); } }
true
true
public void visitBinopExpression(BinopExpression node) throws ACCError { int size = Math.max(node.left.size,node.right.size); // Evaluate left needAddress = false; scan(node.left); adjustSize(size,node.left.size,node.left.isSigned); // Evaluate right needAddress = false; scan(node.right); if (node.operator.compareTo(BinopExpression.Operator.SHR) > 0) { adjustSize(size,node.right.size,node.right.isSigned); } // Do the operation boolean signed = node.left.isSigned || node.right.isSigned(); switch (node.operator) { case SHL: emit(new SHLInstruction(size)); break; case SHR: emit(new SHRInstruction(size, signed)); break; case TIMES: emit(new MULInstruction(size, signed)); break; case DIVIDE: emit(new DIVInstruction(size, signed)); break; case PLUS: emit(new ADDInstruction(size)); break; case MINUS: emit(new SUBInstruction(size)); break; case EQUALS: emit(new TEQInstruction(size)); break; case GT: emit(new TGTInstruction(size, signed)); break; case GEQ: emit(new TGEInstruction(size, signed)); break; case LT: emit(new TLTInstruction(size, signed)); break; case LEQ: emit(new TLEInstruction(size, signed)); break; case AND: emit(new ANLInstruction(size)); break; case OR: emit(new ORLInstruction(size)); break; case XOR: emit(new ORXInstruction(size)); break; } }
public void visitBinopExpression(BinopExpression node) throws ACCError { int size = Math.max(node.left.size,node.right.size); // Evaluate left needAddress = false; scan(node.left); adjustSize(size,node.left.size,node.left.isSigned); // Evaluate right needAddress = false; scan(node.right); if (node.operator.compareTo(BinopExpression.Operator.SHR) > 0) { adjustSize(size,node.right.size,node.right.isSigned); } // Do the operation boolean signed = node.left.isSigned || node.right.isSigned; switch (node.operator) { case SHL: emit(new SHLInstruction(size)); break; case SHR: emit(new SHRInstruction(size, signed)); break; case TIMES: emit(new MULInstruction(size, signed)); break; case DIVIDE: emit(new DIVInstruction(size, signed)); break; case PLUS: emit(new ADDInstruction(size)); break; case MINUS: emit(new SUBInstruction(size)); break; case EQUALS: emit(new TEQInstruction(size)); break; case GT: emit(new TGTInstruction(size, signed)); break; case GEQ: emit(new TGEInstruction(size, signed)); break; case LT: emit(new TLTInstruction(size, signed)); break; case LEQ: emit(new TLEInstruction(size, signed)); break; case AND: emit(new ANLInstruction(size)); break; case OR: emit(new ORLInstruction(size)); break; case XOR: emit(new ORXInstruction(size)); break; } }
diff --git a/plugins/org.eclipse.wst.common.frameworks/src/org/eclipse/wst/common/frameworks/internal/OperationManager.java b/plugins/org.eclipse.wst.common.frameworks/src/org/eclipse/wst/common/frameworks/internal/OperationManager.java index 6fb0d412..78e77e93 100644 --- a/plugins/org.eclipse.wst.common.frameworks/src/org/eclipse/wst/common/frameworks/internal/OperationManager.java +++ b/plugins/org.eclipse.wst.common.frameworks/src/org/eclipse/wst/common/frameworks/internal/OperationManager.java @@ -1,377 +1,377 @@ /*************************************************************************************************** * Copyright (c) 2003, 2005 IBM Corporation and others. All rights reserved. This program and the * accompanying materials are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation **************************************************************************************************/ package org.eclipse.wst.common.frameworks.internal; import java.util.ArrayList; import java.util.HashMap; import java.util.Stack; import java.util.Vector; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation; import org.eclipse.wst.common.frameworks.datamodel.IDataModel; import org.eclipse.wst.common.frameworks.datamodel.IDataModelOperation; import org.eclipse.wst.common.frameworks.internal.datamodel.IWorkspaceRunnableWithStatus; import org.eclipse.wst.common.frameworks.internal.operations.DMComposedExtendedOperationHolder; import org.eclipse.wst.common.frameworks.internal.operations.DMOperationExtensionRegistry; import org.eclipse.wst.common.frameworks.internal.operations.OperationStatus; public class OperationManager { private IDataModel dataModel; private DataModelManager dataModelManager; private TableEntry rootOperation; private HashMap operationTable; private Stack runStopList; private IProgressMonitor monitor; private IAdaptable adaptable; private OperationStatus status; private OperationListener preExecuteListener; private OperationListener postExecuteListener; private OperationListener undoExecuteListener; public OperationManager(DataModelManager aDataModelManager, IDataModelOperation aRootOperation) { if (aRootOperation == null) aRootOperation = new NullOperation(); TableEntry entry = new TableEntry(aRootOperation); dataModelManager = aDataModelManager; dataModel = dataModelManager.getDataModel(); rootOperation = entry; operationTable = new HashMap(); runStopList = new Stack(); operationTable.put(aRootOperation.getID(), entry); addExtendedOperations(aRootOperation); OperationListener defaultListener = new OperationListener() { public boolean notify(IDataModelOperation operation) { return true; } }; preExecuteListener = defaultListener; postExecuteListener = defaultListener; undoExecuteListener = defaultListener; } public void setProgressMonitor(IProgressMonitor monitor) { this.monitor = monitor; } public void setAdaptable(IAdaptable adaptable) { this.adaptable = adaptable; } public void addPreOperation(String operationId, IDataModelOperation insertOperation) { TableEntry entry = (TableEntry) operationTable.get(operationId); if (entry != null) { TableEntry newEntry = new TableEntry(insertOperation); entry.preOperations.add(newEntry); operationTable.put(insertOperation.getID(), newEntry); } } public void addPostOperation(String operationId, IDataModelOperation insertOperation) { TableEntry entry = (TableEntry) operationTable.get(operationId); if (entry != null) { TableEntry newEntry = new TableEntry(insertOperation); entry.postOperations.add(newEntry); operationTable.put(insertOperation.getID(), newEntry); } } public void setPreExecuteListener(OperationListener listener) { if (listener != null) preExecuteListener = listener; } public void setPostExecuteListener(OperationListener listener) { if (listener != null) postExecuteListener = listener; } public void setUndoExecuteListener(OperationListener listener) { if (listener != null) undoExecuteListener = listener; } public IStatus runOperations() { boolean continueRun = true; RunListEntry runEntry = startNewRun(); status = null; // All operations have already been run so just return OK. if (runEntry.stackEntries.empty()) return Status.OK_STATUS; while (continueRun) { continueRun = runOperationsUntilStopped(runEntry) && !runEntry.stackEntries.empty(); } if (status != null && status.getSeverity() == IStatus.ERROR) { undoLastRun(); } return status; } public void undoLastRun() { if (!runStopList.empty()) { RunListEntry runListEntry = (RunListEntry) runStopList.pop(); for (int index = runListEntry.executedOperations.size() - 1; index >= 0; index--) { IDataModelOperation operation = (IDataModelOperation) runListEntry.executedOperations.elementAt(index); String dataModelID = operation.getDataModelID(); if (dataModelID != null) dataModelManager.removeNestedDataModel(dataModelID); try { undoExecuteListener.notify(operation); } catch (Throwable exc) { // TODO report undo notify exception. } if (operation.canUndo()) { try { runOperation(operation, true); } catch (Throwable exc) { // TODO report an undo exception here. } } } } } private RunListEntry startNewRun() { RunListEntry newEntry = null; if (runStopList.empty()) { newEntry = new RunListEntry(rootOperation); } else { RunListEntry topRunList = (RunListEntry) runStopList.peek(); newEntry = new RunListEntry(topRunList); } runStopList.push(newEntry); return newEntry; } private boolean runOperationsUntilStopped(RunListEntry runListEntry) { StackEntry stackEntry = (StackEntry) runListEntry.stackEntries.peek(); boolean continueRun = true; // Run the pre operations. for (int index = stackEntry.preOperationIndex + 1; continueRun && index < stackEntry.tableEntry.preOperations.size(); index++) { TableEntry tableEntry = (TableEntry) stackEntry.tableEntry.preOperations.elementAt(index); runListEntry.stackEntries.push(new StackEntry(tableEntry)); stackEntry.preOperationIndex = index; continueRun = runOperationsUntilStopped(runListEntry); } if (continueRun && !stackEntry.operationExecuted) { IDataModelOperation operation = stackEntry.tableEntry.operation; try { continueRun = preExecuteListener.notify(operation); if (continueRun) { String dataModelID = operation.getDataModelID(); if (dataModelID != null) dataModelManager.addNestedDataModel(dataModelID); operation.setDataModel(dataModel); setStatus(runOperation(operation, false)); runListEntry.executedOperations.add(operation); stackEntry.operationExecuted = true; continueRun = postExecuteListener.notify(operation); } } catch (Throwable exc) { - setStatus(new Status(IStatus.ERROR, "id", 0, exc.getMessage(), exc)); + setStatus(new Status(IStatus.ERROR, "id", 0, exc.getMessage() == null ? exc.toString() : exc.getMessage(), exc)); } if (status != null && status.getSeverity() == IStatus.ERROR) { // This isn't really true, but it will cause the run operations to stop. continueRun = false; } } // Run post operations. for (int index = stackEntry.postOperationIndex + 1; continueRun && index < stackEntry.tableEntry.postOperations.size(); index++) { TableEntry tableEntry = (TableEntry) stackEntry.tableEntry.postOperations.elementAt(index); stackEntry.postOperationIndex = index; runListEntry.stackEntries.push(new StackEntry(tableEntry)); continueRun = runOperationsUntilStopped(runListEntry); } // If we are have run the pre ops, this operation, and // the post ops, we should pop this entry off the stack. // Also, if continueRun is false we don't want to pop the stack since we will want to come // back to this entry later. if (continueRun) { runListEntry.stackEntries.pop(); } return continueRun; } private IStatus runOperation(final IDataModelOperation operation, final boolean isUndo) { IWorkspaceRunnableWithStatus workspaceRunnable = new IWorkspaceRunnableWithStatus(adaptable) { public void run(IProgressMonitor pm) throws CoreException { try { if (isUndo) { this.setStatus(operation.undo(monitor, getInfo())); } else { this.setStatus(operation.execute(monitor, getInfo())); } } catch (Throwable exc) { exc.printStackTrace(); } } }; ISchedulingRule rule = operation.getSchedulingRule(); try { if (rule == null) { ResourcesPlugin.getWorkspace().run(workspaceRunnable, monitor); } else { ResourcesPlugin.getWorkspace().run(workspaceRunnable, rule, operation.getOperationExecutionFlags(), monitor); } } catch (CoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } return workspaceRunnable.getStatus(); } private void setStatus(IStatus newStatus) { if (status == null) { status = new OperationStatus(newStatus.getMessage(), newStatus.getException()); status.setSeverity(newStatus.getSeverity()); status.add(newStatus); } else { status.add(newStatus); } } private void addExtendedOperations(IDataModelOperation operation) { DMComposedExtendedOperationHolder extendedOps = DMOperationExtensionRegistry.getExtensions(operation); ArrayList preOps = null; ArrayList postOps = null; if (extendedOps != null) { preOps = extendedOps.getPreOps(); postOps = extendedOps.getPostOps(); } if (preOps == null) preOps = new ArrayList(); if (postOps == null) postOps = new ArrayList(); for (int index = 0; index < preOps.size(); index++) { IDataModelOperation newOperation = (IDataModelOperation) preOps.get(index); addPreOperation(operation.getID(), newOperation); addExtendedOperations(newOperation); } for (int index = 0; index < postOps.size(); index++) { IDataModelOperation newOperation = (IDataModelOperation) postOps.get(index); addPostOperation(operation.getID(), newOperation); addExtendedOperations(newOperation); } } private class RunListEntry { public Stack stackEntries; public Vector executedOperations; public RunListEntry(TableEntry newEntry) { stackEntries = new Stack(); executedOperations = new Vector(); stackEntries.push(new StackEntry(newEntry)); } public RunListEntry(RunListEntry oldList) { stackEntries = new Stack(); executedOperations = new Vector(); for (int index = 0; index < oldList.stackEntries.size(); index++) { StackEntry oldEntry = (StackEntry) oldList.stackEntries.elementAt(index); stackEntries.add(new StackEntry(oldEntry)); } } } private class StackEntry { public int preOperationIndex; public int postOperationIndex; public boolean operationExecuted; public TableEntry tableEntry; public StackEntry(TableEntry newTableEntry) { preOperationIndex = -1; postOperationIndex = -1; operationExecuted = false; tableEntry = newTableEntry; } public StackEntry(StackEntry newStackEntry) { preOperationIndex = newStackEntry.preOperationIndex; postOperationIndex = newStackEntry.postOperationIndex; operationExecuted = newStackEntry.operationExecuted; tableEntry = newStackEntry.tableEntry; } } private class TableEntry { public IDataModelOperation operation; public Vector preOperations; public Vector postOperations; public TableEntry(IDataModelOperation newOperation) { operation = newOperation; preOperations = new Vector(3); postOperations = new Vector(3); } } private class NullOperation extends AbstractDataModelOperation { public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return Status.OK_STATUS; } public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return Status.OK_STATUS; } public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return Status.OK_STATUS; } } }
true
true
private boolean runOperationsUntilStopped(RunListEntry runListEntry) { StackEntry stackEntry = (StackEntry) runListEntry.stackEntries.peek(); boolean continueRun = true; // Run the pre operations. for (int index = stackEntry.preOperationIndex + 1; continueRun && index < stackEntry.tableEntry.preOperations.size(); index++) { TableEntry tableEntry = (TableEntry) stackEntry.tableEntry.preOperations.elementAt(index); runListEntry.stackEntries.push(new StackEntry(tableEntry)); stackEntry.preOperationIndex = index; continueRun = runOperationsUntilStopped(runListEntry); } if (continueRun && !stackEntry.operationExecuted) { IDataModelOperation operation = stackEntry.tableEntry.operation; try { continueRun = preExecuteListener.notify(operation); if (continueRun) { String dataModelID = operation.getDataModelID(); if (dataModelID != null) dataModelManager.addNestedDataModel(dataModelID); operation.setDataModel(dataModel); setStatus(runOperation(operation, false)); runListEntry.executedOperations.add(operation); stackEntry.operationExecuted = true; continueRun = postExecuteListener.notify(operation); } } catch (Throwable exc) { setStatus(new Status(IStatus.ERROR, "id", 0, exc.getMessage(), exc)); } if (status != null && status.getSeverity() == IStatus.ERROR) { // This isn't really true, but it will cause the run operations to stop. continueRun = false; } } // Run post operations. for (int index = stackEntry.postOperationIndex + 1; continueRun && index < stackEntry.tableEntry.postOperations.size(); index++) { TableEntry tableEntry = (TableEntry) stackEntry.tableEntry.postOperations.elementAt(index); stackEntry.postOperationIndex = index; runListEntry.stackEntries.push(new StackEntry(tableEntry)); continueRun = runOperationsUntilStopped(runListEntry); } // If we are have run the pre ops, this operation, and // the post ops, we should pop this entry off the stack. // Also, if continueRun is false we don't want to pop the stack since we will want to come // back to this entry later. if (continueRun) { runListEntry.stackEntries.pop(); } return continueRun; }
private boolean runOperationsUntilStopped(RunListEntry runListEntry) { StackEntry stackEntry = (StackEntry) runListEntry.stackEntries.peek(); boolean continueRun = true; // Run the pre operations. for (int index = stackEntry.preOperationIndex + 1; continueRun && index < stackEntry.tableEntry.preOperations.size(); index++) { TableEntry tableEntry = (TableEntry) stackEntry.tableEntry.preOperations.elementAt(index); runListEntry.stackEntries.push(new StackEntry(tableEntry)); stackEntry.preOperationIndex = index; continueRun = runOperationsUntilStopped(runListEntry); } if (continueRun && !stackEntry.operationExecuted) { IDataModelOperation operation = stackEntry.tableEntry.operation; try { continueRun = preExecuteListener.notify(operation); if (continueRun) { String dataModelID = operation.getDataModelID(); if (dataModelID != null) dataModelManager.addNestedDataModel(dataModelID); operation.setDataModel(dataModel); setStatus(runOperation(operation, false)); runListEntry.executedOperations.add(operation); stackEntry.operationExecuted = true; continueRun = postExecuteListener.notify(operation); } } catch (Throwable exc) { setStatus(new Status(IStatus.ERROR, "id", 0, exc.getMessage() == null ? exc.toString() : exc.getMessage(), exc)); } if (status != null && status.getSeverity() == IStatus.ERROR) { // This isn't really true, but it will cause the run operations to stop. continueRun = false; } } // Run post operations. for (int index = stackEntry.postOperationIndex + 1; continueRun && index < stackEntry.tableEntry.postOperations.size(); index++) { TableEntry tableEntry = (TableEntry) stackEntry.tableEntry.postOperations.elementAt(index); stackEntry.postOperationIndex = index; runListEntry.stackEntries.push(new StackEntry(tableEntry)); continueRun = runOperationsUntilStopped(runListEntry); } // If we are have run the pre ops, this operation, and // the post ops, we should pop this entry off the stack. // Also, if continueRun is false we don't want to pop the stack since we will want to come // back to this entry later. if (continueRun) { runListEntry.stackEntries.pop(); } return continueRun; }
diff --git a/htroot/Bookmarks.java b/htroot/Bookmarks.java index 96b7b0d15..2f8a8b8c0 100644 --- a/htroot/Bookmarks.java +++ b/htroot/Bookmarks.java @@ -1,282 +1,285 @@ // Bookmarks_p.java // ----------------------- // part of YACY // (C) by Michael Peter Christen; [email protected] // first published on http://www.anomic.de // Frankfurt, Germany, 2004 // // This File is contributed by Alexander Schier // last change: 26.12.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. // You must compile this file with // javac -classpath .:../Classes Blacklist_p.java // if the shell's current path is HTROOT import java.io.File; import java.net.MalformedURLException; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import de.anomic.data.bookmarksDB; import de.anomic.data.listManager; import de.anomic.data.bookmarksDB.Tag; import de.anomic.http.httpHeader; import de.anomic.net.URL; import de.anomic.plasma.plasmaCrawlLURL; import de.anomic.plasma.plasmaParserDocument; import de.anomic.plasma.plasmaSwitchboard; import de.anomic.server.serverObjects; import de.anomic.server.serverSwitch; import de.anomic.yacy.yacyCore; import de.anomic.yacy.yacyNewsRecord; public class Bookmarks { public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { serverObjects prop = new serverObjects(); plasmaSwitchboard switchboard = (plasmaSwitchboard) env; int max_count=10; String tagName=""; int start=0; boolean isAdmin=switchboard.verifyAuthentication(header, true); //defaultvalues prop.put("mode", 0); if(isAdmin){ prop.put("mode", 1); } prop.put("mode_edit", 0); prop.put("mode_title", ""); prop.put("mode_description", ""); prop.put("mode_url", ""); prop.put("mode_tags", ""); prop.put("mode_public", 1); //1=is public if(post != null){ if(!isAdmin){ if(post.containsKey("login")){ prop.put("AUTHENTICATE","admin log-in"); } }else if(post.containsKey("mode")){ String mode=(String) post.get("mode"); if(mode.equals("add")){ prop.put("mode", 2); }else if(mode.equals("importxml")){ prop.put("mode", 3); }else if(mode.equals("importbookmarks")){ prop.put("mode", 4); } }else if(post.containsKey("add")){ //add an Entry String url=(String) post.get("url"); String title=(String) post.get("title"); String description=(String) post.get("description"); String tagsString = (String)post.get("tags"); if(tagsString.equals("")){ tagsString="unsorted"; //defaulttag } HashSet tags=listManager.string2hashset(tagsString); bookmarksDB.Bookmark bookmark = switchboard.bookmarksDB.createBookmark(url); if(bookmark != null){ bookmark.setProperty(bookmarksDB.Bookmark.BOOKMARK_TITLE, title); bookmark.setProperty(bookmarksDB.Bookmark.BOOKMARK_DESCRIPTION, description); if(((String) post.get("public")).equals("public")){ bookmark.setPublic(true); // create a news message HashMap map = new HashMap(); map.put("url", url.replace(',', '|')); map.put("title", title.replace(',', ' ')); map.put("description", description.replace(',', ' ')); map.put("tags", tagsString.replace(',', ' ')); yacyCore.newsPool.publishMyNews(new yacyNewsRecord("bkmrkadd", map)); }else{ bookmark.setPublic(false); } bookmark.setTags(tags, true); switchboard.bookmarksDB.saveBookmark(bookmark); }else{ //ERROR } }else if(post.containsKey("edit")){ String urlHash=(String) post.get("edit"); prop.put("mode", 2); if (urlHash.length() == 0) { prop.put("mode_edit", 0); // create mode prop.put("mode_title", (String) post.get("title")); prop.put("mode_description", (String) post.get("description")); prop.put("mode_url", (String) post.get("url")); prop.put("mode_tags", (String) post.get("tags")); prop.put("mode_public", 0); } else { bookmarksDB.Bookmark bookmark = switchboard.bookmarksDB.getBookmark(urlHash); if (bookmark == null) { // try to get the bookmark from the LURL database plasmaCrawlLURL.Entry urlentry = switchboard.urlPool.loadedURL.load(urlHash, null); - plasmaParserDocument document = switchboard.snippetCache.retrieveDocument(urlentry.url(), true); + plasmaParserDocument document = null; + if(urlentry != null){ + document = switchboard.snippetCache.retrieveDocument(urlentry.url(), true); + } if (urlentry != null) { prop.put("mode_edit", 0); // create mode prop.put("mode_title", urlentry.descr()); prop.put("mode_description", (document == null) ? urlentry.descr() : document.getMainLongTitle()); prop.put("mode_url", urlentry.url()); prop.put("mode_tags", (document == null) ? "" : document.getKeywords(',')); prop.put("mode_public", 0); } } else { // get from the bookmark database prop.put("mode_edit", 1); // edit mode prop.put("mode_title", bookmark.getTitle()); prop.put("mode_description", bookmark.getDescription()); prop.put("mode_url", bookmark.getUrl()); prop.put("mode_tags", bookmark.getTagsString()); if (bookmark.getPublic()) { prop.put("mode_public", 1); } else { prop.put("mode_public", 0); } } } }else if(post.containsKey("bookmarksfile")){ boolean isPublic=false; if(((String) post.get("public")).equals("public")){ isPublic=true; } String tags=(String) post.get("tags"); if(tags.equals("")){ tags="unsorted"; } try { File file=new File((String)post.get("bookmarksfile")); switchboard.bookmarksDB.importFromBookmarks(new URL(file) , new String((byte[])post.get("bookmarksfile$file")), tags, isPublic); } catch (MalformedURLException e) {} }else if(post.containsKey("xmlfile")){ boolean isPublic=false; if(((String) post.get("public")).equals("public")){ isPublic=true; } switchboard.bookmarksDB.importFromXML(new String((byte[])post.get("xmlfile$file")), isPublic); }else if(post.containsKey("delete")){ String urlHash=(String) post.get("delete"); switchboard.bookmarksDB.removeBookmark(urlHash); } if(post.containsKey("tag")){ tagName=(String) post.get("tag"); } if(post.containsKey("start")){ start=Integer.parseInt((String) post.get("start")); } if(post.containsKey("num")){ max_count=Integer.parseInt((String) post.get("num")); } } Iterator it=switchboard.bookmarksDB.getTagIterator(isAdmin); int count=0; bookmarksDB.Tag tag; prop.put("num-bookmarks", switchboard.bookmarksDB.bookmarksSize()); while(it.hasNext()){ tag=(Tag) it.next(); prop.put("taglist_"+count+"_name", tag.getFriendlyName()); prop.put("taglist_"+count+"_tag", tag.getTagName()); prop.put("taglist_"+count+"_num", tag.size()); count++; } prop.put("taglist", count); count=0; if(!tagName.equals("")){ it=switchboard.bookmarksDB.getBookmarksIterator(tagName, isAdmin); }else{ it=switchboard.bookmarksDB.getBookmarksIterator(isAdmin); } bookmarksDB.Bookmark bookmark; //skip the first entries (display next page) count=0; while(count < start && it.hasNext()){ it.next(); count++; } count=0; HashSet tags; Iterator tagsIt; int tagCount; while(count<max_count && it.hasNext()){ bookmark=switchboard.bookmarksDB.getBookmark((String)it.next()); if(bookmark!=null){ prop.put("bookmarks_"+count+"_link", bookmark.getUrl()); prop.put("bookmarks_"+count+"_title", bookmark.getTitle()); prop.put("bookmarks_"+count+"_description", bookmark.getDescription()); prop.put("bookmarks_"+count+"_public", (bookmark.getPublic()? 1:0)); //List Tags. tags=bookmark.getTags(); tagsIt=tags.iterator(); tagCount=0; while(tagsIt.hasNext()){ prop.put("bookmarks_"+count+"_tags_"+tagCount+"_tag", tagsIt.next()); tagCount++; } prop.put("bookmarks_"+count+"_tags", tagCount); prop.put("bookmarks_"+count+"_hash", bookmark.getUrlHash()); count++; } } prop.put("tag", tagName); prop.put("start", start); if(it.hasNext()){ prop.put("next-page", 1); prop.put("next-page_start", start+max_count); prop.put("next-page_tag", tagName); prop.put("next-page_num", max_count); } if(start >= max_count){ start=start-max_count; if(start <0){ start=0; } prop.put("prev-page", 1); prop.put("prev-page_start", start); prop.put("prev-page_tag", tagName); prop.put("prev-page_num", max_count); } prop.put("bookmarks", count); return prop; } }
true
true
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { serverObjects prop = new serverObjects(); plasmaSwitchboard switchboard = (plasmaSwitchboard) env; int max_count=10; String tagName=""; int start=0; boolean isAdmin=switchboard.verifyAuthentication(header, true); //defaultvalues prop.put("mode", 0); if(isAdmin){ prop.put("mode", 1); } prop.put("mode_edit", 0); prop.put("mode_title", ""); prop.put("mode_description", ""); prop.put("mode_url", ""); prop.put("mode_tags", ""); prop.put("mode_public", 1); //1=is public if(post != null){ if(!isAdmin){ if(post.containsKey("login")){ prop.put("AUTHENTICATE","admin log-in"); } }else if(post.containsKey("mode")){ String mode=(String) post.get("mode"); if(mode.equals("add")){ prop.put("mode", 2); }else if(mode.equals("importxml")){ prop.put("mode", 3); }else if(mode.equals("importbookmarks")){ prop.put("mode", 4); } }else if(post.containsKey("add")){ //add an Entry String url=(String) post.get("url"); String title=(String) post.get("title"); String description=(String) post.get("description"); String tagsString = (String)post.get("tags"); if(tagsString.equals("")){ tagsString="unsorted"; //defaulttag } HashSet tags=listManager.string2hashset(tagsString); bookmarksDB.Bookmark bookmark = switchboard.bookmarksDB.createBookmark(url); if(bookmark != null){ bookmark.setProperty(bookmarksDB.Bookmark.BOOKMARK_TITLE, title); bookmark.setProperty(bookmarksDB.Bookmark.BOOKMARK_DESCRIPTION, description); if(((String) post.get("public")).equals("public")){ bookmark.setPublic(true); // create a news message HashMap map = new HashMap(); map.put("url", url.replace(',', '|')); map.put("title", title.replace(',', ' ')); map.put("description", description.replace(',', ' ')); map.put("tags", tagsString.replace(',', ' ')); yacyCore.newsPool.publishMyNews(new yacyNewsRecord("bkmrkadd", map)); }else{ bookmark.setPublic(false); } bookmark.setTags(tags, true); switchboard.bookmarksDB.saveBookmark(bookmark); }else{ //ERROR } }else if(post.containsKey("edit")){ String urlHash=(String) post.get("edit"); prop.put("mode", 2); if (urlHash.length() == 0) { prop.put("mode_edit", 0); // create mode prop.put("mode_title", (String) post.get("title")); prop.put("mode_description", (String) post.get("description")); prop.put("mode_url", (String) post.get("url")); prop.put("mode_tags", (String) post.get("tags")); prop.put("mode_public", 0); } else { bookmarksDB.Bookmark bookmark = switchboard.bookmarksDB.getBookmark(urlHash); if (bookmark == null) { // try to get the bookmark from the LURL database plasmaCrawlLURL.Entry urlentry = switchboard.urlPool.loadedURL.load(urlHash, null); plasmaParserDocument document = switchboard.snippetCache.retrieveDocument(urlentry.url(), true); if (urlentry != null) { prop.put("mode_edit", 0); // create mode prop.put("mode_title", urlentry.descr()); prop.put("mode_description", (document == null) ? urlentry.descr() : document.getMainLongTitle()); prop.put("mode_url", urlentry.url()); prop.put("mode_tags", (document == null) ? "" : document.getKeywords(',')); prop.put("mode_public", 0); } } else { // get from the bookmark database prop.put("mode_edit", 1); // edit mode prop.put("mode_title", bookmark.getTitle()); prop.put("mode_description", bookmark.getDescription()); prop.put("mode_url", bookmark.getUrl()); prop.put("mode_tags", bookmark.getTagsString()); if (bookmark.getPublic()) { prop.put("mode_public", 1); } else { prop.put("mode_public", 0); } } } }else if(post.containsKey("bookmarksfile")){ boolean isPublic=false; if(((String) post.get("public")).equals("public")){ isPublic=true; } String tags=(String) post.get("tags"); if(tags.equals("")){ tags="unsorted"; } try { File file=new File((String)post.get("bookmarksfile")); switchboard.bookmarksDB.importFromBookmarks(new URL(file) , new String((byte[])post.get("bookmarksfile$file")), tags, isPublic); } catch (MalformedURLException e) {} }else if(post.containsKey("xmlfile")){ boolean isPublic=false; if(((String) post.get("public")).equals("public")){ isPublic=true; } switchboard.bookmarksDB.importFromXML(new String((byte[])post.get("xmlfile$file")), isPublic); }else if(post.containsKey("delete")){ String urlHash=(String) post.get("delete"); switchboard.bookmarksDB.removeBookmark(urlHash); } if(post.containsKey("tag")){ tagName=(String) post.get("tag"); } if(post.containsKey("start")){ start=Integer.parseInt((String) post.get("start")); } if(post.containsKey("num")){ max_count=Integer.parseInt((String) post.get("num")); } } Iterator it=switchboard.bookmarksDB.getTagIterator(isAdmin); int count=0; bookmarksDB.Tag tag; prop.put("num-bookmarks", switchboard.bookmarksDB.bookmarksSize()); while(it.hasNext()){ tag=(Tag) it.next(); prop.put("taglist_"+count+"_name", tag.getFriendlyName()); prop.put("taglist_"+count+"_tag", tag.getTagName()); prop.put("taglist_"+count+"_num", tag.size()); count++; } prop.put("taglist", count); count=0; if(!tagName.equals("")){ it=switchboard.bookmarksDB.getBookmarksIterator(tagName, isAdmin); }else{ it=switchboard.bookmarksDB.getBookmarksIterator(isAdmin); } bookmarksDB.Bookmark bookmark; //skip the first entries (display next page) count=0; while(count < start && it.hasNext()){ it.next(); count++; } count=0; HashSet tags; Iterator tagsIt; int tagCount; while(count<max_count && it.hasNext()){ bookmark=switchboard.bookmarksDB.getBookmark((String)it.next()); if(bookmark!=null){ prop.put("bookmarks_"+count+"_link", bookmark.getUrl()); prop.put("bookmarks_"+count+"_title", bookmark.getTitle()); prop.put("bookmarks_"+count+"_description", bookmark.getDescription()); prop.put("bookmarks_"+count+"_public", (bookmark.getPublic()? 1:0)); //List Tags. tags=bookmark.getTags(); tagsIt=tags.iterator(); tagCount=0; while(tagsIt.hasNext()){ prop.put("bookmarks_"+count+"_tags_"+tagCount+"_tag", tagsIt.next()); tagCount++; } prop.put("bookmarks_"+count+"_tags", tagCount); prop.put("bookmarks_"+count+"_hash", bookmark.getUrlHash()); count++; } } prop.put("tag", tagName); prop.put("start", start); if(it.hasNext()){ prop.put("next-page", 1); prop.put("next-page_start", start+max_count); prop.put("next-page_tag", tagName); prop.put("next-page_num", max_count); } if(start >= max_count){ start=start-max_count; if(start <0){ start=0; } prop.put("prev-page", 1); prop.put("prev-page_start", start); prop.put("prev-page_tag", tagName); prop.put("prev-page_num", max_count); } prop.put("bookmarks", count); return prop; }
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) { serverObjects prop = new serverObjects(); plasmaSwitchboard switchboard = (plasmaSwitchboard) env; int max_count=10; String tagName=""; int start=0; boolean isAdmin=switchboard.verifyAuthentication(header, true); //defaultvalues prop.put("mode", 0); if(isAdmin){ prop.put("mode", 1); } prop.put("mode_edit", 0); prop.put("mode_title", ""); prop.put("mode_description", ""); prop.put("mode_url", ""); prop.put("mode_tags", ""); prop.put("mode_public", 1); //1=is public if(post != null){ if(!isAdmin){ if(post.containsKey("login")){ prop.put("AUTHENTICATE","admin log-in"); } }else if(post.containsKey("mode")){ String mode=(String) post.get("mode"); if(mode.equals("add")){ prop.put("mode", 2); }else if(mode.equals("importxml")){ prop.put("mode", 3); }else if(mode.equals("importbookmarks")){ prop.put("mode", 4); } }else if(post.containsKey("add")){ //add an Entry String url=(String) post.get("url"); String title=(String) post.get("title"); String description=(String) post.get("description"); String tagsString = (String)post.get("tags"); if(tagsString.equals("")){ tagsString="unsorted"; //defaulttag } HashSet tags=listManager.string2hashset(tagsString); bookmarksDB.Bookmark bookmark = switchboard.bookmarksDB.createBookmark(url); if(bookmark != null){ bookmark.setProperty(bookmarksDB.Bookmark.BOOKMARK_TITLE, title); bookmark.setProperty(bookmarksDB.Bookmark.BOOKMARK_DESCRIPTION, description); if(((String) post.get("public")).equals("public")){ bookmark.setPublic(true); // create a news message HashMap map = new HashMap(); map.put("url", url.replace(',', '|')); map.put("title", title.replace(',', ' ')); map.put("description", description.replace(',', ' ')); map.put("tags", tagsString.replace(',', ' ')); yacyCore.newsPool.publishMyNews(new yacyNewsRecord("bkmrkadd", map)); }else{ bookmark.setPublic(false); } bookmark.setTags(tags, true); switchboard.bookmarksDB.saveBookmark(bookmark); }else{ //ERROR } }else if(post.containsKey("edit")){ String urlHash=(String) post.get("edit"); prop.put("mode", 2); if (urlHash.length() == 0) { prop.put("mode_edit", 0); // create mode prop.put("mode_title", (String) post.get("title")); prop.put("mode_description", (String) post.get("description")); prop.put("mode_url", (String) post.get("url")); prop.put("mode_tags", (String) post.get("tags")); prop.put("mode_public", 0); } else { bookmarksDB.Bookmark bookmark = switchboard.bookmarksDB.getBookmark(urlHash); if (bookmark == null) { // try to get the bookmark from the LURL database plasmaCrawlLURL.Entry urlentry = switchboard.urlPool.loadedURL.load(urlHash, null); plasmaParserDocument document = null; if(urlentry != null){ document = switchboard.snippetCache.retrieveDocument(urlentry.url(), true); } if (urlentry != null) { prop.put("mode_edit", 0); // create mode prop.put("mode_title", urlentry.descr()); prop.put("mode_description", (document == null) ? urlentry.descr() : document.getMainLongTitle()); prop.put("mode_url", urlentry.url()); prop.put("mode_tags", (document == null) ? "" : document.getKeywords(',')); prop.put("mode_public", 0); } } else { // get from the bookmark database prop.put("mode_edit", 1); // edit mode prop.put("mode_title", bookmark.getTitle()); prop.put("mode_description", bookmark.getDescription()); prop.put("mode_url", bookmark.getUrl()); prop.put("mode_tags", bookmark.getTagsString()); if (bookmark.getPublic()) { prop.put("mode_public", 1); } else { prop.put("mode_public", 0); } } } }else if(post.containsKey("bookmarksfile")){ boolean isPublic=false; if(((String) post.get("public")).equals("public")){ isPublic=true; } String tags=(String) post.get("tags"); if(tags.equals("")){ tags="unsorted"; } try { File file=new File((String)post.get("bookmarksfile")); switchboard.bookmarksDB.importFromBookmarks(new URL(file) , new String((byte[])post.get("bookmarksfile$file")), tags, isPublic); } catch (MalformedURLException e) {} }else if(post.containsKey("xmlfile")){ boolean isPublic=false; if(((String) post.get("public")).equals("public")){ isPublic=true; } switchboard.bookmarksDB.importFromXML(new String((byte[])post.get("xmlfile$file")), isPublic); }else if(post.containsKey("delete")){ String urlHash=(String) post.get("delete"); switchboard.bookmarksDB.removeBookmark(urlHash); } if(post.containsKey("tag")){ tagName=(String) post.get("tag"); } if(post.containsKey("start")){ start=Integer.parseInt((String) post.get("start")); } if(post.containsKey("num")){ max_count=Integer.parseInt((String) post.get("num")); } } Iterator it=switchboard.bookmarksDB.getTagIterator(isAdmin); int count=0; bookmarksDB.Tag tag; prop.put("num-bookmarks", switchboard.bookmarksDB.bookmarksSize()); while(it.hasNext()){ tag=(Tag) it.next(); prop.put("taglist_"+count+"_name", tag.getFriendlyName()); prop.put("taglist_"+count+"_tag", tag.getTagName()); prop.put("taglist_"+count+"_num", tag.size()); count++; } prop.put("taglist", count); count=0; if(!tagName.equals("")){ it=switchboard.bookmarksDB.getBookmarksIterator(tagName, isAdmin); }else{ it=switchboard.bookmarksDB.getBookmarksIterator(isAdmin); } bookmarksDB.Bookmark bookmark; //skip the first entries (display next page) count=0; while(count < start && it.hasNext()){ it.next(); count++; } count=0; HashSet tags; Iterator tagsIt; int tagCount; while(count<max_count && it.hasNext()){ bookmark=switchboard.bookmarksDB.getBookmark((String)it.next()); if(bookmark!=null){ prop.put("bookmarks_"+count+"_link", bookmark.getUrl()); prop.put("bookmarks_"+count+"_title", bookmark.getTitle()); prop.put("bookmarks_"+count+"_description", bookmark.getDescription()); prop.put("bookmarks_"+count+"_public", (bookmark.getPublic()? 1:0)); //List Tags. tags=bookmark.getTags(); tagsIt=tags.iterator(); tagCount=0; while(tagsIt.hasNext()){ prop.put("bookmarks_"+count+"_tags_"+tagCount+"_tag", tagsIt.next()); tagCount++; } prop.put("bookmarks_"+count+"_tags", tagCount); prop.put("bookmarks_"+count+"_hash", bookmark.getUrlHash()); count++; } } prop.put("tag", tagName); prop.put("start", start); if(it.hasNext()){ prop.put("next-page", 1); prop.put("next-page_start", start+max_count); prop.put("next-page_tag", tagName); prop.put("next-page_num", max_count); } if(start >= max_count){ start=start-max_count; if(start <0){ start=0; } prop.put("prev-page", 1); prop.put("prev-page_start", start); prop.put("prev-page_tag", tagName); prop.put("prev-page_num", max_count); } prop.put("bookmarks", count); return prop; }
diff --git a/parser/src/main/java/org/apache/abdera/parser/stax/FOMElement.java b/parser/src/main/java/org/apache/abdera/parser/stax/FOMElement.java index 1c8cc78b..f70fa0af 100644 --- a/parser/src/main/java/org/apache/abdera/parser/stax/FOMElement.java +++ b/parser/src/main/java/org/apache/abdera/parser/stax/FOMElement.java @@ -1,663 +1,664 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.parser.stax; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Locale; import javax.activation.MimeType; import javax.activation.MimeTypeParseException; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; //import javax.xml.stream.XMLStreamWriter; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.Base; import org.apache.abdera.model.Content; import org.apache.abdera.model.Div; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.ElementWrapper; import org.apache.abdera.model.Link; import org.apache.abdera.model.Text; import org.apache.abdera.parser.ParseException; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.ParserOptions; import org.apache.abdera.parser.stax.util.FOMElementIteratorWrapper; import org.apache.abdera.parser.stax.util.FOMList; import org.apache.abdera.util.Constants; import org.apache.abdera.util.MimeTypeHelper; import org.apache.abdera.util.URIHelper; import org.apache.abdera.util.iri.IRI; import org.apache.abdera.util.iri.IRISyntaxException; import org.apache.axiom.om.OMAttribute; import org.apache.axiom.om.OMComment; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.OMOutputFormat; import org.apache.axiom.om.OMProcessingInstruction; import org.apache.axiom.om.OMText; import org.apache.axiom.om.OMXMLParserWrapper; import org.apache.axiom.om.impl.llom.OMElementImpl; public class FOMElement extends OMElementImpl implements Element, OMElement, Constants { private static final long serialVersionUID = 8024257594220911953L; public FOMElement(QName qname) { super(qname, null, null); } public FOMElement( String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } public FOMElement( QName qname, OMContainer parent, OMFactory factory) throws OMException { super( qname.getLocalPart(), getOrCreateNamespace(qname,parent,factory), parent,factory); } public FOMElement( QName qname, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super( qname.getLocalPart(), factory.createOMNamespace( qname.getNamespaceURI(), qname.getPrefix()), parent, builder, factory); } private static OMNamespace getOrCreateNamespace( QName qname, OMContainer parent, OMFactory factory) { String namespace = qname.getNamespaceURI(); String prefix = qname.getPrefix(); if (parent != null && parent instanceof OMElement) { OMNamespace ns = ((OMElement)parent).findNamespace(namespace, prefix); if (ns != null) return ns; } return factory.createOMNamespace( qname.getNamespaceURI(), qname.getPrefix()); } protected Element getWrapped(Element internal) { if (internal == null) return null; FOMFactory factory = (FOMFactory) getFactory(); return factory.getElementWrapper(internal); } @SuppressWarnings("unchecked") public <T extends Base>T getParentElement() { T parent = (T)super.getParent(); return (T) ((parent instanceof Element) ? getWrapped((Element)parent) : parent); } protected void setParentDocument(Document parent) { super.setParent((OMContainer)parent); } public void setParentElement(Element parent) { if (parent instanceof ElementWrapper) { parent = ((ElementWrapper)parent).getInternal(); } super.setParent((FOMElement)parent); } @SuppressWarnings("unchecked") public <T extends Element>T getPreviousSibling() { OMNode el = this.getPreviousOMSibling(); while (el != null) { if (el instanceof Element) return (T)getWrapped((Element)el); else el = el.getPreviousOMSibling(); } return null; } @SuppressWarnings("unchecked") public <T extends Element>T getNextSibling() { OMNode el = this.getNextOMSibling(); while (el != null) { if (el instanceof Element) return (T)getWrapped((Element)el); else el = el.getNextOMSibling(); } return null; } @SuppressWarnings("unchecked") public <T extends Element>T getFirstChild() { return (T)getWrapped((Element)this.getFirstElement()); } @SuppressWarnings("unchecked") public <T extends Element>T getPreviousSibling(QName qname) { Element el = getPreviousSibling(); while (el != null) { OMElement omel = (OMElement) el; if (omel.getQName().equals(qname)) return (T)getWrapped((Element)omel); el = el.getPreviousSibling(); } return null; } @SuppressWarnings("unchecked") public <T extends Element>T getNextSibling(QName qname) { Element el = getNextSibling(); while (el != null) { OMElement omel = (OMElement) el; if (omel.getQName().equals(qname)) return (T)getWrapped((Element)omel); el = el.getNextSibling(); } return null; } @SuppressWarnings("unchecked") public <T extends Element>T getFirstChild(QName qname) { return (T)getWrapped((Element)this.getFirstChildWithName(qname)); } public String getLanguage() { return getAttributeValue(LANG); } public void setLanguage(String language) { setAttributeValue(LANG,language); } public IRI getBaseUri() throws IRISyntaxException { IRI uri = _getUriValue(getAttributeValue(BASE)); if (URIHelper.isJavascriptUri(uri) || URIHelper.isMailtoUri(uri)) { uri = null; } if (uri == null) { if (parent instanceof Element) { uri = ((Element)parent).getBaseUri(); } else if (parent instanceof Document) { uri = ((Document)parent).getBaseUri(); } } return uri; } public IRI getResolvedBaseUri() throws IRISyntaxException { IRI baseUri = null; IRI uri = _getUriValue(getAttributeValue(BASE)); if (URIHelper.isJavascriptUri(uri) || URIHelper.isMailtoUri(uri)) { uri = null; } if (parent instanceof Element) baseUri = ((Element)parent).getResolvedBaseUri(); else if (parent instanceof Document) baseUri = ((Document)parent).getBaseUri(); if (uri != null && baseUri != null) { uri = baseUri.resolve(uri); } else if (uri == null) { uri = baseUri; } return uri; } public void setBaseUri(IRI base) { setAttributeValue(BASE,_getStringValue(base)); } public void setBaseUri(String base) throws IRISyntaxException { setBaseUri((base != null) ? new IRI(base) : null); } public String getAttributeValue(QName qname) { OMAttribute attr = getAttribute(qname); return (attr != null) ? attr.getAttributeValue() : null; } public void setAttributeValue(QName qname, String value) { OMAttribute attr = this.getAttribute(qname); if (attr != null && value != null) { attr.setAttributeValue(value); } else { if (value != null) { if (qname.getNamespaceURI() != null) { attr = factory.createOMAttribute( qname.getLocalPart(), factory.createOMNamespace( qname.getNamespaceURI(), qname.getPrefix()), value); } else { attr = factory.createOMAttribute( qname.getLocalPart(), null, value); } addAttribute(attr); } else { removeAttribute(attr); } } } @SuppressWarnings("unchecked") protected <E extends Element>List<E> _getChildrenAsSet(QName qname) { FOMFactory factory = (FOMFactory) getFactory(); return new FOMList(new FOMElementIteratorWrapper( factory,getChildrenWithName(qname))); } protected void _setChild(QName qname, OMElement element) { OMElement e = getFirstChildWithName(qname); if (e == null && element != null) { addChild(element); } else if (e != null && element != null) { e.insertSiblingBefore(element); e.discard(); } else if (e != null && element == null) { e.discard(); } } protected IRI _getUriValue(String v) throws IRISyntaxException { return (v != null) ? new IRI(v) : null; } protected String _getStringValue(IRI uri) { return (uri != null) ? uri.toString() : null; } protected IRI _resolve(IRI base, IRI value) throws IRISyntaxException { if (value == null) return null; if ("".equals(value.toString()) || "#".equals(value.toString()) || ".".equals(value.toString()) || "./".equals(value.toString())) return base; if (base == null) return value; if ("".equals(base.getPath())) base = base.resolve("/"); IRI resolved = (base != null) ? base.resolve(value) : value; return resolved; } public void writeTo(OutputStream out) throws IOException { writeTo(new OutputStreamWriter(out)); } public void writeTo(java.io.Writer writer) throws IOException { try { OMOutputFormat outputFormat = new OMOutputFormat(); if (getDocument() != null && getDocument().getCharset() != null) outputFormat.setCharSetEncoding(getDocument().getCharset()); serialize(writer, outputFormat); } catch (XMLStreamException e) { throw new FOMException(e); } } @SuppressWarnings("unchecked") public <T extends Element>Document<T> getDocument() { Document<T> document = null; if (parent != null) { if (parent instanceof Element) { document = ((Element)parent).getDocument(); } else if (parent instanceof Document) { document = (Document<T>) parent; } } return document; } public String getAttributeValue(String name) { return getAttributeValue(new QName(name)); } public void setAttributeValue(String name, String value) { setAttributeValue(new QName(name), value); } protected void _setElementValue(QName qname, String value) { OMElement element = this.getFirstChildWithName(qname); if (element != null && value != null) { element.setText(value); } else if (element != null && value == null) { for (Iterator i = element.getChildren(); i.hasNext();) { OMNode node = (OMNode) i.next(); node.discard(); } } else if (element == null && value != null ) { element = factory.createOMElement(qname, this); element.setText(value); this.addChild(element); } } protected String _getElementValue(QName qname) { String value = null; OMElement element = this.getFirstChildWithName(qname); if (element != null) value = element.getText(); return value; } @SuppressWarnings("unchecked") protected <T extends Text>T getTextElement(QName qname) { return (T)getFirstChildWithName(qname); } protected <T extends Text>void setTextElement(QName qname, T text, boolean many) { if (text != null) { if (!many) { OMElement el = getFirstChildWithName(qname); if (el != null) el.discard(); } _setChild(qname, (OMElement)text); } else _removeChildren(qname, false); } protected Text setTextText(QName qname, String value) { if (value == null) { setTextElement(qname, null, false); return null; } FOMFactory fomfactory = (FOMFactory) factory; Text text = fomfactory.newText(qname, Text.Type.TEXT); text.setValue(value); setTextElement(qname, text, false); return text; } protected Text setHtmlText(QName qname, String value, IRI baseUri) { if (value == null) { setTextElement(qname, null, false); return null; } FOMFactory fomfactory = (FOMFactory) factory; Text text = fomfactory.newText(qname, Text.Type.HTML); if (baseUri != null) text.setBaseUri(baseUri); text.setValue(value); setTextElement(qname, text, false); return text; } protected Text setXhtmlText(QName qname, String value, IRI baseUri) { if (value == null) { setTextElement(qname, null, false); return null; } FOMFactory fomfactory = (FOMFactory) factory; Text text = fomfactory.newText(qname, Text.Type.XHTML); if (baseUri != null) text.setBaseUri(baseUri); text.setValue(value); setTextElement(qname, text, false); return text; } protected Text setXhtmlText(QName qname, Div value, IRI baseUri) { if (value == null) { setTextElement(qname, null, false); return null; } FOMFactory fomfactory = (FOMFactory) factory; Text text = fomfactory.newText(qname, Text.Type.XHTML); if (baseUri != null) text.setBaseUri(baseUri); text.setValueElement(value); setTextElement(qname, text, false); return text; } public String getText() { StringBuffer buf = new StringBuffer(); Iterator i = getChildren(); while (i.hasNext()) { OMNode node = (OMNode) i.next(); if (node instanceof OMText) { buf.append(((OMText)node).getText()); } else { // for now, let's ignore other elements. eventually, we // should make this work like innerHTML in browsers... stripping // out all markup but leaving all text, even in child nodes } } return buf.toString(); } protected String getText(QName qname) { Text text = getTextElement(qname); return (text != null) ? text.getValue() : null; } public List<QName> getAttributes() { List<QName> list = new ArrayList<QName>(); for (Iterator i = getAllAttributes(); i.hasNext();) { OMAttribute attr = (OMAttribute) i.next(); list.add(attr.getQName()); } return Collections.unmodifiableList(list); } public List<QName> getExtensionAttributes() { List<QName> list = new ArrayList<QName>(); for (Iterator i = getAllAttributes(); i.hasNext();) { OMAttribute attr = (OMAttribute) i.next(); String namespace = (attr.getNamespace() != null) ? attr.getNamespace().getName() : ""; if (!namespace.equals(getNamespace().getName()) && !namespace.equals("")) list.add(attr.getQName()); } return Collections.unmodifiableList(list); } protected Element _parse(String value, IRI baseUri) throws ParseException, IRISyntaxException { if (value == null) return null; FOMFactory fomfactory = (FOMFactory) factory; Parser parser = fomfactory.newParser(); ByteArrayInputStream bais = new ByteArrayInputStream(value.getBytes()); ParserOptions options = parser.getDefaultParserOptions(); options.setCharset(getXMLStreamReader().getCharacterEncodingScheme()); options.setFactory(fomfactory); Document doc = parser.parse(bais, (baseUri != null) ? baseUri.toString() : null, options); return doc.getRoot(); } public void removeAttribute(QName qname) { OMAttribute attr = getAttribute(qname); if (attr != null) removeAttribute(attr); } public void removeAttribute(String name) { removeAttribute(getAttribute(new QName(name))); } protected void _removeChildren(QName qname, boolean many) { if (many) { for (Iterator i = getChildrenWithName(qname); i.hasNext();) { OMElement element = (OMElement) i.next(); element.discard(); } } else { OMElement element = getFirstChildWithName(qname); if (element != null) element.discard(); } } protected void _removeAllChildren() { for (Iterator i = getChildren(); i.hasNext();) { OMNode node = (OMNode) i.next(); node.discard(); } } @SuppressWarnings("unchecked") public Object clone() { OMElement el = _create(this); _copyElement(this, el); return el; } protected OMElement _copyElement(OMElement src, OMElement dest) { for (Iterator i = src.getAllAttributes(); i.hasNext();) { OMAttribute attr = (OMAttribute) i.next(); + dest.addAttribute(attr); dest.addAttribute( - attr.getLocalName(), - attr.getAttributeValue(), - (attr.getNamespace() != null) ? - dest.declareNamespace(attr.getNamespace()) : null); + factory.createOMAttribute( + attr.getLocalName(), + attr.getNamespace(), + attr.getAttributeValue())); } for (Iterator i = src.getChildren(); i.hasNext();) { OMNode node = (OMNode) i.next(); if (node.getType() == OMNode.ELEMENT_NODE) { OMElement element = (OMElement) node; OMElement child = _create(element); if (child != null) { _copyElement(element, child); dest.addChild(child); } } else if (node.getType() == OMNode.CDATA_SECTION_NODE) { OMText text = (OMText) node; factory.createOMText(dest,text.getText(), OMNode.CDATA_SECTION_NODE); } else if (node.getType() == OMNode.TEXT_NODE) { OMText text = (OMText) node; factory.createOMText(dest,text.getText()); } else if (node.getType() == OMNode.COMMENT_NODE) { OMComment comment = (OMComment) node; factory.createOMComment(dest, comment.getValue()); } else if (node.getType() == OMNode.PI_NODE) { OMProcessingInstruction pi = (OMProcessingInstruction) node; factory.createOMProcessingInstruction(dest, pi.getTarget(), pi.getValue()); } else if (node.getType() == OMNode.SPACE_NODE) { OMText text = (OMText) node; factory.createOMText(dest, text.getText(), OMNode.SPACE_NODE); } else if (node.getType() == OMNode.ENTITY_REFERENCE_NODE) { OMText text = (OMText) node; factory.createOMText(dest, text.getText(), OMNode.ENTITY_REFERENCE_NODE); } } return dest; } protected OMElement _create(OMElement src) { OMElement el = null; FOMFactory fomfactory = (FOMFactory)factory; Object obj = null; if (src instanceof Content) obj = ((Content)src).getContentType(); if (src instanceof Text) obj = ((Text)src).getTextType(); el = fomfactory.createElement( src.getQName(), (OMContainer) fomfactory.newDocument(), factory, obj); return el; } public Factory getFactory() { return (Factory) this.factory; } // This appears to no longer be necessary with Axiom 1.2 // // @Override // protected void internalSerialize( // XMLStreamWriter writer, // boolean bool) throws XMLStreamException { // if (this.getNamespace() != null) { // this.declareNamespace(this.getNamespace()); // } // Iterator i = this.getAllAttributes(); // while (i.hasNext()) { // OMAttribute attr = (OMAttribute) i.next(); // if (attr.getNamespace() != null) // this.declareNamespace(attr.getNamespace()); // } // super.internalSerialize(writer, bool); // } public void addComment(String value) { factory.createOMComment(this, value); } public Locale getLocale() { String tag = getLanguage(); if (tag == null || tag.length() == 0) return null; String[] tokens = tag.split("-"); Locale locale = null; switch(tokens.length) { case 0: break; case 1: locale = new Locale(tokens[0]); break; case 2: locale = new Locale(tokens[0],tokens[1]); break; default: locale = new Locale(tokens[0],tokens[1],tokens[2]); break; } return locale; } protected Link selectLink( List<Link> links, String type, String hreflang) throws MimeTypeParseException { for (Link link : links) { MimeType mt = link.getMimeType(); boolean typematch = MimeTypeHelper.isMatch( (mt != null) ? mt.toString() : null, type); boolean langmatch = "*".equals(hreflang) || ((hreflang != null) ? hreflang.equals(link.getHrefLang()) : link.getHrefLang() == null); if (typematch && langmatch) return link; } return null; } public void declareNS(String prefix, String uri) { super.declareNamespace(uri,prefix); } }
false
true
protected OMElement _copyElement(OMElement src, OMElement dest) { for (Iterator i = src.getAllAttributes(); i.hasNext();) { OMAttribute attr = (OMAttribute) i.next(); dest.addAttribute( attr.getLocalName(), attr.getAttributeValue(), (attr.getNamespace() != null) ? dest.declareNamespace(attr.getNamespace()) : null); } for (Iterator i = src.getChildren(); i.hasNext();) { OMNode node = (OMNode) i.next(); if (node.getType() == OMNode.ELEMENT_NODE) { OMElement element = (OMElement) node; OMElement child = _create(element); if (child != null) { _copyElement(element, child); dest.addChild(child); } } else if (node.getType() == OMNode.CDATA_SECTION_NODE) { OMText text = (OMText) node; factory.createOMText(dest,text.getText(), OMNode.CDATA_SECTION_NODE); } else if (node.getType() == OMNode.TEXT_NODE) { OMText text = (OMText) node; factory.createOMText(dest,text.getText()); } else if (node.getType() == OMNode.COMMENT_NODE) { OMComment comment = (OMComment) node; factory.createOMComment(dest, comment.getValue()); } else if (node.getType() == OMNode.PI_NODE) { OMProcessingInstruction pi = (OMProcessingInstruction) node; factory.createOMProcessingInstruction(dest, pi.getTarget(), pi.getValue()); } else if (node.getType() == OMNode.SPACE_NODE) { OMText text = (OMText) node; factory.createOMText(dest, text.getText(), OMNode.SPACE_NODE); } else if (node.getType() == OMNode.ENTITY_REFERENCE_NODE) { OMText text = (OMText) node; factory.createOMText(dest, text.getText(), OMNode.ENTITY_REFERENCE_NODE); } } return dest; }
protected OMElement _copyElement(OMElement src, OMElement dest) { for (Iterator i = src.getAllAttributes(); i.hasNext();) { OMAttribute attr = (OMAttribute) i.next(); dest.addAttribute(attr); dest.addAttribute( factory.createOMAttribute( attr.getLocalName(), attr.getNamespace(), attr.getAttributeValue())); } for (Iterator i = src.getChildren(); i.hasNext();) { OMNode node = (OMNode) i.next(); if (node.getType() == OMNode.ELEMENT_NODE) { OMElement element = (OMElement) node; OMElement child = _create(element); if (child != null) { _copyElement(element, child); dest.addChild(child); } } else if (node.getType() == OMNode.CDATA_SECTION_NODE) { OMText text = (OMText) node; factory.createOMText(dest,text.getText(), OMNode.CDATA_SECTION_NODE); } else if (node.getType() == OMNode.TEXT_NODE) { OMText text = (OMText) node; factory.createOMText(dest,text.getText()); } else if (node.getType() == OMNode.COMMENT_NODE) { OMComment comment = (OMComment) node; factory.createOMComment(dest, comment.getValue()); } else if (node.getType() == OMNode.PI_NODE) { OMProcessingInstruction pi = (OMProcessingInstruction) node; factory.createOMProcessingInstruction(dest, pi.getTarget(), pi.getValue()); } else if (node.getType() == OMNode.SPACE_NODE) { OMText text = (OMText) node; factory.createOMText(dest, text.getText(), OMNode.SPACE_NODE); } else if (node.getType() == OMNode.ENTITY_REFERENCE_NODE) { OMText text = (OMText) node; factory.createOMText(dest, text.getText(), OMNode.ENTITY_REFERENCE_NODE); } } return dest; }
diff --git a/src/be/ibridge/kettle/trans/step/combinationlookup/CombinationLookup.java b/src/be/ibridge/kettle/trans/step/combinationlookup/CombinationLookup.java index 2c0066d3..5bd965ca 100644 --- a/src/be/ibridge/kettle/trans/step/combinationlookup/CombinationLookup.java +++ b/src/be/ibridge/kettle/trans/step/combinationlookup/CombinationLookup.java @@ -1,343 +1,343 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.trans.step.combinationlookup; import java.util.Hashtable; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.database.Database; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleStepException; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStep; import be.ibridge.kettle.trans.step.StepDataInterface; import be.ibridge.kettle.trans.step.StepInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; /** * Manages or loooks up information in a junk dimension.<p> * <p> 1) Lookup combination field1..n in a dimension<p> 2) If this combination exists, return technical key<p> 3) If this combination doesn't exist, insert & return technical key<p> 4) if replace is Y, remove all key fields from output.<p> <p> * @author Matt * @since 22-jul-2003 * */ public class CombinationLookup extends BaseStep implements StepInterface { private CombinationLookupMeta meta; private CombinationLookupData data; public CombinationLookup(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); meta=(CombinationLookupMeta)getStepMeta().getStepMetaInterface(); data=(CombinationLookupData)stepDataInterface; } private Value lookupInCache(Row row) { // try to find the row in the cache... // It looks using Row.hashcode() & Row.equals() Value tk = (Value) data.cache.get(row); return tk; } private void storeInCache(Row row, Value tk) { data.cache.put(row, tk); } private void lookupValues(Row row) throws KettleException { Value val_hash = null; Value val_key = null; if (first) { debug="First: lookup keys etc"; first=false; // Lookup values data.keynrs = new int[meta.getKeyField().length]; for (int i=0;i<meta.getKeyField().length;i++) { data.keynrs[i]=row.searchValueIndex(meta.getKeyField()[i]); if (data.keynrs[i]<0) // couldn't find field! { throw new KettleStepException(Messages.getString("CombinationLookup.Exception.FieldNotFound",meta.getKeyField()[i])); //$NON-NLS-1$ //$NON-NLS-2$ } } // Sort lookup values in reverse so we can delete from back to front! if (meta.replaceFields()) { int x,y; int size=meta.getKeyField().length; int nr1, nr2; for (x=0;x<size;x++) { for (y=0;y<size-1;y++) { nr1 = data.keynrs[y]; nr2 = data.keynrs[y+1]; if (nr2>nr1) // reverse sort: swap values... { int nr_dummy = data.keynrs[y]; String key_dummy = meta.getKeyField()[y]; String keylookup_dummy = meta.getKeyLookup()[y]; data.keynrs[y] = data.keynrs[y+1]; meta.getKeyField()[y] = meta.getKeyField()[y+1]; meta.getKeyLookup()[y] = meta.getKeyLookup()[y+1]; data.keynrs[y+1] = nr_dummy; meta.getKeyField()[y+1] = key_dummy; meta.getKeyLookup()[y+1] = keylookup_dummy; } } } } debug="First: setCombiLookup"; data.db.setCombiLookup(meta.getTablename(), meta.getKeyLookup(), meta.getTechnicalKeyField(), meta.useHash(), meta.getHashField() ); } debug="Create lookup row lu"; Row lu = new Row(); for (int i=0;i<meta.getKeyField().length;i++) { lu.addValue( row.getValue(data.keynrs[i]) ); // KEYi = ? } debug="Use hashcode?"; if (meta.useHash()) { val_hash = new Value(meta.getHashField(), (long)lu.hashCode()); lu.clear(); lu.addValue(val_hash); } else { lu.clear(); } debug="Add values to lookup row lu"; for (int i=0;i<meta.getKeyField().length;i++) { Value parval = row.getValue(data.keynrs[i]); lu.addValue( parval ); // KEYi = ? lu.addValue( parval ); // KEYi IS NULL or ? IS NULL } debug="Check the cache"; // Before doing the actual lookup in the database, see if it's not in the cache... val_key = lookupInCache(lu); if (val_key==null) { debug="Set lookup values"; data.db.setValuesLookup(lu); debug="Get the row back"; Row add=data.db.getLookup(); linesInput++; if (add==null) // The dimension entry was not found, we need to add it! { debug="New entry: calc autoinc/sequence/..."; // First try to use an AUTOINCREMENT field boolean autoinc=false; if (meta.getDatabase().supportsAutoinc() && meta.isUseAutoinc()) { autoinc=true; val_key=new Value(meta.getTechnicalKeyField(), 0.0); // value to accept new key... } else // Try to get the value by looking at a SEQUENCE (oracle mostly) if (meta.getDatabase().supportsSequences() && meta.getSequenceFrom()!=null && meta.getSequenceFrom().length()>0) { val_key=data.db.getNextSequenceValue(meta.getSequenceFrom(), meta.getTechnicalKeyField()); if (val_key!=null && log.isRowLevel()) logRowlevel(Messages.getString("CombinationLookup.Log.FoundNextSequenceValue")+val_key.toString()); //$NON-NLS-1$ } else // Use our own sequence here... { // What's the next value for the technical key? val_key=new Value(meta.getTechnicalKeyField(), 0.0); // value to accept new key... data.db.getNextValue(getTransMeta().getCounters(), meta.getTablename(), val_key); } debug="New entry: calc tkFieldName"; String tkFieldName = meta.getTechnicalKeyField(); if (autoinc) tkFieldName=null; - if (meta.getSequenceFrom()!=null && meta.getSequenceFrom().length()>0) tkFieldName=null; + // if (meta.getSequenceFrom()!=null && meta.getSequenceFrom().length()>0) tkFieldName=null; debug="New entry: combiInsert"; data.db.combiInsert( row, meta.getTablename(), tkFieldName, autoinc, val_key, meta.getKeyLookup(), data.keynrs, meta.useHash(), meta.getHashField(), val_hash ); linesOutput++; log.logRowlevel(toString(), Messages.getString("CombinationLookup.Log.AddedDimensionEntry")+val_key); //$NON-NLS-1$ debug="New entry: Store in cache "; // Also store it in our Hashtable... storeInCache(lu, val_key); } else { debug="Found: store in cache"; val_key = add.getValue(0); // Only one value possible here... storeInCache(lu, val_key); } } debug="Replace fields?"; // See if we need to replace the fields with the technical key if (meta.replaceFields()) { for (int i=0;i<data.keynrs.length;i++) { row.removeValue(data.keynrs[i]); // safe because reverse sorted on index nr. } } debug="add TK"; // Add the technical key... row.addValue( val_key ); } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { Row r=getRow(); // Get row from input rowset & set row busy! if (r==null) // no more input to be expected... { setOutputDone(); return false; } try { lookupValues(r); // add new values to the row in rowset[0]. putRow(r); // copy row to output rowset(s); if ((linesRead>0) && (linesRead%Const.ROWS_UPDATE)==0) logBasic(Messages.getString("CombinationLookup.Log.LineNumber")+linesRead); //$NON-NLS-1$ } catch(KettleException e) { logError(Messages.getString("CombinationLookup.Log.ErrorInStepRunning")+e.getMessage()); //$NON-NLS-1$ setErrors(1); stopAll(); setOutputDone(); // signal end to receiver(s) return false; } return true; } public boolean init(StepMetaInterface sii, StepDataInterface sdi) { if (super.init(sii, sdi)) { data.cache=new Hashtable(); data.db=new Database(meta.getDatabase()); try { data.db.connect(); logBasic(Messages.getString("CombinationLookup.Log.ConnectedToDB")); //$NON-NLS-1$ data.db.setCommit(meta.getCommitSize()); return true; } catch(KettleDatabaseException dbe) { logError(Messages.getString("CombinationLookup.Log.UnableToConnectDB")+dbe.getMessage()); //$NON-NLS-1$ } } return false; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta = (CombinationLookupMeta)smi; data = (CombinationLookupData)sdi; data.db.disconnect(); super.dispose(smi, sdi); } // // Run is were the action happens! public void run() { logBasic(Messages.getString("CombinationLookup.Log.StartingToRun")); //$NON-NLS-1$ try { while (processRow(meta, data) && !isStopped()); } catch(Exception e) { logError(Messages.getString("CombinationLookup.Log.UnexpectedError")+debug+"' : "+e.toString()); //$NON-NLS-1$ //$NON-NLS-2$ setErrors(1); stopAll(); } finally { dispose(meta, data); markStop(); logSummary(); } } public String toString() { return this.getClass().getName(); } }
true
true
private void lookupValues(Row row) throws KettleException { Value val_hash = null; Value val_key = null; if (first) { debug="First: lookup keys etc"; first=false; // Lookup values data.keynrs = new int[meta.getKeyField().length]; for (int i=0;i<meta.getKeyField().length;i++) { data.keynrs[i]=row.searchValueIndex(meta.getKeyField()[i]); if (data.keynrs[i]<0) // couldn't find field! { throw new KettleStepException(Messages.getString("CombinationLookup.Exception.FieldNotFound",meta.getKeyField()[i])); //$NON-NLS-1$ //$NON-NLS-2$ } } // Sort lookup values in reverse so we can delete from back to front! if (meta.replaceFields()) { int x,y; int size=meta.getKeyField().length; int nr1, nr2; for (x=0;x<size;x++) { for (y=0;y<size-1;y++) { nr1 = data.keynrs[y]; nr2 = data.keynrs[y+1]; if (nr2>nr1) // reverse sort: swap values... { int nr_dummy = data.keynrs[y]; String key_dummy = meta.getKeyField()[y]; String keylookup_dummy = meta.getKeyLookup()[y]; data.keynrs[y] = data.keynrs[y+1]; meta.getKeyField()[y] = meta.getKeyField()[y+1]; meta.getKeyLookup()[y] = meta.getKeyLookup()[y+1]; data.keynrs[y+1] = nr_dummy; meta.getKeyField()[y+1] = key_dummy; meta.getKeyLookup()[y+1] = keylookup_dummy; } } } } debug="First: setCombiLookup"; data.db.setCombiLookup(meta.getTablename(), meta.getKeyLookup(), meta.getTechnicalKeyField(), meta.useHash(), meta.getHashField() ); } debug="Create lookup row lu"; Row lu = new Row(); for (int i=0;i<meta.getKeyField().length;i++) { lu.addValue( row.getValue(data.keynrs[i]) ); // KEYi = ? } debug="Use hashcode?"; if (meta.useHash()) { val_hash = new Value(meta.getHashField(), (long)lu.hashCode()); lu.clear(); lu.addValue(val_hash); } else { lu.clear(); } debug="Add values to lookup row lu"; for (int i=0;i<meta.getKeyField().length;i++) { Value parval = row.getValue(data.keynrs[i]); lu.addValue( parval ); // KEYi = ? lu.addValue( parval ); // KEYi IS NULL or ? IS NULL } debug="Check the cache"; // Before doing the actual lookup in the database, see if it's not in the cache... val_key = lookupInCache(lu); if (val_key==null) { debug="Set lookup values"; data.db.setValuesLookup(lu); debug="Get the row back"; Row add=data.db.getLookup(); linesInput++; if (add==null) // The dimension entry was not found, we need to add it! { debug="New entry: calc autoinc/sequence/..."; // First try to use an AUTOINCREMENT field boolean autoinc=false; if (meta.getDatabase().supportsAutoinc() && meta.isUseAutoinc()) { autoinc=true; val_key=new Value(meta.getTechnicalKeyField(), 0.0); // value to accept new key... } else // Try to get the value by looking at a SEQUENCE (oracle mostly) if (meta.getDatabase().supportsSequences() && meta.getSequenceFrom()!=null && meta.getSequenceFrom().length()>0) { val_key=data.db.getNextSequenceValue(meta.getSequenceFrom(), meta.getTechnicalKeyField()); if (val_key!=null && log.isRowLevel()) logRowlevel(Messages.getString("CombinationLookup.Log.FoundNextSequenceValue")+val_key.toString()); //$NON-NLS-1$ } else // Use our own sequence here... { // What's the next value for the technical key? val_key=new Value(meta.getTechnicalKeyField(), 0.0); // value to accept new key... data.db.getNextValue(getTransMeta().getCounters(), meta.getTablename(), val_key); } debug="New entry: calc tkFieldName"; String tkFieldName = meta.getTechnicalKeyField(); if (autoinc) tkFieldName=null; if (meta.getSequenceFrom()!=null && meta.getSequenceFrom().length()>0) tkFieldName=null; debug="New entry: combiInsert"; data.db.combiInsert( row, meta.getTablename(), tkFieldName, autoinc, val_key, meta.getKeyLookup(), data.keynrs, meta.useHash(), meta.getHashField(), val_hash ); linesOutput++; log.logRowlevel(toString(), Messages.getString("CombinationLookup.Log.AddedDimensionEntry")+val_key); //$NON-NLS-1$ debug="New entry: Store in cache "; // Also store it in our Hashtable... storeInCache(lu, val_key); } else { debug="Found: store in cache"; val_key = add.getValue(0); // Only one value possible here... storeInCache(lu, val_key); } } debug="Replace fields?"; // See if we need to replace the fields with the technical key if (meta.replaceFields()) { for (int i=0;i<data.keynrs.length;i++) { row.removeValue(data.keynrs[i]); // safe because reverse sorted on index nr. } } debug="add TK"; // Add the technical key... row.addValue( val_key ); }
private void lookupValues(Row row) throws KettleException { Value val_hash = null; Value val_key = null; if (first) { debug="First: lookup keys etc"; first=false; // Lookup values data.keynrs = new int[meta.getKeyField().length]; for (int i=0;i<meta.getKeyField().length;i++) { data.keynrs[i]=row.searchValueIndex(meta.getKeyField()[i]); if (data.keynrs[i]<0) // couldn't find field! { throw new KettleStepException(Messages.getString("CombinationLookup.Exception.FieldNotFound",meta.getKeyField()[i])); //$NON-NLS-1$ //$NON-NLS-2$ } } // Sort lookup values in reverse so we can delete from back to front! if (meta.replaceFields()) { int x,y; int size=meta.getKeyField().length; int nr1, nr2; for (x=0;x<size;x++) { for (y=0;y<size-1;y++) { nr1 = data.keynrs[y]; nr2 = data.keynrs[y+1]; if (nr2>nr1) // reverse sort: swap values... { int nr_dummy = data.keynrs[y]; String key_dummy = meta.getKeyField()[y]; String keylookup_dummy = meta.getKeyLookup()[y]; data.keynrs[y] = data.keynrs[y+1]; meta.getKeyField()[y] = meta.getKeyField()[y+1]; meta.getKeyLookup()[y] = meta.getKeyLookup()[y+1]; data.keynrs[y+1] = nr_dummy; meta.getKeyField()[y+1] = key_dummy; meta.getKeyLookup()[y+1] = keylookup_dummy; } } } } debug="First: setCombiLookup"; data.db.setCombiLookup(meta.getTablename(), meta.getKeyLookup(), meta.getTechnicalKeyField(), meta.useHash(), meta.getHashField() ); } debug="Create lookup row lu"; Row lu = new Row(); for (int i=0;i<meta.getKeyField().length;i++) { lu.addValue( row.getValue(data.keynrs[i]) ); // KEYi = ? } debug="Use hashcode?"; if (meta.useHash()) { val_hash = new Value(meta.getHashField(), (long)lu.hashCode()); lu.clear(); lu.addValue(val_hash); } else { lu.clear(); } debug="Add values to lookup row lu"; for (int i=0;i<meta.getKeyField().length;i++) { Value parval = row.getValue(data.keynrs[i]); lu.addValue( parval ); // KEYi = ? lu.addValue( parval ); // KEYi IS NULL or ? IS NULL } debug="Check the cache"; // Before doing the actual lookup in the database, see if it's not in the cache... val_key = lookupInCache(lu); if (val_key==null) { debug="Set lookup values"; data.db.setValuesLookup(lu); debug="Get the row back"; Row add=data.db.getLookup(); linesInput++; if (add==null) // The dimension entry was not found, we need to add it! { debug="New entry: calc autoinc/sequence/..."; // First try to use an AUTOINCREMENT field boolean autoinc=false; if (meta.getDatabase().supportsAutoinc() && meta.isUseAutoinc()) { autoinc=true; val_key=new Value(meta.getTechnicalKeyField(), 0.0); // value to accept new key... } else // Try to get the value by looking at a SEQUENCE (oracle mostly) if (meta.getDatabase().supportsSequences() && meta.getSequenceFrom()!=null && meta.getSequenceFrom().length()>0) { val_key=data.db.getNextSequenceValue(meta.getSequenceFrom(), meta.getTechnicalKeyField()); if (val_key!=null && log.isRowLevel()) logRowlevel(Messages.getString("CombinationLookup.Log.FoundNextSequenceValue")+val_key.toString()); //$NON-NLS-1$ } else // Use our own sequence here... { // What's the next value for the technical key? val_key=new Value(meta.getTechnicalKeyField(), 0.0); // value to accept new key... data.db.getNextValue(getTransMeta().getCounters(), meta.getTablename(), val_key); } debug="New entry: calc tkFieldName"; String tkFieldName = meta.getTechnicalKeyField(); if (autoinc) tkFieldName=null; // if (meta.getSequenceFrom()!=null && meta.getSequenceFrom().length()>0) tkFieldName=null; debug="New entry: combiInsert"; data.db.combiInsert( row, meta.getTablename(), tkFieldName, autoinc, val_key, meta.getKeyLookup(), data.keynrs, meta.useHash(), meta.getHashField(), val_hash ); linesOutput++; log.logRowlevel(toString(), Messages.getString("CombinationLookup.Log.AddedDimensionEntry")+val_key); //$NON-NLS-1$ debug="New entry: Store in cache "; // Also store it in our Hashtable... storeInCache(lu, val_key); } else { debug="Found: store in cache"; val_key = add.getValue(0); // Only one value possible here... storeInCache(lu, val_key); } } debug="Replace fields?"; // See if we need to replace the fields with the technical key if (meta.replaceFields()) { for (int i=0;i<data.keynrs.length;i++) { row.removeValue(data.keynrs[i]); // safe because reverse sorted on index nr. } } debug="add TK"; // Add the technical key... row.addValue( val_key ); }
diff --git a/src/main/java/org/atlasapi/remotesite/space/TheSpaceItemProcessor.java b/src/main/java/org/atlasapi/remotesite/space/TheSpaceItemProcessor.java index f46688a7c..a136369a5 100644 --- a/src/main/java/org/atlasapi/remotesite/space/TheSpaceItemProcessor.java +++ b/src/main/java/org/atlasapi/remotesite/space/TheSpaceItemProcessor.java @@ -1,266 +1,266 @@ package org.atlasapi.remotesite.space; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.metabroadcast.common.http.SimpleHttpClient; import com.metabroadcast.common.http.SimpleHttpRequest; import com.metabroadcast.common.intl.Countries; import java.util.Iterator; import org.atlasapi.media.TransportType; import org.atlasapi.media.entity.Clip; import org.atlasapi.media.entity.Content; import org.atlasapi.media.entity.Encoding; import org.atlasapi.media.entity.Episode; import org.atlasapi.media.entity.Item; import org.atlasapi.media.entity.Location; import org.atlasapi.media.entity.ParentRef; import org.atlasapi.media.entity.Policy; import org.atlasapi.media.entity.Series; import org.atlasapi.media.entity.Version; import org.atlasapi.persistence.content.ContentResolver; import org.atlasapi.persistence.content.ContentWriter; import org.atlasapi.persistence.logging.AdapterLog; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.joda.time.Duration; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.ISODateTimeFormat; /** */ public class TheSpaceItemProcessor { private final String BASE_CANONICAL_URI = "http://thespace.org/items/"; private final String EPISODE_TYPE = "episode"; // private final SimpleHttpClient client; private final AdapterLog log; private final ContentResolver contentResolver; private final ContentWriter contentWriter; public TheSpaceItemProcessor(SimpleHttpClient client, AdapterLog log, ContentResolver contentResolver, ContentWriter contentWriter) { this.client = client; this.log = log; this.contentResolver = contentResolver; this.contentWriter = contentWriter; } public void process(JsonNode item) throws Exception { ObjectMapper mapper = new ObjectMapper(); // String type = item.get("type").asText(); String pid = item.get("pid").asText(); // if (type.equals(EPISODE_TYPE)) { Episode episode = (Episode) contentResolver.findByCanonicalUris(ImmutableSet.of(getCanonicalUri(pid))).getFirstValue().valueOrNull(); if (episode == null) { episode = new Episode(); } makeEpisode(episode, item, mapper); } } private void makeEpisode(Episode episode, JsonNode node, ObjectMapper mapper) throws Exception { JsonNode pid = node.get("pid"); episode.setCanonicalUri(getCanonicalUri(pid.asText())); JsonNode title = node.get("title"); episode.setTitle(title.asText()); JsonNode position = node.get("position"); if (position != null) { episode.setEpisodeNumber(position.asInt()); } JsonNode long_synopsis = node.get("long_synopsis"); JsonNode medium_synopsis = node.get("medium_synopsis"); JsonNode short_synopsis = node.get("short_synopsis"); String synopsis = null; if (long_synopsis != null) { synopsis = long_synopsis.asText(); } else if (medium_synopsis != null) { synopsis = medium_synopsis.asText(); } else if (short_synopsis != null) { synopsis = short_synopsis.asText(); } episode.setDescription(synopsis); JsonNode image = node.get("image"); if (image != null) { JsonNode smallImage = image.get("depiction_320"); if (smallImage != null) { episode.setThumbnail(smallImage.asText()); } JsonNode bigImage = image.get("depiction_640"); if (bigImage != null) { episode.setImage(bigImage.asText()); } } Iterator<JsonNode> clips = node.get("available_clips").getElements(); while (clips.hasNext()) { String cPid = clips.next().get("pid").asText(); JsonNode clip = client.get(new SimpleHttpRequest<JsonNode>(TheSpaceUpdater.BASE_API_URL + "/items/" + cPid + ".json", new JSonNodeHttpResponseTransformer(mapper))); - episode.addClip(getClip(mapper, clip.get("clip"), episode)); + episode.addClip(getClip(mapper, clip.get("programme"), episode)); } Iterator<JsonNode> versions = node.get("versions").getElements(); while (versions.hasNext()) { String vPid = versions.next().get("pid").asText(); JsonNode version = client.get(new SimpleHttpRequest<JsonNode>(TheSpaceUpdater.BASE_API_URL + "/items/" + vPid + ".json", new JSonNodeHttpResponseTransformer(mapper))); episode.addVersion(getVersion(mapper, version.get("version"), episode)); } JsonNode parent = node.get("parent"); if (parent != null) { String pPid = parent.get("pid").asText(); Series series = (Series) contentResolver.findByCanonicalUris(ImmutableSet.of(getCanonicalUri(pPid))).getFirstValue().valueOrNull(); if (series == null) { series = new Series(); series.setChildRefs(ImmutableList.of(episode.childRef())); fillSeries(series, mapper, client.get(new SimpleHttpRequest<JsonNode>(TheSpaceUpdater.BASE_API_URL + "/items/" + pPid + ".json", new JSonNodeHttpResponseTransformer(mapper))).get("programme")); } else { series.setChildRefs(Iterables.concat(series.getChildRefs(), ImmutableList.of(episode.childRef()))); } episode.setParentRef(ParentRef.parentRefFrom(series)); contentWriter.createOrUpdate(series); } contentWriter.createOrUpdate(episode); } private Clip getClip(ObjectMapper mapper, JsonNode node, Content parent) throws Exception { Clip clip = new Clip(); JsonNode pid = node.get("pid"); clip.setCanonicalUri(getCanonicalUri(pid.asText())); JsonNode title = node.get("title"); clip.setTitle(title.asText()); JsonNode long_synopsis = node.get("long_synopsis"); JsonNode medium_synopsis = node.get("medium_synopsis"); JsonNode short_synopsis = node.get("short_synopsis"); String synopsis = null; if (long_synopsis != null) { synopsis = long_synopsis.asText(); } else if (medium_synopsis != null) { synopsis = medium_synopsis.asText(); } else if (short_synopsis != null) { synopsis = short_synopsis.asText(); } clip.setDescription(synopsis); JsonNode image = node.get("image"); if (image != null) { JsonNode smallImage = image.get("depiction_320"); if (smallImage != null) { clip.setThumbnail(smallImage.asText()); } JsonNode bigImage = image.get("depiction_640"); if (bigImage != null) { clip.setImage(bigImage.asText()); } } Iterator<JsonNode> versions = node.get("versions").getElements(); while (versions.hasNext()) { String vPid = versions.next().get("pid").asText(); JsonNode version = client.get(new SimpleHttpRequest<JsonNode>(TheSpaceUpdater.BASE_API_URL + "/items/" + vPid + ".json", new JSonNodeHttpResponseTransformer(mapper))); clip.addVersion(getVersion(mapper, version.get("version"), clip)); } return clip; } private Version getVersion(ObjectMapper mapper, JsonNode node, Item parent) { Version version = new Version(); JsonNode pid = node.get("pid"); version.setCanonicalUri(getCanonicalUri(pid.asText())); JsonNode duration = node.get("duration"); if (duration != null) { version.setDuration(Duration.standardSeconds(Integer.parseInt(duration.asText()))); } Iterator<JsonNode> availabilities = node.get("availabilities").getElements(); while (availabilities.hasNext()) { Encoding encoding = new Encoding(); Location location = new Location(); Policy policy = new Policy(); encoding.addAvailableAt(location); location.setAvailable(true); location.setTransportType(TransportType.LINK); location.setUri(parent.getCanonicalUri()); location.setPolicy(policy); policy.setRevenueContract(Policy.RevenueContract.FREE_TO_VIEW); policy.setAvailableCountries(ImmutableSet.of(Countries.ALL)); JsonNode availability = availabilities.next(); JsonNode start = availability.get("start_of_media_availability"); if (start != null) { policy.setAvailabilityStart(ISODateTimeFormat.dateTimeParser().parseDateTime(start.asText())); } JsonNode end = availability.get("end_of_media_availability"); if (end != null) { policy.setAvailabilityEnd(ISODateTimeFormat.dateTimeParser().parseDateTime(end.asText())); } version.addManifestedAs(encoding); } return version; } private Series fillSeries(Series series, ObjectMapper mapper, JsonNode node) throws Exception { JsonNode pid = node.get("pid"); series.setCanonicalUri(getCanonicalUri(pid.asText())); JsonNode title = node.get("title"); series.setTitle(title.asText()); JsonNode episodes = node.get("expected_child_count"); if (episodes != null) { series.setTotalEpisodes(episodes.asInt()); } JsonNode long_synopsis = node.get("long_synopsis"); JsonNode medium_synopsis = node.get("medium_synopsis"); JsonNode short_synopsis = node.get("short_synopsis"); String synopsis = null; if (long_synopsis != null) { synopsis = long_synopsis.asText(); } else if (medium_synopsis != null) { synopsis = medium_synopsis.asText(); } else if (short_synopsis != null) { synopsis = short_synopsis.asText(); } series.setDescription(synopsis); JsonNode image = node.get("image"); if (image != null) { JsonNode smallImage = image.get("depiction_320"); if (smallImage != null) { series.setThumbnail(smallImage.asText()); } JsonNode bigImage = image.get("depiction_640"); if (bigImage != null) { series.setImage(bigImage.asText()); } } Iterator<JsonNode> clips = node.get("available_clips").getElements(); while (clips.hasNext()) { String cPid = clips.next().get("pid").asText(); JsonNode clip = client.get(new SimpleHttpRequest<JsonNode>(TheSpaceUpdater.BASE_API_URL + "/items/" + cPid + ".json", new JSonNodeHttpResponseTransformer(mapper))); series.addClip(getClip(mapper, clip.get("programme"), series)); } return series; } private String getCanonicalUri(String pid) { return BASE_CANONICAL_URI + pid; } }
true
true
private void makeEpisode(Episode episode, JsonNode node, ObjectMapper mapper) throws Exception { JsonNode pid = node.get("pid"); episode.setCanonicalUri(getCanonicalUri(pid.asText())); JsonNode title = node.get("title"); episode.setTitle(title.asText()); JsonNode position = node.get("position"); if (position != null) { episode.setEpisodeNumber(position.asInt()); } JsonNode long_synopsis = node.get("long_synopsis"); JsonNode medium_synopsis = node.get("medium_synopsis"); JsonNode short_synopsis = node.get("short_synopsis"); String synopsis = null; if (long_synopsis != null) { synopsis = long_synopsis.asText(); } else if (medium_synopsis != null) { synopsis = medium_synopsis.asText(); } else if (short_synopsis != null) { synopsis = short_synopsis.asText(); } episode.setDescription(synopsis); JsonNode image = node.get("image"); if (image != null) { JsonNode smallImage = image.get("depiction_320"); if (smallImage != null) { episode.setThumbnail(smallImage.asText()); } JsonNode bigImage = image.get("depiction_640"); if (bigImage != null) { episode.setImage(bigImage.asText()); } } Iterator<JsonNode> clips = node.get("available_clips").getElements(); while (clips.hasNext()) { String cPid = clips.next().get("pid").asText(); JsonNode clip = client.get(new SimpleHttpRequest<JsonNode>(TheSpaceUpdater.BASE_API_URL + "/items/" + cPid + ".json", new JSonNodeHttpResponseTransformer(mapper))); episode.addClip(getClip(mapper, clip.get("clip"), episode)); } Iterator<JsonNode> versions = node.get("versions").getElements(); while (versions.hasNext()) { String vPid = versions.next().get("pid").asText(); JsonNode version = client.get(new SimpleHttpRequest<JsonNode>(TheSpaceUpdater.BASE_API_URL + "/items/" + vPid + ".json", new JSonNodeHttpResponseTransformer(mapper))); episode.addVersion(getVersion(mapper, version.get("version"), episode)); } JsonNode parent = node.get("parent"); if (parent != null) { String pPid = parent.get("pid").asText(); Series series = (Series) contentResolver.findByCanonicalUris(ImmutableSet.of(getCanonicalUri(pPid))).getFirstValue().valueOrNull(); if (series == null) { series = new Series(); series.setChildRefs(ImmutableList.of(episode.childRef())); fillSeries(series, mapper, client.get(new SimpleHttpRequest<JsonNode>(TheSpaceUpdater.BASE_API_URL + "/items/" + pPid + ".json", new JSonNodeHttpResponseTransformer(mapper))).get("programme")); } else { series.setChildRefs(Iterables.concat(series.getChildRefs(), ImmutableList.of(episode.childRef()))); } episode.setParentRef(ParentRef.parentRefFrom(series)); contentWriter.createOrUpdate(series); } contentWriter.createOrUpdate(episode); }
private void makeEpisode(Episode episode, JsonNode node, ObjectMapper mapper) throws Exception { JsonNode pid = node.get("pid"); episode.setCanonicalUri(getCanonicalUri(pid.asText())); JsonNode title = node.get("title"); episode.setTitle(title.asText()); JsonNode position = node.get("position"); if (position != null) { episode.setEpisodeNumber(position.asInt()); } JsonNode long_synopsis = node.get("long_synopsis"); JsonNode medium_synopsis = node.get("medium_synopsis"); JsonNode short_synopsis = node.get("short_synopsis"); String synopsis = null; if (long_synopsis != null) { synopsis = long_synopsis.asText(); } else if (medium_synopsis != null) { synopsis = medium_synopsis.asText(); } else if (short_synopsis != null) { synopsis = short_synopsis.asText(); } episode.setDescription(synopsis); JsonNode image = node.get("image"); if (image != null) { JsonNode smallImage = image.get("depiction_320"); if (smallImage != null) { episode.setThumbnail(smallImage.asText()); } JsonNode bigImage = image.get("depiction_640"); if (bigImage != null) { episode.setImage(bigImage.asText()); } } Iterator<JsonNode> clips = node.get("available_clips").getElements(); while (clips.hasNext()) { String cPid = clips.next().get("pid").asText(); JsonNode clip = client.get(new SimpleHttpRequest<JsonNode>(TheSpaceUpdater.BASE_API_URL + "/items/" + cPid + ".json", new JSonNodeHttpResponseTransformer(mapper))); episode.addClip(getClip(mapper, clip.get("programme"), episode)); } Iterator<JsonNode> versions = node.get("versions").getElements(); while (versions.hasNext()) { String vPid = versions.next().get("pid").asText(); JsonNode version = client.get(new SimpleHttpRequest<JsonNode>(TheSpaceUpdater.BASE_API_URL + "/items/" + vPid + ".json", new JSonNodeHttpResponseTransformer(mapper))); episode.addVersion(getVersion(mapper, version.get("version"), episode)); } JsonNode parent = node.get("parent"); if (parent != null) { String pPid = parent.get("pid").asText(); Series series = (Series) contentResolver.findByCanonicalUris(ImmutableSet.of(getCanonicalUri(pPid))).getFirstValue().valueOrNull(); if (series == null) { series = new Series(); series.setChildRefs(ImmutableList.of(episode.childRef())); fillSeries(series, mapper, client.get(new SimpleHttpRequest<JsonNode>(TheSpaceUpdater.BASE_API_URL + "/items/" + pPid + ".json", new JSonNodeHttpResponseTransformer(mapper))).get("programme")); } else { series.setChildRefs(Iterables.concat(series.getChildRefs(), ImmutableList.of(episode.childRef()))); } episode.setParentRef(ParentRef.parentRefFrom(series)); contentWriter.createOrUpdate(series); } contentWriter.createOrUpdate(episode); }
diff --git a/src/savant/view/swing/interval/IntervalTrack.java b/src/savant/view/swing/interval/IntervalTrack.java index 93a27e9e..16980a4d 100644 --- a/src/savant/view/swing/interval/IntervalTrack.java +++ b/src/savant/view/swing/interval/IntervalTrack.java @@ -1,139 +1,139 @@ /* * Copyright 2010 University of Toronto * * 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 savant.view.swing.interval; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import savant.api.adapter.RangeAdapter; import savant.data.sources.DataSource; import savant.data.types.GenericIntervalRecord; import savant.data.types.Interval; import savant.data.types.Record; import savant.exception.SavantTrackCreationCancelledException; import savant.settings.ColourSettings; import savant.util.*; import savant.view.swing.Track; /** * * @author mfiume */ public class IntervalTrack extends Track { private static Log LOG = LogFactory.getLog(IntervalTrack.class); public enum DrawingMode { SQUISH, PACK, ARC }; public IntervalTrack(DataSource intervalTrack) throws SavantTrackCreationCancelledException { super(intervalTrack, new IntervalTrackRenderer()); setColorScheme(getDefaultColorScheme()); setDrawModes(this.renderer.getRenderingModes()); setDrawMode(this.renderer.getDefaultRenderingMode()); this.notifyControllerOfCreation(); } private ColorScheme getDefaultColorScheme() { ColorScheme c = new ColorScheme(); /* add settings here */ //c.addColorSetting("Background", BrowserDefaults.colorGraphMain); c.addColorSetting("Translucent Graph", ColourSettings.getTranslucentGraph()); c.addColorSetting("Opaque Graph", ColourSettings.getOpaqueGraph()); c.addColorSetting("Line", ColourSettings.getPointLine()); return c; } @Override public void resetColorScheme() { setColorScheme(getDefaultColorScheme()); } @Override public Resolution getResolution(RangeAdapter range) { return getResolution(range, getDrawMode()); } public Resolution getResolution(RangeAdapter range, String mode) { if (mode.equals(IntervalTrackRenderer.SQUISH_MODE)) { return getSquishModeResolution(range); } else if (mode.equals(IntervalTrackRenderer.ARC_MODE)) { return getArcModeResolution(range); } else if (mode.equals(IntervalTrackRenderer.PACK_MODE)) { return getDefaultModeResolution(range); } else { LOG.warn("Unrecognized draw mode " + mode); return getDefaultModeResolution(range); } } public Resolution getDefaultModeResolution(RangeAdapter range) { return Resolution.VERY_HIGH; } public Resolution getArcModeResolution(RangeAdapter range) { return Resolution.VERY_HIGH; } public Resolution getSquishModeResolution(RangeAdapter range) { return Resolution.VERY_HIGH; } @Override public void prepareForRendering(String reference, Range range) { Resolution r = getResolution(range); switch (r) { case VERY_HIGH: renderer.addInstruction(DrawingInstruction.PROGRESS, "Loading track..."); requestData(reference, range); break; default: - renderer.addInstruction(DrawingInstruction.ERROR, "zoom in to see data"); + renderer.addInstruction(DrawingInstruction.ERROR, "Zoom in to see data"); break; } renderer.addInstruction(DrawingInstruction.RESOLUTION, r); renderer.addInstruction(DrawingInstruction.RANGE, range); renderer.addInstruction(DrawingInstruction.COLOR_SCHEME, getColorScheme()); renderer.addInstruction(DrawingInstruction.REFERENCE_EXISTS, containsReference(reference)); if (!getDrawMode().equals(IntervalTrackRenderer.ARC_MODE)) { renderer.addInstruction(DrawingInstruction.AXIS_RANGE, AxisRange.initWithRanges(range, getDefaultYRange())); } renderer.addInstruction(DrawingInstruction.MODE, getDrawMode()); renderer.addInstruction(DrawingInstruction.SELECTION_ALLOWED, true); } private Range getDefaultYRange() { return new Range(0, 1); } public static int getMaxValue(List<Record> data) { double max = 0; for (Record r: data) { Interval interval = ((GenericIntervalRecord)r).getInterval(); double val = interval.getLength(); if (val > max) max = val; } return (int)Math.ceil(max); } }
true
true
public void prepareForRendering(String reference, Range range) { Resolution r = getResolution(range); switch (r) { case VERY_HIGH: renderer.addInstruction(DrawingInstruction.PROGRESS, "Loading track..."); requestData(reference, range); break; default: renderer.addInstruction(DrawingInstruction.ERROR, "zoom in to see data"); break; } renderer.addInstruction(DrawingInstruction.RESOLUTION, r); renderer.addInstruction(DrawingInstruction.RANGE, range); renderer.addInstruction(DrawingInstruction.COLOR_SCHEME, getColorScheme()); renderer.addInstruction(DrawingInstruction.REFERENCE_EXISTS, containsReference(reference)); if (!getDrawMode().equals(IntervalTrackRenderer.ARC_MODE)) { renderer.addInstruction(DrawingInstruction.AXIS_RANGE, AxisRange.initWithRanges(range, getDefaultYRange())); } renderer.addInstruction(DrawingInstruction.MODE, getDrawMode()); renderer.addInstruction(DrawingInstruction.SELECTION_ALLOWED, true); }
public void prepareForRendering(String reference, Range range) { Resolution r = getResolution(range); switch (r) { case VERY_HIGH: renderer.addInstruction(DrawingInstruction.PROGRESS, "Loading track..."); requestData(reference, range); break; default: renderer.addInstruction(DrawingInstruction.ERROR, "Zoom in to see data"); break; } renderer.addInstruction(DrawingInstruction.RESOLUTION, r); renderer.addInstruction(DrawingInstruction.RANGE, range); renderer.addInstruction(DrawingInstruction.COLOR_SCHEME, getColorScheme()); renderer.addInstruction(DrawingInstruction.REFERENCE_EXISTS, containsReference(reference)); if (!getDrawMode().equals(IntervalTrackRenderer.ARC_MODE)) { renderer.addInstruction(DrawingInstruction.AXIS_RANGE, AxisRange.initWithRanges(range, getDefaultYRange())); } renderer.addInstruction(DrawingInstruction.MODE, getDrawMode()); renderer.addInstruction(DrawingInstruction.SELECTION_ALLOWED, true); }
diff --git a/dev/core/src/com/google/gwt/core/ext/linker/impl/SelectionScriptLinker.java b/dev/core/src/com/google/gwt/core/ext/linker/impl/SelectionScriptLinker.java index e475f8481..648ba05a0 100644 --- a/dev/core/src/com/google/gwt/core/ext/linker/impl/SelectionScriptLinker.java +++ b/dev/core/src/com/google/gwt/core/ext/linker/impl/SelectionScriptLinker.java @@ -1,345 +1,347 @@ /* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.core.ext.linker.impl; import com.google.gwt.core.ext.LinkerContext; import com.google.gwt.core.ext.TreeLogger; import com.google.gwt.core.ext.UnableToCompleteException; import com.google.gwt.core.ext.linker.AbstractLinker; import com.google.gwt.core.ext.linker.ArtifactSet; import com.google.gwt.core.ext.linker.CompilationResult; import com.google.gwt.core.ext.linker.EmittedArtifact; import com.google.gwt.core.ext.linker.ScriptReference; import com.google.gwt.core.ext.linker.SelectionProperty; import com.google.gwt.core.ext.linker.StylesheetReference; import com.google.gwt.dev.util.Util; import com.google.gwt.util.tools.Utility; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.Map; import java.util.SortedSet; /** * A base class for Linkers that use an external script to boostrap the GWT * module. This implementation injects JavaScript snippits into a JS program * defined in an external file. */ public abstract class SelectionScriptLinker extends AbstractLinker { /** * TODO(bobv): Move this class into c.g.g.core.linker when HostedModeLinker * goes away? */ /** * Determines whether or not the URL is relative. * * @param src the test url * @return <code>true</code> if the URL is relative, <code>false</code> if * not */ @SuppressWarnings("unused") protected static boolean isRelativeURL(String src) { // A straight absolute url for the same domain, server, and protocol. if (src.startsWith("/")) { return false; } // If it can be parsed as a URL, then it's probably absolute. try { URL testUrl = new URL(src); // Let's guess that it is absolute (thus, not relative). return false; } catch (MalformedURLException e) { // Do nothing, since it was a speculative parse. } // Since none of the above matched, let's guess that it's relative. return true; } protected static void replaceAll(StringBuffer buf, String search, String replace) { int len = search.length(); for (int pos = buf.indexOf(search); pos >= 0; pos = buf.indexOf(search, pos + 1)) { buf.replace(pos, pos + len, replace); } } private final Map<CompilationResult, String> compilationPartialPaths = new IdentityHashMap<CompilationResult, String>(); @Override public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) throws UnableToCompleteException { ArtifactSet toReturn = new ArtifactSet(artifacts); for (CompilationResult compilation : toReturn.find(CompilationResult.class)) { toReturn.add(doEmitCompilation(logger, context, compilation)); } toReturn.add(emitSelectionScript(logger, context, artifacts)); return toReturn; } protected EmittedArtifact doEmitCompilation(TreeLogger logger, LinkerContext context, CompilationResult result) throws UnableToCompleteException { StringBuffer b = new StringBuffer(); b.append(getModulePrefix(logger, context)); b.append(result.getJavaScript()); b.append(getModuleSuffix(logger, context)); EmittedArtifact toReturn = emitWithStrongName(logger, Util.getBytes(b.toString()), "", getCompilationExtension(logger, context)); compilationPartialPaths.put(result, toReturn.getPartialPath()); return toReturn; } protected EmittedArtifact emitSelectionScript(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) throws UnableToCompleteException { String selectionScript = generateSelectionScript(logger, context, artifacts); selectionScript = context.optimizeJavaScript(logger, selectionScript); /* * Last modified is important to keep hosted mode refreses from clobbering * web mode compiles. We set the timestamp on the hosted mode selection * script to the same mod time as the module (to allow updates). For web * mode, we just set it to now. */ long lastModified; if (artifacts.find(CompilationResult.class).size() == 0) { lastModified = context.getModuleLastModified(); } else { lastModified = System.currentTimeMillis(); } return emitString(logger, selectionScript, context.getModuleName() + ".nocache.js", lastModified); } protected String generatePropertyProvider(SelectionProperty prop) { StringBuffer toReturn = new StringBuffer(); if (prop.tryGetValue() == null) { toReturn.append("providers['" + prop.getName() + "'] = function()"); toReturn.append(prop.getPropertyProvider()); toReturn.append(";"); toReturn.append("values['" + prop.getName() + "'] = {"); boolean needsComma = false; int counter = 0; for (String value : prop.getPossibleValues()) { if (needsComma) { toReturn.append(","); } else { needsComma = true; } toReturn.append("'" + value + "':"); toReturn.append(counter++); } toReturn.append("};"); } return toReturn.toString(); } protected String generateScriptInjector(String scriptUrl) { if (isRelativeURL(scriptUrl)) { return " if (!__gwt_scriptsLoaded['" + scriptUrl + "']) {\n" + " __gwt_scriptsLoaded['" + scriptUrl + "'] = true;\n" + " document.write('<script language=\\\"javascript\\\" src=\\\"'+base+'" + scriptUrl + "\\\"></script>');\n" + " }\n"; } else { return " if (!__gwt_scriptsLoaded['" + scriptUrl + "']) {\n" + " __gwt_scriptsLoaded['" + scriptUrl + "'] = true;\n" + " document.write('<script language=\\\"javascript\\\" src=\\\"" + scriptUrl + "\\\"></script>');\n" + " }\n"; } } protected String generateSelectionScript(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) throws UnableToCompleteException { StringBuffer selectionScript; try { selectionScript = new StringBuffer( Utility.getFileFromClassPath(getSelectionScriptTemplate(logger, context))); } catch (IOException e) { logger.log(TreeLogger.ERROR, "Unable to read selection script template", e); throw new UnableToCompleteException(); } replaceAll(selectionScript, "__MODULE_FUNC__", context.getModuleFunctionName()); replaceAll(selectionScript, "__MODULE_NAME__", context.getModuleName()); int startPos; // Add external dependencies startPos = selectionScript.indexOf("// __MODULE_STYLES_END__"); if (startPos != -1) { for (StylesheetReference resource : artifacts.find(StylesheetReference.class)) { String text = generateStylesheetInjector(resource.getSrc()); selectionScript.insert(startPos, text); startPos += text.length(); } } startPos = selectionScript.indexOf("// __MODULE_SCRIPTS_END__"); if (startPos != -1) { for (ScriptReference resource : artifacts.find(ScriptReference.class)) { String text = generateScriptInjector(resource.getSrc()); selectionScript.insert(startPos, text); startPos += text.length(); } } // Add property providers startPos = selectionScript.indexOf("// __PROPERTIES_END__"); if (startPos != -1) { for (SelectionProperty p : context.getProperties()) { String text = generatePropertyProvider(p); selectionScript.insert(startPos, text); startPos += text.length(); } } // Possibly add permutations SortedSet<CompilationResult> compilations = artifacts.find(CompilationResult.class); startPos = selectionScript.indexOf("// __PERMUTATIONS_END__"); if (startPos != -1) { StringBuffer text = new StringBuffer(); if (compilations.size() == 0) { // Hosted mode link. - text.append("alert('This module needs to be (re)compiled, " - + "please run a compile or use the Compile/Browse button in hosted mode');"); + text.append("alert(\"GWT module '" + + context.getModuleName() + + "' needs to be (re)compiled, " + + "please run a compile or use the Compile/Browse button in hosted mode\");"); text.append("return;"); } else if (compilations.size() == 1) { // Just one distinct compilation; no need to evaluate properties Iterator<CompilationResult> iter = compilations.iterator(); CompilationResult result = iter.next(); text.append("strongName = '" + compilationPartialPaths.get(result) + "';"); } else { for (CompilationResult r : compilations) { for (Map<SelectionProperty, String> propertyMap : r.getPropertyMap()) { // unflatten([v1, v2, v3], 'strongName'); text.append("unflattenKeylistIntoAnswers(["); boolean needsComma = false; for (SelectionProperty p : context.getProperties()) { if (!propertyMap.containsKey(p)) { continue; } if (needsComma) { text.append(","); } else { needsComma = true; } text.append("'" + propertyMap.get(p) + "'"); } text.append("], '").append(compilationPartialPaths.get(r)).append( "');\n"); } } // strongName = answers[compute('p1')][compute('p2')]; text.append("strongName = answers["); boolean needsIndexMarkers = false; for (SelectionProperty p : context.getProperties()) { if (p.tryGetValue() != null) { continue; } if (needsIndexMarkers) { text.append("]["); } else { needsIndexMarkers = true; } text.append("computePropValue('" + p.getName() + "')"); } text.append("];"); } selectionScript.insert(startPos, text); } return selectionScript.toString(); } /** * Generate a snippit of JavaScript to inject an external stylesheet. * * <pre> * if (!__gwt_stylesLoaded['URL']) { * var l = $doc.createElement('link'); * __gwt_styleLoaded['URL'] = l; * l.setAttribute('rel', 'stylesheet'); * l.setAttribute('href', HREF_EXPR); * $doc.getElementsByTagName('head')[0].appendChild(l); * } * </pre> */ protected String generateStylesheetInjector(String stylesheetUrl) { String hrefExpr = "'" + stylesheetUrl + "'"; if (isRelativeURL(stylesheetUrl)) { hrefExpr = "base + " + hrefExpr; } return "if (!__gwt_stylesLoaded['" + stylesheetUrl + "']) {\n " + " var l = $doc.createElement('link');\n " + " __gwt_stylesLoaded['" + stylesheetUrl + "'] = l;\n " + " l.setAttribute('rel', 'stylesheet');\n " + " l.setAttribute('href', " + hrefExpr + ");\n " + " $doc.getElementsByTagName('head')[0].appendChild(l);\n " + "}\n"; } protected abstract String getCompilationExtension(TreeLogger logger, LinkerContext context) throws UnableToCompleteException; /** * Get the partial path on which a CompilationResult has been emitted. * * @return the partial path, or <code>null</code> if the CompilationResult * has not been emitted. */ protected String getCompilationPartialPath(CompilationResult result) { return compilationPartialPaths.get(result); } protected abstract String getModulePrefix(TreeLogger logger, LinkerContext context) throws UnableToCompleteException; protected abstract String getModuleSuffix(TreeLogger logger, LinkerContext context) throws UnableToCompleteException; protected abstract String getSelectionScriptTemplate(TreeLogger logger, LinkerContext context) throws UnableToCompleteException; }
true
true
protected String generateSelectionScript(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) throws UnableToCompleteException { StringBuffer selectionScript; try { selectionScript = new StringBuffer( Utility.getFileFromClassPath(getSelectionScriptTemplate(logger, context))); } catch (IOException e) { logger.log(TreeLogger.ERROR, "Unable to read selection script template", e); throw new UnableToCompleteException(); } replaceAll(selectionScript, "__MODULE_FUNC__", context.getModuleFunctionName()); replaceAll(selectionScript, "__MODULE_NAME__", context.getModuleName()); int startPos; // Add external dependencies startPos = selectionScript.indexOf("// __MODULE_STYLES_END__"); if (startPos != -1) { for (StylesheetReference resource : artifacts.find(StylesheetReference.class)) { String text = generateStylesheetInjector(resource.getSrc()); selectionScript.insert(startPos, text); startPos += text.length(); } } startPos = selectionScript.indexOf("// __MODULE_SCRIPTS_END__"); if (startPos != -1) { for (ScriptReference resource : artifacts.find(ScriptReference.class)) { String text = generateScriptInjector(resource.getSrc()); selectionScript.insert(startPos, text); startPos += text.length(); } } // Add property providers startPos = selectionScript.indexOf("// __PROPERTIES_END__"); if (startPos != -1) { for (SelectionProperty p : context.getProperties()) { String text = generatePropertyProvider(p); selectionScript.insert(startPos, text); startPos += text.length(); } } // Possibly add permutations SortedSet<CompilationResult> compilations = artifacts.find(CompilationResult.class); startPos = selectionScript.indexOf("// __PERMUTATIONS_END__"); if (startPos != -1) { StringBuffer text = new StringBuffer(); if (compilations.size() == 0) { // Hosted mode link. text.append("alert('This module needs to be (re)compiled, " + "please run a compile or use the Compile/Browse button in hosted mode');"); text.append("return;"); } else if (compilations.size() == 1) { // Just one distinct compilation; no need to evaluate properties Iterator<CompilationResult> iter = compilations.iterator(); CompilationResult result = iter.next(); text.append("strongName = '" + compilationPartialPaths.get(result) + "';"); } else { for (CompilationResult r : compilations) { for (Map<SelectionProperty, String> propertyMap : r.getPropertyMap()) { // unflatten([v1, v2, v3], 'strongName'); text.append("unflattenKeylistIntoAnswers(["); boolean needsComma = false; for (SelectionProperty p : context.getProperties()) { if (!propertyMap.containsKey(p)) { continue; } if (needsComma) { text.append(","); } else { needsComma = true; } text.append("'" + propertyMap.get(p) + "'"); } text.append("], '").append(compilationPartialPaths.get(r)).append( "');\n"); } } // strongName = answers[compute('p1')][compute('p2')]; text.append("strongName = answers["); boolean needsIndexMarkers = false; for (SelectionProperty p : context.getProperties()) { if (p.tryGetValue() != null) { continue; } if (needsIndexMarkers) { text.append("]["); } else { needsIndexMarkers = true; } text.append("computePropValue('" + p.getName() + "')"); } text.append("];"); } selectionScript.insert(startPos, text); } return selectionScript.toString(); }
protected String generateSelectionScript(TreeLogger logger, LinkerContext context, ArtifactSet artifacts) throws UnableToCompleteException { StringBuffer selectionScript; try { selectionScript = new StringBuffer( Utility.getFileFromClassPath(getSelectionScriptTemplate(logger, context))); } catch (IOException e) { logger.log(TreeLogger.ERROR, "Unable to read selection script template", e); throw new UnableToCompleteException(); } replaceAll(selectionScript, "__MODULE_FUNC__", context.getModuleFunctionName()); replaceAll(selectionScript, "__MODULE_NAME__", context.getModuleName()); int startPos; // Add external dependencies startPos = selectionScript.indexOf("// __MODULE_STYLES_END__"); if (startPos != -1) { for (StylesheetReference resource : artifacts.find(StylesheetReference.class)) { String text = generateStylesheetInjector(resource.getSrc()); selectionScript.insert(startPos, text); startPos += text.length(); } } startPos = selectionScript.indexOf("// __MODULE_SCRIPTS_END__"); if (startPos != -1) { for (ScriptReference resource : artifacts.find(ScriptReference.class)) { String text = generateScriptInjector(resource.getSrc()); selectionScript.insert(startPos, text); startPos += text.length(); } } // Add property providers startPos = selectionScript.indexOf("// __PROPERTIES_END__"); if (startPos != -1) { for (SelectionProperty p : context.getProperties()) { String text = generatePropertyProvider(p); selectionScript.insert(startPos, text); startPos += text.length(); } } // Possibly add permutations SortedSet<CompilationResult> compilations = artifacts.find(CompilationResult.class); startPos = selectionScript.indexOf("// __PERMUTATIONS_END__"); if (startPos != -1) { StringBuffer text = new StringBuffer(); if (compilations.size() == 0) { // Hosted mode link. text.append("alert(\"GWT module '" + context.getModuleName() + "' needs to be (re)compiled, " + "please run a compile or use the Compile/Browse button in hosted mode\");"); text.append("return;"); } else if (compilations.size() == 1) { // Just one distinct compilation; no need to evaluate properties Iterator<CompilationResult> iter = compilations.iterator(); CompilationResult result = iter.next(); text.append("strongName = '" + compilationPartialPaths.get(result) + "';"); } else { for (CompilationResult r : compilations) { for (Map<SelectionProperty, String> propertyMap : r.getPropertyMap()) { // unflatten([v1, v2, v3], 'strongName'); text.append("unflattenKeylistIntoAnswers(["); boolean needsComma = false; for (SelectionProperty p : context.getProperties()) { if (!propertyMap.containsKey(p)) { continue; } if (needsComma) { text.append(","); } else { needsComma = true; } text.append("'" + propertyMap.get(p) + "'"); } text.append("], '").append(compilationPartialPaths.get(r)).append( "');\n"); } } // strongName = answers[compute('p1')][compute('p2')]; text.append("strongName = answers["); boolean needsIndexMarkers = false; for (SelectionProperty p : context.getProperties()) { if (p.tryGetValue() != null) { continue; } if (needsIndexMarkers) { text.append("]["); } else { needsIndexMarkers = true; } text.append("computePropValue('" + p.getName() + "')"); } text.append("];"); } selectionScript.insert(startPos, text); } return selectionScript.toString(); }
diff --git a/src/main/java/batch/launch/HelloBatchMain.java b/src/main/java/batch/launch/HelloBatchMain.java index 43d2983..3d6af3d 100644 --- a/src/main/java/batch/launch/HelloBatchMain.java +++ b/src/main/java/batch/launch/HelloBatchMain.java @@ -1,33 +1,34 @@ package batch.launch; import java.util.HashMap; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobParameter; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersInvalidException; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException; import org.springframework.batch.core.repository.JobRestartException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import batch.config.DatabaseRepositoryProducer; import batch.job.HelloWorldJobProducer; public class HelloBatchMain { public static void main(String[] args) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( HelloWorldJobProducer.class, DatabaseRepositoryProducer.class); Job job = context.getBean("helloWorldJob", Job.class); JobLauncher launcher = context.getBean(JobLauncher.class); HashMap<String, JobParameter> parameters = new HashMap<String, JobParameter>(); parameters.put("run", new JobParameter("c")); launcher.run(job, new JobParameters(parameters)); + context.close(); } }
true
true
public static void main(String[] args) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( HelloWorldJobProducer.class, DatabaseRepositoryProducer.class); Job job = context.getBean("helloWorldJob", Job.class); JobLauncher launcher = context.getBean(JobLauncher.class); HashMap<String, JobParameter> parameters = new HashMap<String, JobParameter>(); parameters.put("run", new JobParameter("c")); launcher.run(job, new JobParameters(parameters)); }
public static void main(String[] args) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( HelloWorldJobProducer.class, DatabaseRepositoryProducer.class); Job job = context.getBean("helloWorldJob", Job.class); JobLauncher launcher = context.getBean(JobLauncher.class); HashMap<String, JobParameter> parameters = new HashMap<String, JobParameter>(); parameters.put("run", new JobParameter("c")); launcher.run(job, new JobParameters(parameters)); context.close(); }
diff --git a/farrago/src/net/sf/farrago/query/FennelCartesianJoinRule.java b/farrago/src/net/sf/farrago/query/FennelCartesianJoinRule.java index 36e251b48..e4e5076d9 100644 --- a/farrago/src/net/sf/farrago/query/FennelCartesianJoinRule.java +++ b/farrago/src/net/sf/farrago/query/FennelCartesianJoinRule.java @@ -1,228 +1,234 @@ /* // $Id$ // Farrago is an extensible data management system. // Copyright (C) 2005-2005 The Eigenbase Project // Copyright (C) 2005-2005 Disruptive Tech // Copyright (C) 2005-2005 LucidEra, Inc. // Portions Copyright (C) 2003-2005 John V. Sichi // // 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 approved by The Eigenbase Project. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.sf.farrago.query; import org.eigenbase.rel.*; import org.eigenbase.relopt.*; import org.eigenbase.rel.metadata.*; import org.eigenbase.rex.*; /** * FennelCartesianJoinRule is a rule for converting an INNER JoinRel with no * join condition into a FennelCartesianProductRel. * * @author John V. Sichi * @version $Id$ */ public class FennelCartesianJoinRule extends RelOptRule { //~ Constructors ----------------------------------------------------------- public FennelCartesianJoinRule() { super(new RelOptRuleOperand( JoinRel.class, null)); } //~ Methods ---------------------------------------------------------------- // implement RelOptRule public CallingConvention getOutConvention() { return FennelRel.FENNEL_EXEC_CONVENTION; } // implement RelOptRule public void onMatch(RelOptRuleCall call) { JoinRel joinRel = (JoinRel) call.rels[0]; RelNode leftRel = joinRel.getLeft(); RelNode rightRel = joinRel.getRight(); /* * Joins that can use CartesianProduct will have only TRUE condition * in JoinRel. Any other join conditions have to be extracted out * already. This implies that only ON TRUE condition is suported for - * LeftOuterJoins. + * LeftOuterJoins or RightOuterJoins. */ - boolean joinTypeFeasible = - (joinRel.getJoinType() == JoinRelType.INNER) || - (joinRel.getJoinType() == JoinRelType.LEFT); + JoinRelType joinType = joinRel.getJoinType(); + boolean joinTypeFeasible = !(joinType == JoinRelType.FULL); + boolean swapped = false; + if (joinType == JoinRelType.RIGHT) { + swapped = true; + RelNode tmp = leftRel; + leftRel = rightRel; + rightRel = tmp; + joinType = JoinRelType.LEFT; + } /* * CartesianProduct relies on a post filter to do the join filtering. * If the join condition is not extracted to a post filter(and is still * in JoinRel), CartesianProduct can not be used. */ boolean joinConditionFeasible = joinRel.getCondition().equals( joinRel.getCluster().getRexBuilder().makeLiteral(true)); if (!joinTypeFeasible || !joinConditionFeasible) { return; } if (!joinRel.getVariablesStopped().isEmpty()) { return; } // see if it makes sense to buffer the existing RHS; if not, try // the LHS, swapping the join operands if it does make sense to buffer - // the LHS - boolean swapped = false; + // the LHS; but only if we haven't already swapped the inputs FennelBufferRel bufRel = bufferRight(leftRel, rightRel, joinRel.getTraits()); if (bufRel != null) { rightRel = bufRel; - } else { + } else if (!swapped) { bufRel = bufferRight(rightRel, leftRel, joinRel.getTraits()); if (bufRel != null) { swapped = true; leftRel = rightRel; rightRel = bufRel; } } RelNode fennelLeft = mergeTraitsAndConvert( joinRel.getTraits(), FennelRel.FENNEL_EXEC_CONVENTION, leftRel); if (fennelLeft == null) { return; } RelNode fennelRight = mergeTraitsAndConvert( joinRel.getTraits(), FennelRel.FENNEL_EXEC_CONVENTION, rightRel); if (fennelRight == null) { return; } FennelCartesianProductRel productRel = new FennelCartesianProductRel( joinRel.getCluster(), fennelLeft, fennelRight, - joinRel.getJoinType(), + joinType, RelOptUtil.getFieldNameList(joinRel.getRowType())); RelNode newRel; if (swapped) { // if the join inputs were swapped, create a CalcRel on top of // the new cartesian join that reflects the original join // projection final RexNode [] exps = RelOptUtil.createSwappedJoinExprs( productRel, joinRel, true); final RexProgram program = RexProgram.create( productRel.getRowType(), exps, null, joinRel.getRowType(), productRel.getCluster().getRexBuilder()); newRel = new CalcRel( productRel.getCluster(), RelOptUtil.clone(joinRel.getTraits()), productRel, joinRel.getRowType(), program, RelCollation.emptyList); } else { newRel = productRel; } call.transformTo(newRel); } /** * Returns a FennelBufferRel in the case where it makes sense to buffer * the RHS into the cartesian product join. This is done by comparing * the cost between the buffered and non-buffered cases. * * @param left left hand input into the cartesian join * @param right right hand input into the cartesian join * @param traits traits of the original join * * @return created FennelBufferRel if it makes sense to buffer the RHS */ private FennelBufferRel bufferRight( RelNode left, RelNode right, RelTraitSet traits) { RelNode fennelInput = mergeTraitsAndConvert( traits, FennelRel.FENNEL_EXEC_CONVENTION, right); FennelBufferRel bufRel = new FennelBufferRel(right.getCluster(), fennelInput, false, true); // if we don't have a rowcount for the LHS, then just go ahead and // buffer Double nRowsLeft = RelMetadataQuery.getRowCount(left); if (nRowsLeft == null) { return bufRel; } // Cost without buffering is: // getCumulativeCost(LHS) + // getRowCount(LHS) * getCumulativeCost(RHS) // // Cost with buffering is: // getCumulativeCost(LHS) + getCumulativeCost(RHS) + // getRowCount(LHS) * getNonCumulativeCost(buffering) * 3; // // The times 3 represents the overhead of caching. The "3" // is arbitrary at this point. // // To decide if buffering makes sense, take the difference between the // two costs described above. RelOptCost rightCost = RelMetadataQuery.getCumulativeCost(right); RelOptCost noBufferPlanCost = rightCost.multiplyBy(nRowsLeft); RelOptCost bufferCost = RelMetadataQuery.getNonCumulativeCost(bufRel); bufferCost = bufferCost.multiplyBy(3); RelOptCost bufferPlanCost = bufferCost.multiplyBy(nRowsLeft); bufferPlanCost = bufferPlanCost.plus(rightCost); if (bufferPlanCost.isLt(noBufferPlanCost)) { return bufRel; } else { return null; } } } // End FennelCartesianJoinRule.java
false
true
public void onMatch(RelOptRuleCall call) { JoinRel joinRel = (JoinRel) call.rels[0]; RelNode leftRel = joinRel.getLeft(); RelNode rightRel = joinRel.getRight(); /* * Joins that can use CartesianProduct will have only TRUE condition * in JoinRel. Any other join conditions have to be extracted out * already. This implies that only ON TRUE condition is suported for * LeftOuterJoins. */ boolean joinTypeFeasible = (joinRel.getJoinType() == JoinRelType.INNER) || (joinRel.getJoinType() == JoinRelType.LEFT); /* * CartesianProduct relies on a post filter to do the join filtering. * If the join condition is not extracted to a post filter(and is still * in JoinRel), CartesianProduct can not be used. */ boolean joinConditionFeasible = joinRel.getCondition().equals( joinRel.getCluster().getRexBuilder().makeLiteral(true)); if (!joinTypeFeasible || !joinConditionFeasible) { return; } if (!joinRel.getVariablesStopped().isEmpty()) { return; } // see if it makes sense to buffer the existing RHS; if not, try // the LHS, swapping the join operands if it does make sense to buffer // the LHS boolean swapped = false; FennelBufferRel bufRel = bufferRight(leftRel, rightRel, joinRel.getTraits()); if (bufRel != null) { rightRel = bufRel; } else { bufRel = bufferRight(rightRel, leftRel, joinRel.getTraits()); if (bufRel != null) { swapped = true; leftRel = rightRel; rightRel = bufRel; } } RelNode fennelLeft = mergeTraitsAndConvert( joinRel.getTraits(), FennelRel.FENNEL_EXEC_CONVENTION, leftRel); if (fennelLeft == null) { return; } RelNode fennelRight = mergeTraitsAndConvert( joinRel.getTraits(), FennelRel.FENNEL_EXEC_CONVENTION, rightRel); if (fennelRight == null) { return; } FennelCartesianProductRel productRel = new FennelCartesianProductRel( joinRel.getCluster(), fennelLeft, fennelRight, joinRel.getJoinType(), RelOptUtil.getFieldNameList(joinRel.getRowType())); RelNode newRel; if (swapped) { // if the join inputs were swapped, create a CalcRel on top of // the new cartesian join that reflects the original join // projection final RexNode [] exps = RelOptUtil.createSwappedJoinExprs( productRel, joinRel, true); final RexProgram program = RexProgram.create( productRel.getRowType(), exps, null, joinRel.getRowType(), productRel.getCluster().getRexBuilder()); newRel = new CalcRel( productRel.getCluster(), RelOptUtil.clone(joinRel.getTraits()), productRel, joinRel.getRowType(), program, RelCollation.emptyList); } else { newRel = productRel; } call.transformTo(newRel); }
public void onMatch(RelOptRuleCall call) { JoinRel joinRel = (JoinRel) call.rels[0]; RelNode leftRel = joinRel.getLeft(); RelNode rightRel = joinRel.getRight(); /* * Joins that can use CartesianProduct will have only TRUE condition * in JoinRel. Any other join conditions have to be extracted out * already. This implies that only ON TRUE condition is suported for * LeftOuterJoins or RightOuterJoins. */ JoinRelType joinType = joinRel.getJoinType(); boolean joinTypeFeasible = !(joinType == JoinRelType.FULL); boolean swapped = false; if (joinType == JoinRelType.RIGHT) { swapped = true; RelNode tmp = leftRel; leftRel = rightRel; rightRel = tmp; joinType = JoinRelType.LEFT; } /* * CartesianProduct relies on a post filter to do the join filtering. * If the join condition is not extracted to a post filter(and is still * in JoinRel), CartesianProduct can not be used. */ boolean joinConditionFeasible = joinRel.getCondition().equals( joinRel.getCluster().getRexBuilder().makeLiteral(true)); if (!joinTypeFeasible || !joinConditionFeasible) { return; } if (!joinRel.getVariablesStopped().isEmpty()) { return; } // see if it makes sense to buffer the existing RHS; if not, try // the LHS, swapping the join operands if it does make sense to buffer // the LHS; but only if we haven't already swapped the inputs FennelBufferRel bufRel = bufferRight(leftRel, rightRel, joinRel.getTraits()); if (bufRel != null) { rightRel = bufRel; } else if (!swapped) { bufRel = bufferRight(rightRel, leftRel, joinRel.getTraits()); if (bufRel != null) { swapped = true; leftRel = rightRel; rightRel = bufRel; } } RelNode fennelLeft = mergeTraitsAndConvert( joinRel.getTraits(), FennelRel.FENNEL_EXEC_CONVENTION, leftRel); if (fennelLeft == null) { return; } RelNode fennelRight = mergeTraitsAndConvert( joinRel.getTraits(), FennelRel.FENNEL_EXEC_CONVENTION, rightRel); if (fennelRight == null) { return; } FennelCartesianProductRel productRel = new FennelCartesianProductRel( joinRel.getCluster(), fennelLeft, fennelRight, joinType, RelOptUtil.getFieldNameList(joinRel.getRowType())); RelNode newRel; if (swapped) { // if the join inputs were swapped, create a CalcRel on top of // the new cartesian join that reflects the original join // projection final RexNode [] exps = RelOptUtil.createSwappedJoinExprs( productRel, joinRel, true); final RexProgram program = RexProgram.create( productRel.getRowType(), exps, null, joinRel.getRowType(), productRel.getCluster().getRexBuilder()); newRel = new CalcRel( productRel.getCluster(), RelOptUtil.clone(joinRel.getTraits()), productRel, joinRel.getRowType(), program, RelCollation.emptyList); } else { newRel = productRel; } call.transformTo(newRel); }
diff --git a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJer.java b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJer.java index ea26e322..363f64d7 100644 --- a/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJer.java +++ b/libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/BridJer.java @@ -1,645 +1,645 @@ /* Copyright (c) 2009-2011 Olivier Chafik, All Rights Reserved This file is part of JNAerator (http://jnaerator.googlecode.com/). JNAerator 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. JNAerator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JNAerator. If not, see <http://www.gnu.org/licenses/>. */ package com.ochafik.lang.jnaerator; import java.util.Iterator; import java.util.Collections; import java.util.Collection; import java.io.PrintStream; import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; import com.ochafik.lang.jnaerator.parser.Statement.ExpressionStatement; import org.bridj.FlagSet; import org.bridj.BridJ; import org.bridj.IntValuedEnum; import org.bridj.StructObject; import org.bridj.ValuedEnum; import org.bridj.cpp.CPPObject; import static com.ochafik.lang.SyntaxUtils.as; //import org.bridj.structs.StructIO; //import org.bridj.structs.Array; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Method; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Pattern; import com.ochafik.lang.jnaerator.JNAeratorConfig.GenFeatures; import com.ochafik.lang.jnaerator.TypeConversion.NL4JConversion; import com.ochafik.lang.jnaerator.cplusplus.CPlusPlusMangler; import com.ochafik.lang.jnaerator.parser.*; import static com.ochafik.lang.jnaerator.parser.Statement.*; import com.ochafik.lang.jnaerator.parser.StoredDeclarations.*; import com.ochafik.lang.jnaerator.parser.Struct.MemberVisibility; import com.ochafik.lang.jnaerator.parser.TypeRef.*; import com.ochafik.lang.jnaerator.parser.Expression.*; import com.ochafik.lang.jnaerator.parser.Function.Type; import com.ochafik.lang.jnaerator.parser.DeclarationsHolder.ListWrapper; import com.ochafik.lang.jnaerator.parser.Declarator.*; import com.ochafik.lang.jnaerator.runtime.VirtualTablePointer; import com.ochafik.util.CompoundCollection; import com.ochafik.util.listenable.Pair; import com.ochafik.util.string.StringUtils; import java.net.URL; import java.net.URLConnection; import java.text.MessageFormat; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.*; import static com.ochafik.lang.jnaerator.TypeConversion.*; import static com.ochafik.lang.jnaerator.MatchingUtils.*; /* mvn -o compile exec:java -Dexec.mainClass=com.ochafik.lang.jnaerator.JNAerator */ public class BridJer { Result result; public BridJer(Result result) { this.result = result; } String primName(TypeRef tr) { tr = tr.clone(); tr.setModifiers(Collections.EMPTY_LIST); return tr.toString(); } String primCapName(TypeRef tr) { return StringUtils.capitalize(primName(tr)); } Expression staticPtrMethod(String name, Expression... args) { return methodCall(expr(typeRef(ptrClass())), name, args); } int iFile = 0; public Pair<Element, List<Declaration>> convertToJava(Element element) { //element = element.clone(); try { PrintStream out = new PrintStream("jnaerator-" + (iFile++) + ".out"); out.println(element); out.close(); } catch (Exception ex) { ex.printStackTrace(); } final List<Declaration> extraDeclarationsOut = new ArrayList<Declaration>(); final Set<Pair<Element, Integer>> referencedElements = new HashSet<Pair<Element, Integer>>(); element.accept(new Scanner() { @Override public void visitUnaryOp(UnaryOp unaryOp) { super.visitUnaryOp(unaryOp); if (unaryOp.getOperator() == UnaryOperator.Reference) { if (unaryOp.getOperand() instanceof VariableRef) { VariableRef vr = (VariableRef)unaryOp.getOperand(); Element e = result.symbols.getVariable(vr.getName()); if (e != null) referencedElements.add(new Pair<Element, Integer>(e, e.getId())); } } } }); final Set<Element> varDeclTypeRefsTransformedToPointers = new HashSet<Element>(); final Map<Integer, String> referencedElementsChangedNames = new HashMap<Integer, String>(); for (Pair<Element, Integer> kv : referencedElements) { Element e = kv.getKey(); //int id = kv if (e instanceof DirectDeclarator) { DirectDeclarator decl = (DirectDeclarator)e; String name = decl.getName(); String changedName = "p" + StringUtils.capitalize(name); referencedElementsChangedNames.put(e.getId(), changedName); decl.setName(changedName); VariablesDeclaration vd = (VariablesDeclaration)decl.getParentElement(); TypeRef tr = vd.getValueType(); //TypeRef wrapper = getWrapperType(tr); //vd.setValueType(pointerToTypeRef(wrapper)); vd.setValueType(new Pointer(tr, PointerStyle.Pointer)); varDeclTypeRefsTransformedToPointers.add(vd); Expression defVal = decl.getDefaultValue(); if (defVal != null) { decl.setDefaultValue(staticPtrMethod("pointerTo" + primCapName(tr), defVal)); } } } // First pass to detect referenced variables (no replacement here) : element.accept(new Scanner() { @Override public void visitIdentifier(Identifier identifier) { super.visitIdentifier(identifier); Element e = result.symbols.getVariable(identifier); if (e != null && isReferenced(e)) { String changedName = referencedElementsChangedNames.get(e.getId()); if (changedName != null) { Identifier replacedIdentifier = ident(changedName); identifier.replaceBy(replacedIdentifier); referencedElements.add(new Pair<Element, Integer>(replacedIdentifier, replacedIdentifier.getId())); } } } boolean isReferenced(Element e) { if (e == null) return false; return referencedElements.contains(new Pair<Element, Integer>(e, e.getId())); } @Override public void visitVariableRef(VariableRef vr) { super.visitVariableRef(vr); Identifier ident = vr.getName(); if (isReferenced(ident)) { vr.replaceBy(methodCall(varRef(ident), "get")); } } @Override public void visitUnaryOp(UnaryOp unaryOp) { if (unaryOp.getOperator() == UnaryOperator.Reference) { if (unaryOp.getOperand() instanceof VariableRef) { VariableRef vr = (VariableRef)unaryOp.getOperand(); Identifier ident = vr.getName(); Element e = result.symbols.getVariable(ident); if ((e != null || isReferenced(e)) || isReferenced(ident)) { String changedName = referencedElementsChangedNames.get(e.getId()); if (changedName != null) { Element rep = varRef(changedName); unaryOp.replaceBy(rep); visit(rep); return; } } } } super.visitUnaryOp(unaryOp); } }); // Second pass : replacement ! element.accept(new Scanner() { @Override public void visitVariableRef(VariableRef vr) { super.visitVariableRef(vr); String identStr = vr.getName() + ""; if ("NULL".equals(identStr)) vr.replaceBy(nullExpr()); } int nConstants = 0; @Override public void visitConstant(Constant c) { if (c.getValue() instanceof String) { //Struct s = c.findParentOfType(Struct.class); Class charClass; String ptrMethodName; if (c.getType() == Constant.Type.LongString) { charClass = Short.class; ptrMethodName = "pointerToWideCString"; } else { charClass = Byte.class; ptrMethodName = "pointerToCString"; } String fieldName = "strConstant" + (++nConstants); VariablesDeclaration staticConstField = new VariablesDeclaration(typeRef(ident(ptrClass(), expr(typeRef(charClass)))), new DirectDeclarator(fieldName, staticPtrMethod(ptrMethodName, c.clone()))); staticConstField.addModifiers(ModifierType.Static, ModifierType.Private, ModifierType.Final); //s.addDeclaration(staticConstField); extraDeclarationsOut.add(staticConstField); c.replaceBy(varRef(fieldName)); return; } super.visitConstant(c); } // // static Map<String, String> primToCapNames = new HashMap<String, String>(); // static { // primToCapNames.put("int", "Int"); // primToCapNames.put("long", "Long"); // primToCapNames.put("short", "Short"); // primToCapNames.put("byte", "Byte"); // primToCapNames.put("double", "Double"); // primToCapNames.put("float", "Float"); // primToCapNames.put("char", "Char"); // primToCapNames.put("boolean", "Boolean"); // } void replaceMalloc(TypeRef pointedType, Element toReplace, Expression sizeExpression) { // TODO handle casts and sizeof expressions ! Pair<TypeRef, Expression> typeAndSize = recognizeSizeOfMult(sizeExpression); if (typeAndSize != null && (pointedType == null || pointedType.equals(typeAndSize.getFirst()))) { String tStr = String.valueOf(typeAndSize.getFirst()); try { JavaPrim prim = JavaPrim.getJavaPrim(tStr); if (prim != null && prim.isPrimitive) { String cap = StringUtils.capitalize(tStr); toReplace.replaceBy(staticPtrMethod("allocate" + cap + "s", typeAndSize.getValue())); return; } } catch (Throwable th) { // Do nothing } } toReplace.replaceBy(staticPtrMethod("allocateBytes", sizeExpression)); } <T extends Element> void visitAllButConstants(List<T> elements) { if (elements == null) return; for (T element : elements) { if (element == null || (element instanceof Constant)) continue; element.accept(this); } } List<Expression> getArgs(List<Pair<String, Expression>> args) { if (args == null) return null; List<Expression> ret = new ArrayList<Expression>(args.size()); for (Pair<String, Expression> p : args) ret.add(p.getValue()); return ret; } @Override public void visitDelete(Delete d) { d.replaceBy(stat(methodCall(d.getValue(), "release"))); } @Override public void visitFunctionCall(FunctionCall fc) { super.visit(fc.getTarget()); super.visit(fc.getFunction()); List<Expression> arguments = getArgs(fc.getArguments()); //super.visitFunctionCall(fc); if (fc.getTarget() == null && (fc.getFunction() instanceof VariableRef)) { Identifier ident = ((VariableRef)fc.getFunction()).getName(); if ((ident instanceof SimpleIdentifier) && ((SimpleIdentifier)ident).getTemplateArguments().isEmpty()) { String name = ident.toString(); int nArgs = arguments == null ? 0 : arguments.size(); Expression arg1 = nArgs > 0 ? arguments.get(0) : null, arg2 = nArgs > 1 ? arguments.get(1) : null, arg3 = nArgs > 2 ? arguments.get(2) : null; if ("printf".equals(name)) { visitAllButConstants(arguments); fc.replaceBy(methodCall(memberRef(expr(typeRef(System.class)), "out"), "println", formatStr(arg1, arguments, 1))); return; } else if ("sprintf".equals(name)) { visitAllButConstants(arguments); fc.replaceBy(methodCall(arg1, "setCString", formatStr(arg2, arguments, 2))); return; } switch (nArgs) { case 1: if ("malloc".equals(name)) { visit(arguments); replaceMalloc(null, fc, arg1); return; } else if ("free".equals(name)) { visit(arguments); fc.replaceBy(methodCall(arg1, "release")); return; } break; case 3: if ("memset".equals(name)) { visit(arguments); Expression value = arg2, num = arg3; if ("0".equals(value + "")) fc.replaceBy(methodCall(arg1, "clearBytes", expr(0), num)); else fc.replaceBy(methodCall(arg1, "clearBytes", expr(0), num, value)); return; } else if ("memcpy".equals(name)) { visit(arguments); Expression dest = arg1, source = arg2, num = arg3; - fc.replaceBy(methodCall(source, "copyBytesTo", expr(0), dest, expr(0), num)); + fc.replaceBy(methodCall(source, "copyBytesAtOffsetTo", expr(0), dest, expr(0), num)); return; } else if ("memmov".equals(name)) { visit(arguments); Expression dest = arg1, source = arg2, num = arg3; - fc.replaceBy(methodCall(source, "moveBytesTo", expr(0), dest, expr(0), num)); + fc.replaceBy(methodCall(source, "moveBytesAtOffsetTo", expr(0), dest, expr(0), num)); return; } else if ("memcmp".equals(name)) { visit(arguments); Expression ptr1 = arg1, ptr2 = arg2, num = arg3; fc.replaceBy(methodCall(ptr1, "compareBytes", ptr2, num)); return; } break; } } } visit(arguments); } Expression formatStr(Expression str, List<Expression> arguments, int argsToSkip) { if (arguments.isEmpty()) return str; List<Expression> fmtArgs = new ArrayList<Expression>(); if (!(str instanceof Constant)) str = methodCall(str, "getCString"); fmtArgs.add(str); for (int i = argsToSkip, nArgs = arguments.size(); i < nArgs; i++) fmtArgs.add(arguments.get(i)); return methodCall(expr(typeRef(String.class)), "format", fmtArgs.toArray(new Expression[fmtArgs.size()])); } @Override public void visitIf(If ifStat) { super.visitIf(ifStat); Expression cond = ifStat.getCondition(); if (!(cond instanceof BinaryOp)) // TODO use typing rather than this hack to detect implicit boolean conversion in if statements (and not only there) cond.replaceBy(expr(cond, BinaryOperator.IsDifferent, expr(0))); } @Override public void visitUnaryOp(UnaryOp unaryOp) { super.visitUnaryOp(unaryOp); switch (unaryOp.getOperator()) { case Dereference: unaryOp.replaceBy(methodCall(unaryOp.getOperand(), "get")); break; case Reference: // TODO handle special case of referenced primitives, for instance unaryOp.replaceBy(methodCall(unaryOp.getOperand(), "getReference")); break; } } @Override public void visitCast(Cast cast) { super.visitCast(cast); if (cast.getType() instanceof TargettedTypeRef) { - cast.replaceBy(methodCall(cast.getTarget(), "asPointerTo", result.typeConverter.typeLiteral(((TargettedTypeRef)cast.getType()).getTarget()))); + cast.replaceBy(methodCall(cast.getTarget(), "as", result.typeConverter.typeLiteral(((TargettedTypeRef)cast.getType()).getTarget()))); } } @Override public void visitArrayAccess(ArrayAccess arrayAccess) { super.visitArrayAccess(arrayAccess); arrayAccess.replaceBy(methodCall(arrayAccess.getTarget(), "get", arrayAccess.getIndex())); } @Override public void visitMemberRef(MemberRef memberRef) { // TODO restrict to struct/class fields // TODO handle global variables with explicit namespaces... if (!(memberRef.getParentElement() instanceof FunctionCall)) { if (memberRef.getName() != null) { switch (memberRef.getMemberRefStyle()) { case Colons: memberRef.setMemberRefStyle(MemberRefStyle.Dot); break; case Arrow: case Dot: Expression rep = methodCall(memberRef.getTarget(), memberRef.getName().toString()); if (memberRef.getMemberRefStyle() == MemberRefStyle.Arrow) rep = methodCall(rep, "get"); memberRef.replaceBy(rep); rep.accept(this); return; } } } super.visitMemberRef(memberRef); } @Override public void visitVariablesDeclaration(VariablesDeclaration v) { super.visitVariablesDeclaration(v); if (v.getDeclarators().size() == 1) { Declarator decl = v.getDeclarators().get(0); //DirectDeclarator decl = (DirectDeclarator); TypeRef vt = v.getValueType(); MutableByDeclarator mt = decl instanceof DirectDeclarator ? vt : decl.mutateType(vt); if (mt instanceof TypeRef) { TypeRef mutatedType = (TypeRef)mt; if (decl.getDefaultValue() == null) { TypeRef actualType = mutatedType; boolean referenced = varDeclTypeRefsTransformedToPointers.contains(v) && (mutatedType instanceof Pointer); if (referenced) { actualType = ((Pointer)mutatedType).getTarget(); } if (result.symbols.isClassType(actualType)) { decl.setDefaultValue(referenced ? staticPtrMethod("allocate", result.typeConverter.typeLiteral(actualType)) : new Expression.New(actualType.clone())); Expression vr = varRef(new SimpleIdentifier(decl.resolveName())); Statement deleteStat = stat(methodCall(expr(typeRef(BridJ.class)), "delete", referenced ? methodCall(vr, "get") : vr)); deleteStat.setCommentAfter("// object would end up being deleted by the GC later, but in C++ it would be deleted here."); Statement.Block parentBlock = (Statement.Block)v.getParentElement(); List<Statement> stats = new ArrayList<Statement>(parentBlock.getStatements()); for (int i = stats.size(); i-- != 0;) { Statement stat = stats.get(i); if (!(stat instanceof Statement.Return) && !deleteStatements.contains(stat)) { stats.add(i + 1, deleteStat); deleteStatements.add(deleteStat); break; } } parentBlock.setStatements(stats); } }// else { TypeConversion.NL4JConversion conv = result.typeConverter.convertTypeToNL4J( mutatedType, null,//callerLibraryName, null,//thisField("io"), null,//varRef(name), -1,//fieldIndex, -1//bits ); v.setValueType(conv.typeRef); if (conv.arrayLengths != null && (mutatedType instanceof TargettedTypeRef) && decl.getDefaultValue() == null) v.setDeclarators(Arrays.asList((Declarator)new DirectDeclarator(decl.resolveName(), newAllocateArray(((TargettedTypeRef)mutatedType).getTarget(), conv.arrayLengths)))); //} } } } Set<Element> deleteStatements = new HashSet<Element>(); @Override public void visitAssignmentOp(AssignmentOp assignment) { BinaryOperator binOp = assignment.getOperator().getCorrespondingBinaryOp(); Expression value = assignment.getValue(); value.setParenthesisIfNeeded(); if (assignment.getTarget() instanceof UnaryOp) { UnaryOp uop = (UnaryOp)assignment.getTarget(); if (uop.getOperator() == UnaryOperator.Dereference) { visit(uop.getOperand()); visit(assignment.getValue()); Expression target = uop.getOperand(); if (binOp != null) { value = expr(methodCall(target.clone(), "get"), binOp, value); } assignment.replaceBy(methodCall(target, "set", value)); return; } } if (assignment.getTarget() instanceof ArrayAccess) { ArrayAccess aa = (ArrayAccess)assignment.getTarget(); visit(aa.getTarget()); visit(aa.getIndex()); visit(assignment.getValue()); Expression target = aa.getTarget(); Expression index = aa.getIndex(); if (binOp != null) { value = expr(methodCall(target.clone(), "get", index.clone()), binOp, value); } assignment.replaceBy(methodCall(target, "set", index, value)); return; } if (assignment.getTarget() instanceof MemberRef) { MemberRef mr = (MemberRef)assignment.getTarget(); boolean isArrow = mr.getMemberRefStyle() == MemberRefStyle.Arrow; if (isArrow || mr.getMemberRefStyle() == MemberRefStyle.Dot) { Expression target = mr.getTarget(); String name = mr.getName().toString(); if (binOp != null) { value = expr(methodCall(target.clone(), name), binOp, value); } if (isArrow) target = methodCall(target, "get"); assignment.replaceBy(methodCall(target, name, value)); return; } } super.visitAssignmentOp(assignment); } @Override public void visitNew(New new1) { super.visitNew(new1); if (new1.getConstruction() == null) new1.replaceBy(staticPtrMethod("allocate" + primCapName(new1.getType()))); } public void notSup(Element x, String msg) throws UnsupportedConversionException { throw new UnsupportedConversionException(x, msg); } /* @Override public void visitExpressionStatement(ExpressionStatement expressionStatement) { super.visitExpressionStatement(expressionStatement); if (expressionStatement.getExpression() instanceof UnaryOp) { UnaryOp uop = (UnaryOp)expressionStatement.getExpression(); Expression target = uop.getOperand(); switch (uop.getOperator()) { case PostIncr: case PreIncr: expressionStatement.replaceBy(expr(target)); } } }*/ Expression newAllocateArray(TypeRef tr, Collection<Expression> sizes) { return staticPtrMethod( "allocate" + primCapName(tr) + "s", sizes.toArray(new Expression[sizes.size()]) ); } @Override public void visitNewArray(NewArray newArray) { super.visitNewArray(newArray); if (newArray.getType() instanceof Primitive) { if (newArray.getDimensions().size() > 3) notSup(newArray, "TODO only dimensions 1 to 3 are supported for primitive array creations !"); newArray.replaceBy(newAllocateArray(newArray.getType(), newArray.getDimensions())); } else { if (newArray.getDimensions().size() != 1) notSup(newArray, "TODO only dimension 1 is supported for reference array creations !"); newArray.replaceBy( staticPtrMethod( "allocateArray", result.typeConverter.typeLiteral(newArray.getType()), newArray.getDimensions().get(0) ) ); } } @Override public void visitPointer(Pointer pointer) { super.visitPointer(pointer); } /* @Override protected void visitTargettedTypeRef(TargettedTypeRef targettedTypeRef) { super.visitTargettedTypeRef(targettedTypeRef); if (targettedTypeRef.getTarget() != null) targettedTypeRef.replaceBy(pointerToTypeRef(targettedTypeRef.getTarget().clone())); }*/ }); return new Pair<Element, List<Declaration>>(element, extraDeclarationsOut); } TypeRef getWrapperType(TypeRef tr) { JavaPrim prim = result.typeConverter.getPrimitive(tr, null); if (prim != null) return typeRef(prim.wrapperType); return tr; } TypeRef pointerToTypeRef(TypeRef targetType) { Identifier id = ident(ptrClass()); id.resolveLastSimpleIdentifier().addTemplateArgument(expr(targetType)); return typeRef(id); } Class ptrClass() { return result.config.runtime.pointerClass; } }
false
true
public Pair<Element, List<Declaration>> convertToJava(Element element) { //element = element.clone(); try { PrintStream out = new PrintStream("jnaerator-" + (iFile++) + ".out"); out.println(element); out.close(); } catch (Exception ex) { ex.printStackTrace(); } final List<Declaration> extraDeclarationsOut = new ArrayList<Declaration>(); final Set<Pair<Element, Integer>> referencedElements = new HashSet<Pair<Element, Integer>>(); element.accept(new Scanner() { @Override public void visitUnaryOp(UnaryOp unaryOp) { super.visitUnaryOp(unaryOp); if (unaryOp.getOperator() == UnaryOperator.Reference) { if (unaryOp.getOperand() instanceof VariableRef) { VariableRef vr = (VariableRef)unaryOp.getOperand(); Element e = result.symbols.getVariable(vr.getName()); if (e != null) referencedElements.add(new Pair<Element, Integer>(e, e.getId())); } } } }); final Set<Element> varDeclTypeRefsTransformedToPointers = new HashSet<Element>(); final Map<Integer, String> referencedElementsChangedNames = new HashMap<Integer, String>(); for (Pair<Element, Integer> kv : referencedElements) { Element e = kv.getKey(); //int id = kv if (e instanceof DirectDeclarator) { DirectDeclarator decl = (DirectDeclarator)e; String name = decl.getName(); String changedName = "p" + StringUtils.capitalize(name); referencedElementsChangedNames.put(e.getId(), changedName); decl.setName(changedName); VariablesDeclaration vd = (VariablesDeclaration)decl.getParentElement(); TypeRef tr = vd.getValueType(); //TypeRef wrapper = getWrapperType(tr); //vd.setValueType(pointerToTypeRef(wrapper)); vd.setValueType(new Pointer(tr, PointerStyle.Pointer)); varDeclTypeRefsTransformedToPointers.add(vd); Expression defVal = decl.getDefaultValue(); if (defVal != null) { decl.setDefaultValue(staticPtrMethod("pointerTo" + primCapName(tr), defVal)); } } } // First pass to detect referenced variables (no replacement here) : element.accept(new Scanner() { @Override public void visitIdentifier(Identifier identifier) { super.visitIdentifier(identifier); Element e = result.symbols.getVariable(identifier); if (e != null && isReferenced(e)) { String changedName = referencedElementsChangedNames.get(e.getId()); if (changedName != null) { Identifier replacedIdentifier = ident(changedName); identifier.replaceBy(replacedIdentifier); referencedElements.add(new Pair<Element, Integer>(replacedIdentifier, replacedIdentifier.getId())); } } } boolean isReferenced(Element e) { if (e == null) return false; return referencedElements.contains(new Pair<Element, Integer>(e, e.getId())); } @Override public void visitVariableRef(VariableRef vr) { super.visitVariableRef(vr); Identifier ident = vr.getName(); if (isReferenced(ident)) { vr.replaceBy(methodCall(varRef(ident), "get")); } } @Override public void visitUnaryOp(UnaryOp unaryOp) { if (unaryOp.getOperator() == UnaryOperator.Reference) { if (unaryOp.getOperand() instanceof VariableRef) { VariableRef vr = (VariableRef)unaryOp.getOperand(); Identifier ident = vr.getName(); Element e = result.symbols.getVariable(ident); if ((e != null || isReferenced(e)) || isReferenced(ident)) { String changedName = referencedElementsChangedNames.get(e.getId()); if (changedName != null) { Element rep = varRef(changedName); unaryOp.replaceBy(rep); visit(rep); return; } } } } super.visitUnaryOp(unaryOp); } }); // Second pass : replacement ! element.accept(new Scanner() { @Override public void visitVariableRef(VariableRef vr) { super.visitVariableRef(vr); String identStr = vr.getName() + ""; if ("NULL".equals(identStr)) vr.replaceBy(nullExpr()); } int nConstants = 0; @Override public void visitConstant(Constant c) { if (c.getValue() instanceof String) { //Struct s = c.findParentOfType(Struct.class); Class charClass; String ptrMethodName; if (c.getType() == Constant.Type.LongString) { charClass = Short.class; ptrMethodName = "pointerToWideCString"; } else { charClass = Byte.class; ptrMethodName = "pointerToCString"; } String fieldName = "strConstant" + (++nConstants); VariablesDeclaration staticConstField = new VariablesDeclaration(typeRef(ident(ptrClass(), expr(typeRef(charClass)))), new DirectDeclarator(fieldName, staticPtrMethod(ptrMethodName, c.clone()))); staticConstField.addModifiers(ModifierType.Static, ModifierType.Private, ModifierType.Final); //s.addDeclaration(staticConstField); extraDeclarationsOut.add(staticConstField); c.replaceBy(varRef(fieldName)); return; } super.visitConstant(c); } // // static Map<String, String> primToCapNames = new HashMap<String, String>(); // static { // primToCapNames.put("int", "Int"); // primToCapNames.put("long", "Long"); // primToCapNames.put("short", "Short"); // primToCapNames.put("byte", "Byte"); // primToCapNames.put("double", "Double"); // primToCapNames.put("float", "Float"); // primToCapNames.put("char", "Char"); // primToCapNames.put("boolean", "Boolean"); // } void replaceMalloc(TypeRef pointedType, Element toReplace, Expression sizeExpression) { // TODO handle casts and sizeof expressions ! Pair<TypeRef, Expression> typeAndSize = recognizeSizeOfMult(sizeExpression); if (typeAndSize != null && (pointedType == null || pointedType.equals(typeAndSize.getFirst()))) { String tStr = String.valueOf(typeAndSize.getFirst()); try { JavaPrim prim = JavaPrim.getJavaPrim(tStr); if (prim != null && prim.isPrimitive) { String cap = StringUtils.capitalize(tStr); toReplace.replaceBy(staticPtrMethod("allocate" + cap + "s", typeAndSize.getValue())); return; } } catch (Throwable th) { // Do nothing } } toReplace.replaceBy(staticPtrMethod("allocateBytes", sizeExpression)); } <T extends Element> void visitAllButConstants(List<T> elements) { if (elements == null) return; for (T element : elements) { if (element == null || (element instanceof Constant)) continue; element.accept(this); } } List<Expression> getArgs(List<Pair<String, Expression>> args) { if (args == null) return null; List<Expression> ret = new ArrayList<Expression>(args.size()); for (Pair<String, Expression> p : args) ret.add(p.getValue()); return ret; } @Override public void visitDelete(Delete d) { d.replaceBy(stat(methodCall(d.getValue(), "release"))); } @Override public void visitFunctionCall(FunctionCall fc) { super.visit(fc.getTarget()); super.visit(fc.getFunction()); List<Expression> arguments = getArgs(fc.getArguments()); //super.visitFunctionCall(fc); if (fc.getTarget() == null && (fc.getFunction() instanceof VariableRef)) { Identifier ident = ((VariableRef)fc.getFunction()).getName(); if ((ident instanceof SimpleIdentifier) && ((SimpleIdentifier)ident).getTemplateArguments().isEmpty()) { String name = ident.toString(); int nArgs = arguments == null ? 0 : arguments.size(); Expression arg1 = nArgs > 0 ? arguments.get(0) : null, arg2 = nArgs > 1 ? arguments.get(1) : null, arg3 = nArgs > 2 ? arguments.get(2) : null; if ("printf".equals(name)) { visitAllButConstants(arguments); fc.replaceBy(methodCall(memberRef(expr(typeRef(System.class)), "out"), "println", formatStr(arg1, arguments, 1))); return; } else if ("sprintf".equals(name)) { visitAllButConstants(arguments); fc.replaceBy(methodCall(arg1, "setCString", formatStr(arg2, arguments, 2))); return; } switch (nArgs) { case 1: if ("malloc".equals(name)) { visit(arguments); replaceMalloc(null, fc, arg1); return; } else if ("free".equals(name)) { visit(arguments); fc.replaceBy(methodCall(arg1, "release")); return; } break; case 3: if ("memset".equals(name)) { visit(arguments); Expression value = arg2, num = arg3; if ("0".equals(value + "")) fc.replaceBy(methodCall(arg1, "clearBytes", expr(0), num)); else fc.replaceBy(methodCall(arg1, "clearBytes", expr(0), num, value)); return; } else if ("memcpy".equals(name)) { visit(arguments); Expression dest = arg1, source = arg2, num = arg3; fc.replaceBy(methodCall(source, "copyBytesTo", expr(0), dest, expr(0), num)); return; } else if ("memmov".equals(name)) { visit(arguments); Expression dest = arg1, source = arg2, num = arg3; fc.replaceBy(methodCall(source, "moveBytesTo", expr(0), dest, expr(0), num)); return; } else if ("memcmp".equals(name)) { visit(arguments); Expression ptr1 = arg1, ptr2 = arg2, num = arg3; fc.replaceBy(methodCall(ptr1, "compareBytes", ptr2, num)); return; } break; } } } visit(arguments); } Expression formatStr(Expression str, List<Expression> arguments, int argsToSkip) { if (arguments.isEmpty()) return str; List<Expression> fmtArgs = new ArrayList<Expression>(); if (!(str instanceof Constant)) str = methodCall(str, "getCString"); fmtArgs.add(str); for (int i = argsToSkip, nArgs = arguments.size(); i < nArgs; i++) fmtArgs.add(arguments.get(i)); return methodCall(expr(typeRef(String.class)), "format", fmtArgs.toArray(new Expression[fmtArgs.size()])); } @Override public void visitIf(If ifStat) { super.visitIf(ifStat); Expression cond = ifStat.getCondition(); if (!(cond instanceof BinaryOp)) // TODO use typing rather than this hack to detect implicit boolean conversion in if statements (and not only there) cond.replaceBy(expr(cond, BinaryOperator.IsDifferent, expr(0))); } @Override public void visitUnaryOp(UnaryOp unaryOp) { super.visitUnaryOp(unaryOp); switch (unaryOp.getOperator()) { case Dereference: unaryOp.replaceBy(methodCall(unaryOp.getOperand(), "get")); break; case Reference: // TODO handle special case of referenced primitives, for instance unaryOp.replaceBy(methodCall(unaryOp.getOperand(), "getReference")); break; } } @Override public void visitCast(Cast cast) { super.visitCast(cast); if (cast.getType() instanceof TargettedTypeRef) { cast.replaceBy(methodCall(cast.getTarget(), "asPointerTo", result.typeConverter.typeLiteral(((TargettedTypeRef)cast.getType()).getTarget()))); } } @Override public void visitArrayAccess(ArrayAccess arrayAccess) { super.visitArrayAccess(arrayAccess); arrayAccess.replaceBy(methodCall(arrayAccess.getTarget(), "get", arrayAccess.getIndex())); } @Override public void visitMemberRef(MemberRef memberRef) { // TODO restrict to struct/class fields // TODO handle global variables with explicit namespaces... if (!(memberRef.getParentElement() instanceof FunctionCall)) { if (memberRef.getName() != null) { switch (memberRef.getMemberRefStyle()) { case Colons: memberRef.setMemberRefStyle(MemberRefStyle.Dot); break; case Arrow: case Dot: Expression rep = methodCall(memberRef.getTarget(), memberRef.getName().toString()); if (memberRef.getMemberRefStyle() == MemberRefStyle.Arrow) rep = methodCall(rep, "get"); memberRef.replaceBy(rep); rep.accept(this); return; } } } super.visitMemberRef(memberRef); } @Override public void visitVariablesDeclaration(VariablesDeclaration v) { super.visitVariablesDeclaration(v); if (v.getDeclarators().size() == 1) { Declarator decl = v.getDeclarators().get(0); //DirectDeclarator decl = (DirectDeclarator); TypeRef vt = v.getValueType(); MutableByDeclarator mt = decl instanceof DirectDeclarator ? vt : decl.mutateType(vt); if (mt instanceof TypeRef) { TypeRef mutatedType = (TypeRef)mt; if (decl.getDefaultValue() == null) { TypeRef actualType = mutatedType; boolean referenced = varDeclTypeRefsTransformedToPointers.contains(v) && (mutatedType instanceof Pointer); if (referenced) { actualType = ((Pointer)mutatedType).getTarget(); } if (result.symbols.isClassType(actualType)) { decl.setDefaultValue(referenced ? staticPtrMethod("allocate", result.typeConverter.typeLiteral(actualType)) : new Expression.New(actualType.clone())); Expression vr = varRef(new SimpleIdentifier(decl.resolveName())); Statement deleteStat = stat(methodCall(expr(typeRef(BridJ.class)), "delete", referenced ? methodCall(vr, "get") : vr)); deleteStat.setCommentAfter("// object would end up being deleted by the GC later, but in C++ it would be deleted here."); Statement.Block parentBlock = (Statement.Block)v.getParentElement(); List<Statement> stats = new ArrayList<Statement>(parentBlock.getStatements()); for (int i = stats.size(); i-- != 0;) { Statement stat = stats.get(i); if (!(stat instanceof Statement.Return) && !deleteStatements.contains(stat)) { stats.add(i + 1, deleteStat); deleteStatements.add(deleteStat); break; } } parentBlock.setStatements(stats); } }// else { TypeConversion.NL4JConversion conv = result.typeConverter.convertTypeToNL4J( mutatedType, null,//callerLibraryName, null,//thisField("io"), null,//varRef(name), -1,//fieldIndex, -1//bits ); v.setValueType(conv.typeRef); if (conv.arrayLengths != null && (mutatedType instanceof TargettedTypeRef) && decl.getDefaultValue() == null) v.setDeclarators(Arrays.asList((Declarator)new DirectDeclarator(decl.resolveName(), newAllocateArray(((TargettedTypeRef)mutatedType).getTarget(), conv.arrayLengths)))); //} } } } Set<Element> deleteStatements = new HashSet<Element>(); @Override public void visitAssignmentOp(AssignmentOp assignment) { BinaryOperator binOp = assignment.getOperator().getCorrespondingBinaryOp(); Expression value = assignment.getValue(); value.setParenthesisIfNeeded(); if (assignment.getTarget() instanceof UnaryOp) { UnaryOp uop = (UnaryOp)assignment.getTarget(); if (uop.getOperator() == UnaryOperator.Dereference) { visit(uop.getOperand()); visit(assignment.getValue()); Expression target = uop.getOperand(); if (binOp != null) { value = expr(methodCall(target.clone(), "get"), binOp, value); } assignment.replaceBy(methodCall(target, "set", value)); return; } } if (assignment.getTarget() instanceof ArrayAccess) { ArrayAccess aa = (ArrayAccess)assignment.getTarget(); visit(aa.getTarget()); visit(aa.getIndex()); visit(assignment.getValue()); Expression target = aa.getTarget(); Expression index = aa.getIndex(); if (binOp != null) { value = expr(methodCall(target.clone(), "get", index.clone()), binOp, value); } assignment.replaceBy(methodCall(target, "set", index, value)); return; } if (assignment.getTarget() instanceof MemberRef) { MemberRef mr = (MemberRef)assignment.getTarget(); boolean isArrow = mr.getMemberRefStyle() == MemberRefStyle.Arrow; if (isArrow || mr.getMemberRefStyle() == MemberRefStyle.Dot) { Expression target = mr.getTarget(); String name = mr.getName().toString(); if (binOp != null) { value = expr(methodCall(target.clone(), name), binOp, value); } if (isArrow) target = methodCall(target, "get"); assignment.replaceBy(methodCall(target, name, value)); return; } } super.visitAssignmentOp(assignment); } @Override public void visitNew(New new1) { super.visitNew(new1); if (new1.getConstruction() == null) new1.replaceBy(staticPtrMethod("allocate" + primCapName(new1.getType()))); } public void notSup(Element x, String msg) throws UnsupportedConversionException { throw new UnsupportedConversionException(x, msg); } /* @Override public void visitExpressionStatement(ExpressionStatement expressionStatement) { super.visitExpressionStatement(expressionStatement); if (expressionStatement.getExpression() instanceof UnaryOp) { UnaryOp uop = (UnaryOp)expressionStatement.getExpression(); Expression target = uop.getOperand(); switch (uop.getOperator()) { case PostIncr: case PreIncr: expressionStatement.replaceBy(expr(target)); } } }*/ Expression newAllocateArray(TypeRef tr, Collection<Expression> sizes) { return staticPtrMethod( "allocate" + primCapName(tr) + "s", sizes.toArray(new Expression[sizes.size()]) ); } @Override public void visitNewArray(NewArray newArray) { super.visitNewArray(newArray); if (newArray.getType() instanceof Primitive) { if (newArray.getDimensions().size() > 3) notSup(newArray, "TODO only dimensions 1 to 3 are supported for primitive array creations !"); newArray.replaceBy(newAllocateArray(newArray.getType(), newArray.getDimensions())); } else { if (newArray.getDimensions().size() != 1) notSup(newArray, "TODO only dimension 1 is supported for reference array creations !"); newArray.replaceBy( staticPtrMethod( "allocateArray", result.typeConverter.typeLiteral(newArray.getType()), newArray.getDimensions().get(0) ) ); } } @Override public void visitPointer(Pointer pointer) { super.visitPointer(pointer); } /* @Override protected void visitTargettedTypeRef(TargettedTypeRef targettedTypeRef) { super.visitTargettedTypeRef(targettedTypeRef); if (targettedTypeRef.getTarget() != null) targettedTypeRef.replaceBy(pointerToTypeRef(targettedTypeRef.getTarget().clone())); }*/ }); return new Pair<Element, List<Declaration>>(element, extraDeclarationsOut); } TypeRef getWrapperType(TypeRef tr) { JavaPrim prim = result.typeConverter.getPrimitive(tr, null); if (prim != null) return typeRef(prim.wrapperType); return tr; } TypeRef pointerToTypeRef(TypeRef targetType) { Identifier id = ident(ptrClass()); id.resolveLastSimpleIdentifier().addTemplateArgument(expr(targetType)); return typeRef(id); } Class ptrClass() { return result.config.runtime.pointerClass; } }
public Pair<Element, List<Declaration>> convertToJava(Element element) { //element = element.clone(); try { PrintStream out = new PrintStream("jnaerator-" + (iFile++) + ".out"); out.println(element); out.close(); } catch (Exception ex) { ex.printStackTrace(); } final List<Declaration> extraDeclarationsOut = new ArrayList<Declaration>(); final Set<Pair<Element, Integer>> referencedElements = new HashSet<Pair<Element, Integer>>(); element.accept(new Scanner() { @Override public void visitUnaryOp(UnaryOp unaryOp) { super.visitUnaryOp(unaryOp); if (unaryOp.getOperator() == UnaryOperator.Reference) { if (unaryOp.getOperand() instanceof VariableRef) { VariableRef vr = (VariableRef)unaryOp.getOperand(); Element e = result.symbols.getVariable(vr.getName()); if (e != null) referencedElements.add(new Pair<Element, Integer>(e, e.getId())); } } } }); final Set<Element> varDeclTypeRefsTransformedToPointers = new HashSet<Element>(); final Map<Integer, String> referencedElementsChangedNames = new HashMap<Integer, String>(); for (Pair<Element, Integer> kv : referencedElements) { Element e = kv.getKey(); //int id = kv if (e instanceof DirectDeclarator) { DirectDeclarator decl = (DirectDeclarator)e; String name = decl.getName(); String changedName = "p" + StringUtils.capitalize(name); referencedElementsChangedNames.put(e.getId(), changedName); decl.setName(changedName); VariablesDeclaration vd = (VariablesDeclaration)decl.getParentElement(); TypeRef tr = vd.getValueType(); //TypeRef wrapper = getWrapperType(tr); //vd.setValueType(pointerToTypeRef(wrapper)); vd.setValueType(new Pointer(tr, PointerStyle.Pointer)); varDeclTypeRefsTransformedToPointers.add(vd); Expression defVal = decl.getDefaultValue(); if (defVal != null) { decl.setDefaultValue(staticPtrMethod("pointerTo" + primCapName(tr), defVal)); } } } // First pass to detect referenced variables (no replacement here) : element.accept(new Scanner() { @Override public void visitIdentifier(Identifier identifier) { super.visitIdentifier(identifier); Element e = result.symbols.getVariable(identifier); if (e != null && isReferenced(e)) { String changedName = referencedElementsChangedNames.get(e.getId()); if (changedName != null) { Identifier replacedIdentifier = ident(changedName); identifier.replaceBy(replacedIdentifier); referencedElements.add(new Pair<Element, Integer>(replacedIdentifier, replacedIdentifier.getId())); } } } boolean isReferenced(Element e) { if (e == null) return false; return referencedElements.contains(new Pair<Element, Integer>(e, e.getId())); } @Override public void visitVariableRef(VariableRef vr) { super.visitVariableRef(vr); Identifier ident = vr.getName(); if (isReferenced(ident)) { vr.replaceBy(methodCall(varRef(ident), "get")); } } @Override public void visitUnaryOp(UnaryOp unaryOp) { if (unaryOp.getOperator() == UnaryOperator.Reference) { if (unaryOp.getOperand() instanceof VariableRef) { VariableRef vr = (VariableRef)unaryOp.getOperand(); Identifier ident = vr.getName(); Element e = result.symbols.getVariable(ident); if ((e != null || isReferenced(e)) || isReferenced(ident)) { String changedName = referencedElementsChangedNames.get(e.getId()); if (changedName != null) { Element rep = varRef(changedName); unaryOp.replaceBy(rep); visit(rep); return; } } } } super.visitUnaryOp(unaryOp); } }); // Second pass : replacement ! element.accept(new Scanner() { @Override public void visitVariableRef(VariableRef vr) { super.visitVariableRef(vr); String identStr = vr.getName() + ""; if ("NULL".equals(identStr)) vr.replaceBy(nullExpr()); } int nConstants = 0; @Override public void visitConstant(Constant c) { if (c.getValue() instanceof String) { //Struct s = c.findParentOfType(Struct.class); Class charClass; String ptrMethodName; if (c.getType() == Constant.Type.LongString) { charClass = Short.class; ptrMethodName = "pointerToWideCString"; } else { charClass = Byte.class; ptrMethodName = "pointerToCString"; } String fieldName = "strConstant" + (++nConstants); VariablesDeclaration staticConstField = new VariablesDeclaration(typeRef(ident(ptrClass(), expr(typeRef(charClass)))), new DirectDeclarator(fieldName, staticPtrMethod(ptrMethodName, c.clone()))); staticConstField.addModifiers(ModifierType.Static, ModifierType.Private, ModifierType.Final); //s.addDeclaration(staticConstField); extraDeclarationsOut.add(staticConstField); c.replaceBy(varRef(fieldName)); return; } super.visitConstant(c); } // // static Map<String, String> primToCapNames = new HashMap<String, String>(); // static { // primToCapNames.put("int", "Int"); // primToCapNames.put("long", "Long"); // primToCapNames.put("short", "Short"); // primToCapNames.put("byte", "Byte"); // primToCapNames.put("double", "Double"); // primToCapNames.put("float", "Float"); // primToCapNames.put("char", "Char"); // primToCapNames.put("boolean", "Boolean"); // } void replaceMalloc(TypeRef pointedType, Element toReplace, Expression sizeExpression) { // TODO handle casts and sizeof expressions ! Pair<TypeRef, Expression> typeAndSize = recognizeSizeOfMult(sizeExpression); if (typeAndSize != null && (pointedType == null || pointedType.equals(typeAndSize.getFirst()))) { String tStr = String.valueOf(typeAndSize.getFirst()); try { JavaPrim prim = JavaPrim.getJavaPrim(tStr); if (prim != null && prim.isPrimitive) { String cap = StringUtils.capitalize(tStr); toReplace.replaceBy(staticPtrMethod("allocate" + cap + "s", typeAndSize.getValue())); return; } } catch (Throwable th) { // Do nothing } } toReplace.replaceBy(staticPtrMethod("allocateBytes", sizeExpression)); } <T extends Element> void visitAllButConstants(List<T> elements) { if (elements == null) return; for (T element : elements) { if (element == null || (element instanceof Constant)) continue; element.accept(this); } } List<Expression> getArgs(List<Pair<String, Expression>> args) { if (args == null) return null; List<Expression> ret = new ArrayList<Expression>(args.size()); for (Pair<String, Expression> p : args) ret.add(p.getValue()); return ret; } @Override public void visitDelete(Delete d) { d.replaceBy(stat(methodCall(d.getValue(), "release"))); } @Override public void visitFunctionCall(FunctionCall fc) { super.visit(fc.getTarget()); super.visit(fc.getFunction()); List<Expression> arguments = getArgs(fc.getArguments()); //super.visitFunctionCall(fc); if (fc.getTarget() == null && (fc.getFunction() instanceof VariableRef)) { Identifier ident = ((VariableRef)fc.getFunction()).getName(); if ((ident instanceof SimpleIdentifier) && ((SimpleIdentifier)ident).getTemplateArguments().isEmpty()) { String name = ident.toString(); int nArgs = arguments == null ? 0 : arguments.size(); Expression arg1 = nArgs > 0 ? arguments.get(0) : null, arg2 = nArgs > 1 ? arguments.get(1) : null, arg3 = nArgs > 2 ? arguments.get(2) : null; if ("printf".equals(name)) { visitAllButConstants(arguments); fc.replaceBy(methodCall(memberRef(expr(typeRef(System.class)), "out"), "println", formatStr(arg1, arguments, 1))); return; } else if ("sprintf".equals(name)) { visitAllButConstants(arguments); fc.replaceBy(methodCall(arg1, "setCString", formatStr(arg2, arguments, 2))); return; } switch (nArgs) { case 1: if ("malloc".equals(name)) { visit(arguments); replaceMalloc(null, fc, arg1); return; } else if ("free".equals(name)) { visit(arguments); fc.replaceBy(methodCall(arg1, "release")); return; } break; case 3: if ("memset".equals(name)) { visit(arguments); Expression value = arg2, num = arg3; if ("0".equals(value + "")) fc.replaceBy(methodCall(arg1, "clearBytes", expr(0), num)); else fc.replaceBy(methodCall(arg1, "clearBytes", expr(0), num, value)); return; } else if ("memcpy".equals(name)) { visit(arguments); Expression dest = arg1, source = arg2, num = arg3; fc.replaceBy(methodCall(source, "copyBytesAtOffsetTo", expr(0), dest, expr(0), num)); return; } else if ("memmov".equals(name)) { visit(arguments); Expression dest = arg1, source = arg2, num = arg3; fc.replaceBy(methodCall(source, "moveBytesAtOffsetTo", expr(0), dest, expr(0), num)); return; } else if ("memcmp".equals(name)) { visit(arguments); Expression ptr1 = arg1, ptr2 = arg2, num = arg3; fc.replaceBy(methodCall(ptr1, "compareBytes", ptr2, num)); return; } break; } } } visit(arguments); } Expression formatStr(Expression str, List<Expression> arguments, int argsToSkip) { if (arguments.isEmpty()) return str; List<Expression> fmtArgs = new ArrayList<Expression>(); if (!(str instanceof Constant)) str = methodCall(str, "getCString"); fmtArgs.add(str); for (int i = argsToSkip, nArgs = arguments.size(); i < nArgs; i++) fmtArgs.add(arguments.get(i)); return methodCall(expr(typeRef(String.class)), "format", fmtArgs.toArray(new Expression[fmtArgs.size()])); } @Override public void visitIf(If ifStat) { super.visitIf(ifStat); Expression cond = ifStat.getCondition(); if (!(cond instanceof BinaryOp)) // TODO use typing rather than this hack to detect implicit boolean conversion in if statements (and not only there) cond.replaceBy(expr(cond, BinaryOperator.IsDifferent, expr(0))); } @Override public void visitUnaryOp(UnaryOp unaryOp) { super.visitUnaryOp(unaryOp); switch (unaryOp.getOperator()) { case Dereference: unaryOp.replaceBy(methodCall(unaryOp.getOperand(), "get")); break; case Reference: // TODO handle special case of referenced primitives, for instance unaryOp.replaceBy(methodCall(unaryOp.getOperand(), "getReference")); break; } } @Override public void visitCast(Cast cast) { super.visitCast(cast); if (cast.getType() instanceof TargettedTypeRef) { cast.replaceBy(methodCall(cast.getTarget(), "as", result.typeConverter.typeLiteral(((TargettedTypeRef)cast.getType()).getTarget()))); } } @Override public void visitArrayAccess(ArrayAccess arrayAccess) { super.visitArrayAccess(arrayAccess); arrayAccess.replaceBy(methodCall(arrayAccess.getTarget(), "get", arrayAccess.getIndex())); } @Override public void visitMemberRef(MemberRef memberRef) { // TODO restrict to struct/class fields // TODO handle global variables with explicit namespaces... if (!(memberRef.getParentElement() instanceof FunctionCall)) { if (memberRef.getName() != null) { switch (memberRef.getMemberRefStyle()) { case Colons: memberRef.setMemberRefStyle(MemberRefStyle.Dot); break; case Arrow: case Dot: Expression rep = methodCall(memberRef.getTarget(), memberRef.getName().toString()); if (memberRef.getMemberRefStyle() == MemberRefStyle.Arrow) rep = methodCall(rep, "get"); memberRef.replaceBy(rep); rep.accept(this); return; } } } super.visitMemberRef(memberRef); } @Override public void visitVariablesDeclaration(VariablesDeclaration v) { super.visitVariablesDeclaration(v); if (v.getDeclarators().size() == 1) { Declarator decl = v.getDeclarators().get(0); //DirectDeclarator decl = (DirectDeclarator); TypeRef vt = v.getValueType(); MutableByDeclarator mt = decl instanceof DirectDeclarator ? vt : decl.mutateType(vt); if (mt instanceof TypeRef) { TypeRef mutatedType = (TypeRef)mt; if (decl.getDefaultValue() == null) { TypeRef actualType = mutatedType; boolean referenced = varDeclTypeRefsTransformedToPointers.contains(v) && (mutatedType instanceof Pointer); if (referenced) { actualType = ((Pointer)mutatedType).getTarget(); } if (result.symbols.isClassType(actualType)) { decl.setDefaultValue(referenced ? staticPtrMethod("allocate", result.typeConverter.typeLiteral(actualType)) : new Expression.New(actualType.clone())); Expression vr = varRef(new SimpleIdentifier(decl.resolveName())); Statement deleteStat = stat(methodCall(expr(typeRef(BridJ.class)), "delete", referenced ? methodCall(vr, "get") : vr)); deleteStat.setCommentAfter("// object would end up being deleted by the GC later, but in C++ it would be deleted here."); Statement.Block parentBlock = (Statement.Block)v.getParentElement(); List<Statement> stats = new ArrayList<Statement>(parentBlock.getStatements()); for (int i = stats.size(); i-- != 0;) { Statement stat = stats.get(i); if (!(stat instanceof Statement.Return) && !deleteStatements.contains(stat)) { stats.add(i + 1, deleteStat); deleteStatements.add(deleteStat); break; } } parentBlock.setStatements(stats); } }// else { TypeConversion.NL4JConversion conv = result.typeConverter.convertTypeToNL4J( mutatedType, null,//callerLibraryName, null,//thisField("io"), null,//varRef(name), -1,//fieldIndex, -1//bits ); v.setValueType(conv.typeRef); if (conv.arrayLengths != null && (mutatedType instanceof TargettedTypeRef) && decl.getDefaultValue() == null) v.setDeclarators(Arrays.asList((Declarator)new DirectDeclarator(decl.resolveName(), newAllocateArray(((TargettedTypeRef)mutatedType).getTarget(), conv.arrayLengths)))); //} } } } Set<Element> deleteStatements = new HashSet<Element>(); @Override public void visitAssignmentOp(AssignmentOp assignment) { BinaryOperator binOp = assignment.getOperator().getCorrespondingBinaryOp(); Expression value = assignment.getValue(); value.setParenthesisIfNeeded(); if (assignment.getTarget() instanceof UnaryOp) { UnaryOp uop = (UnaryOp)assignment.getTarget(); if (uop.getOperator() == UnaryOperator.Dereference) { visit(uop.getOperand()); visit(assignment.getValue()); Expression target = uop.getOperand(); if (binOp != null) { value = expr(methodCall(target.clone(), "get"), binOp, value); } assignment.replaceBy(methodCall(target, "set", value)); return; } } if (assignment.getTarget() instanceof ArrayAccess) { ArrayAccess aa = (ArrayAccess)assignment.getTarget(); visit(aa.getTarget()); visit(aa.getIndex()); visit(assignment.getValue()); Expression target = aa.getTarget(); Expression index = aa.getIndex(); if (binOp != null) { value = expr(methodCall(target.clone(), "get", index.clone()), binOp, value); } assignment.replaceBy(methodCall(target, "set", index, value)); return; } if (assignment.getTarget() instanceof MemberRef) { MemberRef mr = (MemberRef)assignment.getTarget(); boolean isArrow = mr.getMemberRefStyle() == MemberRefStyle.Arrow; if (isArrow || mr.getMemberRefStyle() == MemberRefStyle.Dot) { Expression target = mr.getTarget(); String name = mr.getName().toString(); if (binOp != null) { value = expr(methodCall(target.clone(), name), binOp, value); } if (isArrow) target = methodCall(target, "get"); assignment.replaceBy(methodCall(target, name, value)); return; } } super.visitAssignmentOp(assignment); } @Override public void visitNew(New new1) { super.visitNew(new1); if (new1.getConstruction() == null) new1.replaceBy(staticPtrMethod("allocate" + primCapName(new1.getType()))); } public void notSup(Element x, String msg) throws UnsupportedConversionException { throw new UnsupportedConversionException(x, msg); } /* @Override public void visitExpressionStatement(ExpressionStatement expressionStatement) { super.visitExpressionStatement(expressionStatement); if (expressionStatement.getExpression() instanceof UnaryOp) { UnaryOp uop = (UnaryOp)expressionStatement.getExpression(); Expression target = uop.getOperand(); switch (uop.getOperator()) { case PostIncr: case PreIncr: expressionStatement.replaceBy(expr(target)); } } }*/ Expression newAllocateArray(TypeRef tr, Collection<Expression> sizes) { return staticPtrMethod( "allocate" + primCapName(tr) + "s", sizes.toArray(new Expression[sizes.size()]) ); } @Override public void visitNewArray(NewArray newArray) { super.visitNewArray(newArray); if (newArray.getType() instanceof Primitive) { if (newArray.getDimensions().size() > 3) notSup(newArray, "TODO only dimensions 1 to 3 are supported for primitive array creations !"); newArray.replaceBy(newAllocateArray(newArray.getType(), newArray.getDimensions())); } else { if (newArray.getDimensions().size() != 1) notSup(newArray, "TODO only dimension 1 is supported for reference array creations !"); newArray.replaceBy( staticPtrMethod( "allocateArray", result.typeConverter.typeLiteral(newArray.getType()), newArray.getDimensions().get(0) ) ); } } @Override public void visitPointer(Pointer pointer) { super.visitPointer(pointer); } /* @Override protected void visitTargettedTypeRef(TargettedTypeRef targettedTypeRef) { super.visitTargettedTypeRef(targettedTypeRef); if (targettedTypeRef.getTarget() != null) targettedTypeRef.replaceBy(pointerToTypeRef(targettedTypeRef.getTarget().clone())); }*/ }); return new Pair<Element, List<Declaration>>(element, extraDeclarationsOut); } TypeRef getWrapperType(TypeRef tr) { JavaPrim prim = result.typeConverter.getPrimitive(tr, null); if (prim != null) return typeRef(prim.wrapperType); return tr; } TypeRef pointerToTypeRef(TypeRef targetType) { Identifier id = ident(ptrClass()); id.resolveLastSimpleIdentifier().addTemplateArgument(expr(targetType)); return typeRef(id); } Class ptrClass() { return result.config.runtime.pointerClass; } }
diff --git a/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/external/cabio/CaBioFacadeImplTestIntegration.java b/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/external/cabio/CaBioFacadeImplTestIntegration.java index bddf901f4..7d5bcd848 100644 --- a/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/external/cabio/CaBioFacadeImplTestIntegration.java +++ b/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/external/cabio/CaBioFacadeImplTestIntegration.java @@ -1,155 +1,156 @@ /** * The software subject to this notice and license includes both human readable * source code form and machine readable, binary, object code form. The caIntegrator2 * Software was developed in conjunction with the National Cancer Institute * (NCI) by NCI employees, 5AM Solutions, Inc. (5AM), ScenPro, Inc. (ScenPro) * and Science Applications International Corporation (SAIC). To the extent * government employees are authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * * This caIntegrator2 Software License (the License) is between NCI and You. You (or * Your) shall mean a person or an entity, and all other entities that control, * are controlled by, or are under common control with the entity. Control for * purposes of this definition means (i) the direct or indirect power to cause * the direction or management of such entity, whether by contract or otherwise, * or (ii) ownership of fifty percent (50%) or more of the outstanding shares, * or (iii) beneficial ownership of such entity. * * This License is granted provided that You agree to the conditions described * below. NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up, * no-charge, irrevocable, transferable and royalty-free right and license in * its rights in the caIntegrator2 Software to (i) use, install, access, operate, * execute, copy, modify, translate, market, publicly display, publicly perform, * and prepare derivative works of the caIntegrator2 Software; (ii) distribute and * have distributed to and by third parties the caIntegrator2 Software and any * modifications and derivative works thereof; and (iii) sublicense the * foregoing rights set out in (i) and (ii) to third parties, including the * right to license such rights to further third parties. For sake of clarity, * and not by way of limitation, NCI shall have no right of accounting or right * of payment from You or Your sub-licensees for the rights granted under this * License. This License is granted at no charge to You. * * Your redistributions of the source code for the Software must retain the * above copyright notice, this list of conditions and the disclaimer and * limitation of liability of Article 6, below. Your redistributions in object * code form must reproduce the above copyright notice, this list of conditions * and the disclaimer of Article 6 in the documentation and/or other materials * provided with the distribution, if any. * * Your end-user documentation included with the redistribution, if any, must * include the following acknowledgment: This product includes software * developed by 5AM, ScenPro, SAIC and the National Cancer Institute. If You do * not include such end-user documentation, You shall include this acknowledgment * in the Software itself, wherever such third-party acknowledgments normally * appear. * * You may not use the names "The National Cancer Institute", "NCI", "ScenPro", * "SAIC" or "5AM" to endorse or promote products derived from this Software. * This License does not authorize You to use any trademarks, service marks, * trade names, logos or product names of either NCI, ScenPro, SAID or 5AM, * except as required to comply with the terms of this License. * * For sake of clarity, and not by way of limitation, You may incorporate this * Software into Your proprietary programs and into any third party proprietary * programs. However, if You incorporate the Software into third party * proprietary programs, You agree that You are solely responsible for obtaining * any permission from such third parties required to incorporate the Software * into such third party proprietary programs and for informing Your a * sub-licensees, including without limitation Your end-users, of their * obligation to secure any required permissions from such third parties before * incorporating the Software into such third party proprietary software * programs. In the event that You fail to obtain such permissions, You agree * to indemnify NCI for any claims against NCI by such third parties, except to * the extent prohibited by law, resulting from Your failure to obtain such * permissions. * * For sake of clarity, and not by way of limitation, You may add Your own * copyright statement to Your modifications and to the derivative works, and * You may provide additional or different license terms and conditions in Your * sublicenses of modifications of the Software, or any derivative works of the * Software as a whole, provided Your use, reproduction, and distribution of the * Work otherwise complies with the conditions stated in this License. * * THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, * (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO * EVENT SHALL THE NATIONAL CANCER INSTITUTE, 5AM SOLUTIONS, INC., SCENPRO, INC., * SCIENCE APPLICATIONS INTERNATIONAL CORPORATION OR THEIR * AFFILIATES 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 gov.nih.nci.caintegrator2.external.cabio; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import gov.nih.nci.caintegrator2.domain.annotation.CommonDataElement; import gov.nih.nci.caintegrator2.domain.annotation.ValueDomain; import gov.nih.nci.caintegrator2.external.ConnectionException; import java.util.Arrays; import java.util.List; import org.apache.log4j.Logger; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @SuppressWarnings("unused") public class CaBioFacadeImplTestIntegration { private CaBioFacadeImpl caBioFacade; private static final Logger LOGGER = Logger.getLogger(CaBioFacadeImplTestIntegration.class); @Before public void setUp() { ApplicationContext context = new ClassPathXmlApplicationContext( "cabio-test-config.xml", CaBioFacadeImplTestIntegration.class); caBioFacade = (CaBioFacadeImpl) context.getBean("caBioFacade"); } @Test public void testRetrieveGeneSymbolsFromKeywords() throws ConnectionException { CaBioGeneSearchParameters params = new CaBioGeneSearchParameters(); params.setKeywords("heart"); params.setTaxon("human"); + params.setFilterGenesOnStudy(false); List<CaBioDisplayableGene> genes = caBioFacade.retrieveGenes(params); assertTrue(checkSymbolExists("CDH13", genes)); assertTrue(checkSymbolExists("FABP3", genes)); assertTrue(checkSymbolExists("HAND1", genes)); assertTrue(checkSymbolExists("HAND2", genes)); assertTrue(checkSymbolExists("LBH", genes)); assertTrue(checkSymbolExists("LOC128102", genes)); params.setTaxon("mouse"); genes = caBioFacade.retrieveGenes(params); assertFalse(checkSymbolExists("CDH13", genes)); assertTrue(checkSymbolExists("FABP3", genes)); params.setTaxon(CaBioGeneSearchParameters.ALL_TAXONS); genes = caBioFacade.retrieveGenes(params); assertTrue(!genes.isEmpty()); } @Test public void testRetrieveAllTaxons() throws ConnectionException { List<String> taxons = caBioFacade.retrieveAllTaxons(); assertFalse(taxons.isEmpty()); } private boolean checkSymbolExists(String symbol, List<CaBioDisplayableGene> genes) { for (CaBioDisplayableGene gene : genes) { if (symbol.equals(gene.getSymbol())) { return true; } } return false; } }
true
true
public void testRetrieveGeneSymbolsFromKeywords() throws ConnectionException { CaBioGeneSearchParameters params = new CaBioGeneSearchParameters(); params.setKeywords("heart"); params.setTaxon("human"); List<CaBioDisplayableGene> genes = caBioFacade.retrieveGenes(params); assertTrue(checkSymbolExists("CDH13", genes)); assertTrue(checkSymbolExists("FABP3", genes)); assertTrue(checkSymbolExists("HAND1", genes)); assertTrue(checkSymbolExists("HAND2", genes)); assertTrue(checkSymbolExists("LBH", genes)); assertTrue(checkSymbolExists("LOC128102", genes)); params.setTaxon("mouse"); genes = caBioFacade.retrieveGenes(params); assertFalse(checkSymbolExists("CDH13", genes)); assertTrue(checkSymbolExists("FABP3", genes)); params.setTaxon(CaBioGeneSearchParameters.ALL_TAXONS); genes = caBioFacade.retrieveGenes(params); assertTrue(!genes.isEmpty()); }
public void testRetrieveGeneSymbolsFromKeywords() throws ConnectionException { CaBioGeneSearchParameters params = new CaBioGeneSearchParameters(); params.setKeywords("heart"); params.setTaxon("human"); params.setFilterGenesOnStudy(false); List<CaBioDisplayableGene> genes = caBioFacade.retrieveGenes(params); assertTrue(checkSymbolExists("CDH13", genes)); assertTrue(checkSymbolExists("FABP3", genes)); assertTrue(checkSymbolExists("HAND1", genes)); assertTrue(checkSymbolExists("HAND2", genes)); assertTrue(checkSymbolExists("LBH", genes)); assertTrue(checkSymbolExists("LOC128102", genes)); params.setTaxon("mouse"); genes = caBioFacade.retrieveGenes(params); assertFalse(checkSymbolExists("CDH13", genes)); assertTrue(checkSymbolExists("FABP3", genes)); params.setTaxon(CaBioGeneSearchParameters.ALL_TAXONS); genes = caBioFacade.retrieveGenes(params); assertTrue(!genes.isEmpty()); }
diff --git a/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java b/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java index d0dde504..d70ebacf 100644 --- a/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java +++ b/splat/src/main/uk/ac/starlink/splat/vo/SSAMetadataFrame.java @@ -1,790 +1,790 @@ /* * Copyright (C) 2001-2005 Central Laboratory of the Research Councils * Copyright (C) 2008 Science and Technology Facilities Council * * History: * 23-FEB-2012 (Margarida Castro Neves [email protected]) * Original version. */ package uk.ac.starlink.splat.vo; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.DefaultCellEditor; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.JTable; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import uk.ac.starlink.splat.iface.HelpFrame; import uk.ac.starlink.splat.iface.images.ImageHolder; import uk.ac.starlink.splat.util.SplatCommunicator; import uk.ac.starlink.splat.util.Transmitter; import uk.ac.starlink.splat.util.Utilities; import uk.ac.starlink.util.gui.BasicFileChooser; import uk.ac.starlink.util.gui.BasicFileFilter; import uk.ac.starlink.util.gui.ErrorDialog; import uk.ac.starlink.splat.vo.SSAQueryBrowser.LocalAction; import uk.ac.starlink.splat.vo.SSAQueryBrowser.MetadataInputParameter; import uk.ac.starlink.splat.vo.SSAQueryBrowser.ResolverAction; /** * Class SSAMetadataServerFrame * * This class supports displaying metadata parameters that can be used for a SSA query, * selecting parameters and modifying their values. * * @author Margarida Castro Neves */ public class SSAMetadataFrame extends JFrame implements ActionListener { /** * Panel for the central region. */ protected JPanel centrePanel = new JPanel(); /** * File chooser for storing and restoring server lists. */ protected BasicFileChooser fileChooser = null; // used to trigger a new server metadata query by SSAQueryBrowser private PropertyChangeSupport queryMetadata; private static JTable metadataTable; private static MetadataTableModel metadataTableModel; /** The list of all input parameters read from the servers as a hash map */ private HashMap<String, MetadataInputParameter> metaParam=null; // the metadata table private static final int NRCOLS = 5; // the number of columns in the table // the table indexes private static final int SELECTED_INDEX = 0; private static final int NR_SERVERS_INDEX = 1; private static final int NAME_INDEX = 2; private static final int VALUE_INDEX = 3; private static final int DESCRIPTION_INDEX = 4; // total number of servers that returned parameters int nrServers; // the table headers String[] headers; String[] headersToolTips; // cell renderer for the parameter name column ParamCellRenderer paramRenderer=null; /** * Constructor: */ //public SSAMetadataFrame( HashMap<String, MetadataInputParameter> metaParam , int nrServers) public SSAMetadataFrame( HashMap<String, MetadataInputParameter> metaParam ) { this.metaParam = metaParam; //this.nrServers = nrServers; initUI(); initMetadataTable(); initMenus(); initFrame(); queryMetadata = new PropertyChangeSupport(this); } //initFrame /** * Constructor: creates an empty table */ public SSAMetadataFrame( ) { metaParam = null; // nrServers = 0; initUI(); initMetadataTable(); initMenus(); initFrame(); queryMetadata = new PropertyChangeSupport(this); } //initFrame /** * Initialize the metadata table */ public void initMetadataTable() { // the table headers headers = new String[NRCOLS]; headers[SELECTED_INDEX] = "Use"; headers[NR_SERVERS_INDEX] = "Nr servers"; headers[NAME_INDEX] = "Name"; headers[VALUE_INDEX] = "Value"; headers[DESCRIPTION_INDEX] = "Description"; // the tooltip Texts for the headers headersToolTips = new String[NRCOLS]; headersToolTips[SELECTED_INDEX] = "Select for Query"; headersToolTips[NR_SERVERS_INDEX] = "Nr servers supporting this parameter"; headersToolTips[NAME_INDEX] = "Parameter name"; headersToolTips[VALUE_INDEX] = "Parameter value"; headersToolTips[DESCRIPTION_INDEX] = "Description"; // Table of metadata parameters goes into a scrollpane in the center of // window (along with a set of buttons, see initUI). // set the model and change the appearance // the table data if (metaParam != null) { String[][] paramList = getParamList(); metadataTableModel = new MetadataTableModel(paramList, headers); } else metadataTableModel = new MetadataTableModel(headers); metadataTable.setModel( metadataTableModel ); metadataTable.setShowGrid(true); metadataTable.setGridColor(Color.lightGray); metadataTable.getTableHeader().setReorderingAllowed(false); paramRenderer = new ParamCellRenderer(); // set cell renderer for description column adjustColumns(); } /** * updateMetadata( HashMap<String, MetadataInputParameter> metaParam ) * updates the metadata table information after a "refresh" * * @param metaParam */ public void updateMetadata(HashMap<String, MetadataInputParameter> metaParam ) { metadataTableModel = new MetadataTableModel(headers); metadataTable.setModel(metadataTableModel ); adjustColumns(); } /** * Transform the metadata Hash into a two-dimensional String array (an array of rows). * The rows will be sorted by number of servers supporting the parameter * * @return the metadata array */ public String[][] getParamList() { // Iterate through metaParam, add the entries, populate the table Collection<MetadataInputParameter> mp = metaParam.values(); String[][] metadataList = new String[mp.size()][NRCOLS]; Iterator<MetadataInputParameter> it = mp.iterator(); int row=0; while (it.hasNext()) { MetadataInputParameter mip = it.next(); metadataList[row][NR_SERVERS_INDEX] = Integer.toString(mip.getCounter());//+"/"+Integer.toString(nrServers); // nr supporting servers metadataList[row][NAME_INDEX] = mip.getName().replace("INPUT:", ""); // name metadataList[row][VALUE_INDEX] = mip.getValue(); // value (default value or "") String unit = mip.getUnit(); String desc = mip.getDescription(); desc = desc.replaceAll("\n+", "<br>"); desc = desc.replaceAll("\t+", " "); desc = desc.replaceAll("\\s+", " "); if (unit != null && unit.length() >0) { desc = desc + " ("+unit+")"; // description (unit) } metadataList[row][DESCRIPTION_INDEX] = desc; // description row++; } // while Arrays.sort(metadataList, new SupportedComparator()); return metadataList; } /** * comparator to sort the parameter list by the nr of servers that support a parameter */ class SupportedComparator implements Comparator<String[]> { public int compare(String[] object1, String[] object2) { // compare the frequency counter return ( Integer.parseInt(object2[NR_SERVERS_INDEX]) - Integer.parseInt(object1[NR_SERVERS_INDEX]) ); } } /** * adjust column sizes, renderers and editors */ private void adjustColumns() { JCheckBox cb = new JCheckBox(); JTextField tf = new JTextField(); metadataTable.getColumnModel().getColumn(SELECTED_INDEX).setCellEditor(new DefaultCellEditor(cb)); metadataTable.getColumnModel().getColumn(SELECTED_INDEX).setMaxWidth(30); metadataTable.getColumnModel().getColumn(SELECTED_INDEX).setMinWidth(30); metadataTable.getColumnModel().getColumn(NR_SERVERS_INDEX).setMaxWidth(60); metadataTable.getColumnModel().getColumn(NAME_INDEX).setMinWidth(150); metadataTable.getColumnModel().getColumn(VALUE_INDEX).setMinWidth(150); metadataTable.getColumnModel().getColumn(VALUE_INDEX).setCellEditor(new DefaultCellEditor(tf)); metadataTable.getColumnModel().getColumn(NAME_INDEX).setCellRenderer(paramRenderer); metadataTable.getColumnModel().getColumn (DESCRIPTION_INDEX).setMaxWidth(0); // Remove the description column. Its contents will not be removed. They'll be displayed as tooltip text in the NAME_INDEX column. metadataTable.removeColumn(metadataTable.getColumnModel().getColumn (DESCRIPTION_INDEX)); } /** * Retrieve parameter names and values from table and returns a query substring * Only the parameters on selected rows, and having non-empty values will be added to the table */ public String getParamsQueryString() { String query=""; // iterate through all rows for (int i=0; i< metadataTable.getRowCount(); i++) { if (rowChecked( i )) { String val = getTableData(i,VALUE_INDEX).toString().trim(); if (val != null && val.length() > 0) { String name = getTableData(i,NAME_INDEX).toString().trim(); query += "&"+name+"="+val; } } } return query; } /** * retrieves table content at cell position row, col * * @param row * @param col * @return */ private Object getTableData(int row, int col ) { return metadataTable.getModel().getValueAt(row, col); } /** * retrieves the state of the checkbox row (parameter selected) * * @param row * @return - true if it is checked, false if unchecked */ private boolean rowChecked(int row) { Boolean val = (Boolean) metadataTable.getModel().getValueAt(row, SELECTED_INDEX); if (Boolean.TRUE.equals(val)) return true; else return false; } /** * changes content to newValue at cell position row, col * * @param newValue * @param row * @param col */ private void setTableData(String newValue, int row, int col ) { metadataTable.getModel().setValueAt(newValue, row, col); } /** * Initialise the main part of the user interface. */ protected void initUI() { getContentPane().setLayout( new BorderLayout() ); metadataTable = new JTable( ); JScrollPane scroller = new JScrollPane( metadataTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); // metadataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); centrePanel.setLayout( new BorderLayout() ); centrePanel.add( scroller, BorderLayout.CENTER ); getContentPane().add( centrePanel, BorderLayout.CENTER ); centrePanel.setBorder( BorderFactory.createTitledBorder( "Optional Parameters" ) ); } /** * Initialise frame properties (disposal, title, menus etc.). */ protected void initFrame() { setTitle( Utilities.getTitle( "Select SSAP Parameters" )); setDefaultCloseOperation( JFrame.HIDE_ON_CLOSE ); setSize( new Dimension( 425, 500 ) ); setVisible( true ); } /** * Initialise the menu bar, action bar and related actions. */ protected void initMenus() { // get the icons // Get icons. ImageIcon closeImage = new ImageIcon( ImageHolder.class.getResource( "close.gif" ) ); ImageIcon saveImage = new ImageIcon( ImageHolder.class.getResource( "savefile.gif" ) ); ImageIcon readImage = new ImageIcon( ImageHolder.class.getResource( "openfile.gif" ) ); // ImageIcon helpImage = new ImageIcon( ImageHolder.class.getResource( "help.gif" ) ); ImageIcon updateImage = new ImageIcon( ImageHolder.class.getResource("ssapservers.gif") ); ImageIcon resetImage = new ImageIcon( ImageHolder.class.getResource("reset.gif") ); // The Menu bar // Add the menuBar. JMenuBar menuBar = new JMenuBar(); setJMenuBar( menuBar ); // Create the File menu. JMenu fileMenu = new JMenu( "File" ); fileMenu.setMnemonic( KeyEvent.VK_F ); menuBar.add( fileMenu ); JMenuItem saveFile = new JMenuItem("(S)ave Param List to File", saveImage); saveFile.setMnemonic( KeyEvent.VK_S ); saveFile.addActionListener(this); saveFile.setActionCommand( "save" ); fileMenu.add(saveFile); JMenuItem readFile = new JMenuItem("Read Param List from (F)ile", readImage); fileMenu.add(readFile); readFile.setMnemonic( KeyEvent.VK_F ); readFile.addActionListener(this); readFile.setActionCommand( "restore" ); JMenuItem loadFile = new JMenuItem("(U)pdate Params from servers", updateImage); fileMenu.add(loadFile); loadFile.setMnemonic( KeyEvent.VK_U ); loadFile.addActionListener(this); loadFile.setActionCommand( "load" ); JMenuItem resetFile = new JMenuItem("(R)eset all values", resetImage); fileMenu.add(loadFile); resetFile.setMnemonic( KeyEvent.VK_R ); resetFile.addActionListener(this); resetFile.setActionCommand( "reset" ); // Create the Help menu. HelpFrame.createButtonHelpMenu( "ssa-window", "Help on window", menuBar, null ); // The Buttons bar // the action buttons JPanel buttonsPanel = new JPanel( new GridLayout(1,5) ); // Add action to save the parameter list into a file JButton saveButton = new JButton( "Save" , saveImage ); saveButton.setActionCommand( "save" ); saveButton.setToolTipText( "Save parameter list to a file" ); saveButton.addActionListener( this ); buttonsPanel.add( saveButton ); // Add action to save the parameter list into a file JButton restoreButton = new JButton( "Read" , readImage); restoreButton.setActionCommand( "restore" ); restoreButton.setToolTipText( "Restore parameter list from a file" ); restoreButton.addActionListener( this ); buttonsPanel.add( restoreButton ); // Add action to query the servers for parameters JButton queryButton = new JButton( "Update" , updateImage); - queryButton.setActionCommand( "load" ); + queryButton.setActionCommand( "refresh" ); queryButton.setToolTipText( "Query the servers for a current list of parameters" ); queryButton.addActionListener( this ); buttonsPanel.add( queryButton ); // Add action to do reset the form JButton resetButton = new JButton( "Reset", resetImage ); resetButton.setActionCommand( "reset" ); resetButton.setToolTipText( "Clear all fields" ); resetButton.addActionListener( this ); buttonsPanel.add( resetButton ); // Add an action to close the window. JButton closeButton = new JButton( "Close", closeImage ); //centrePanel.add( closeButton ); closeButton.addActionListener( this ); closeButton.setActionCommand( "close" ); closeButton.setToolTipText( "Close window" ); buttonsPanel.add( closeButton); centrePanel.add( buttonsPanel, BorderLayout.SOUTH); } // initMenus /** * Register new Property Change Listener */ public void addPropertyChangeListener(PropertyChangeListener l) { queryMetadata.addPropertyChangeListener(l); } /** * action performed * process the actions when a button is clicked */ public void actionPerformed(ActionEvent e) { Object command = e.getActionCommand(); if ( command.equals( "save" ) ) // save table values to a file { saveMetadataToFile(); } if ( command.equals( "load" ) ) // read saved table values from a file { readMetadataFromFile(); } if ( command.equals( "refresh" ) ) // add new server to list { queryMetadata.firePropertyChange("refresh", false, true); } if ( command.equals( "reset" ) ) // reset text fields { resetFields(); } if ( command.equals( "close" ) ) // close window { closeWindow(); } } // actionPerformed /** * Close (hide) the window. */ private void closeWindow() { this.setVisible( false ); } /** * Open (show) the window. */ public void openWindow() { this.setVisible( true ); } /** * Reset all fields */ private void resetFields() { for (int i=0; i< metadataTable.getRowCount(); i++) { String val = getTableData(i,VALUE_INDEX).toString().trim(); if (val != null && val.length() > 0) { setTableData("", i,VALUE_INDEX); } } } //resetFields /** * Initialise the file chooser to have the necessary filters. */ protected void initFileChooser() { if ( fileChooser == null ) { fileChooser = new BasicFileChooser( false ); fileChooser.setMultiSelectionEnabled( false ); // Add a filter for XML files. BasicFileFilter csvFileFilter = new BasicFileFilter( "csv", "CSV files" ); fileChooser.addChoosableFileFilter( csvFileFilter ); // But allow all files as well. fileChooser.addChoosableFileFilter ( fileChooser.getAcceptAllFileFilter() ); } } //initFileChooser /** * Restore metadata that has been previously written to a * CSV file. The file name is obtained interactively. */ public void readMetadataFromFile() { initFileChooser(); int result = fileChooser.showOpenDialog( this ); if ( result == JFileChooser.APPROVE_OPTION ) { File file = fileChooser.getSelectedFile(); try { readTable( file ); } catch (Exception e) { ErrorDialog.showError( this, e ); } } } // readMetadataFromFile /** * Interactively gets a file name and save current metadata table to it in CSV format * a VOTable. */ public void saveMetadataToFile() { if ( metadataTable == null || metadataTable.getRowCount() == 0 ) { JOptionPane.showMessageDialog( this, "There are no parameters to save", "No parameters", JOptionPane.ERROR_MESSAGE ); return; } initFileChooser(); int result = fileChooser.showSaveDialog( this ); if ( result == JFileChooser.APPROVE_OPTION ) { File file = fileChooser.getSelectedFile(); try { saveTable( file ); } catch (Exception e) { ErrorDialog.showError( this, e ); } } } // readMetadataFromFile /** * saveTable(file) * saves the metadata table to a file in csv format * * @param paramFile - file where to save the table * @throws IOException */ private void saveTable(File paramFile) throws IOException { BufferedWriter tableWriter = new BufferedWriter(new FileWriter(paramFile)); for ( int row=0; row< metadataTable.getRowCount(); row++) { tableWriter.append(metadataTable.getValueAt(row, NR_SERVERS_INDEX).toString()); tableWriter.append(';'); tableWriter.append(metadataTable.getValueAt(row, NAME_INDEX).toString()); tableWriter.append(';'); tableWriter.append(metadataTable.getValueAt(row, VALUE_INDEX).toString()); tableWriter.append(';'); tableWriter.append(metadataTable.getValueAt(row, DESCRIPTION_INDEX).toString()); tableWriter.append('\n'); } tableWriter.flush(); tableWriter.close(); } //saveTable() /** * readTable( File paramFile) * reads the metadata table previously saved with saveTable() from a file in csv format * * @param paramFile - the csv file to be read * @throws IOException * @throws FileNotFoundException */ private void readTable(File paramFile) throws IOException, FileNotFoundException { MetadataTableModel newmodel = new MetadataTableModel(headers); BufferedReader CSVFile = new BufferedReader(new FileReader(paramFile)); String tableRow = CSVFile.readLine(); while (tableRow != null) { String [] paramRow = new String [NRCOLS]; paramRow = tableRow.split(";", NRCOLS); newmodel.addRow(paramRow); tableRow = CSVFile.readLine(); } // Close the file once all data has been read. CSVFile.close(); // set the new model metadataTable.setModel(newmodel); adjustColumns(); // adjust column sizes in the new model } //readTable() /** * Adds a new row to the table * @param mip the metadata parameter that will be added to the table */ public void addRow (MetadataInputParameter mip) { String [] paramRow = new String [NRCOLS]; paramRow[NR_SERVERS_INDEX] = Integer.toString(mip.getCounter());//+"/"+Integer.toString(nrServers); // nr supporting servers paramRow[NAME_INDEX] = mip.getName().replace("INPUT:", ""); // name paramRow[VALUE_INDEX] = mip.getValue(); // value (default value or "") String unit = mip.getUnit(); String desc = mip.getDescription(); if (desc != null) { // remove newline, tabs, and multiple spaces desc = desc.replaceAll("\n+", " "); desc = desc.replaceAll("\t+", " "); desc = desc.replaceAll("\\s+", " "); // insert linebreaks for multi-lined tooltip int linelength=100; int sum=0; String [] words = desc.split( " " ); desc=""; for (int i=0; i<words.length; i++ ) { sum+=words[i].length()+1; if (sum > linelength) { desc+="<br>"+words[i]+" "; sum=words[i].length(); } else { desc+=words[i]+" "; } } } if (unit != null && unit.length() >0) { desc = desc + " ("+unit+")"; // description (unit) } paramRow[DESCRIPTION_INDEX] = desc; // description MetadataTableModel mtm = (MetadataTableModel) metadataTable.getModel(); mtm.addRow( paramRow ); } //addRow /** * Set number of servers to the respective column in the table * @param counter the nr of servers supporting the parameter * @param name the name of the parameter */ public void setNrServers(int counter, String name) { // boolean found=false; int row=0; String paramName = name.replace("INPUT:", ""); MetadataTableModel mtm = (MetadataTableModel) metadataTable.getModel(); while (row<mtm.getRowCount() ) { if ( mtm.getValueAt(row, NAME_INDEX).toString().equalsIgnoreCase(paramName)) { mtm.setValueAt(counter, row, NR_SERVERS_INDEX); return; } row++; } }//setnrServers /** * the cell renderer for the parameter name column ( show description as toolTipText ) * */ class ParamCellRenderer extends JLabel implements TableCellRenderer { public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setText(value.toString()); setToolTipText("<html><p>"+table.getModel().getValueAt(row, DESCRIPTION_INDEX).toString()+"</p></html>"); if (isSelected) setBackground(table.getSelectionBackground()); return this; } } //ParamCellRenderer /** * MetadataTableModel * defines the model of the metadata table */ class MetadataTableModel extends DefaultTableModel { // creates a metadataTableModel with headers and data public MetadataTableModel( String [][] data, String [] headers ) { super(data, headers); } // creates a metadataTableModel with headers and no data rows public MetadataTableModel( String [] headers ) { super(headers, 0); } @Override public boolean isCellEditable(int row, int column) { return (column == VALUE_INDEX || column == SELECTED_INDEX ); // the Values column is editable } @Override public Class getColumnClass(int column) { if (column == SELECTED_INDEX ) return Boolean.class; return String.class; } } //MetadataTableModel } //SSAMetadataFrame
true
true
protected void initMenus() { // get the icons // Get icons. ImageIcon closeImage = new ImageIcon( ImageHolder.class.getResource( "close.gif" ) ); ImageIcon saveImage = new ImageIcon( ImageHolder.class.getResource( "savefile.gif" ) ); ImageIcon readImage = new ImageIcon( ImageHolder.class.getResource( "openfile.gif" ) ); // ImageIcon helpImage = new ImageIcon( ImageHolder.class.getResource( "help.gif" ) ); ImageIcon updateImage = new ImageIcon( ImageHolder.class.getResource("ssapservers.gif") ); ImageIcon resetImage = new ImageIcon( ImageHolder.class.getResource("reset.gif") ); // The Menu bar // Add the menuBar. JMenuBar menuBar = new JMenuBar(); setJMenuBar( menuBar ); // Create the File menu. JMenu fileMenu = new JMenu( "File" ); fileMenu.setMnemonic( KeyEvent.VK_F ); menuBar.add( fileMenu ); JMenuItem saveFile = new JMenuItem("(S)ave Param List to File", saveImage); saveFile.setMnemonic( KeyEvent.VK_S ); saveFile.addActionListener(this); saveFile.setActionCommand( "save" ); fileMenu.add(saveFile); JMenuItem readFile = new JMenuItem("Read Param List from (F)ile", readImage); fileMenu.add(readFile); readFile.setMnemonic( KeyEvent.VK_F ); readFile.addActionListener(this); readFile.setActionCommand( "restore" ); JMenuItem loadFile = new JMenuItem("(U)pdate Params from servers", updateImage); fileMenu.add(loadFile); loadFile.setMnemonic( KeyEvent.VK_U ); loadFile.addActionListener(this); loadFile.setActionCommand( "load" ); JMenuItem resetFile = new JMenuItem("(R)eset all values", resetImage); fileMenu.add(loadFile); resetFile.setMnemonic( KeyEvent.VK_R ); resetFile.addActionListener(this); resetFile.setActionCommand( "reset" ); // Create the Help menu. HelpFrame.createButtonHelpMenu( "ssa-window", "Help on window", menuBar, null ); // The Buttons bar // the action buttons JPanel buttonsPanel = new JPanel( new GridLayout(1,5) ); // Add action to save the parameter list into a file JButton saveButton = new JButton( "Save" , saveImage ); saveButton.setActionCommand( "save" ); saveButton.setToolTipText( "Save parameter list to a file" ); saveButton.addActionListener( this ); buttonsPanel.add( saveButton ); // Add action to save the parameter list into a file JButton restoreButton = new JButton( "Read" , readImage); restoreButton.setActionCommand( "restore" ); restoreButton.setToolTipText( "Restore parameter list from a file" ); restoreButton.addActionListener( this ); buttonsPanel.add( restoreButton ); // Add action to query the servers for parameters JButton queryButton = new JButton( "Update" , updateImage); queryButton.setActionCommand( "load" ); queryButton.setToolTipText( "Query the servers for a current list of parameters" ); queryButton.addActionListener( this ); buttonsPanel.add( queryButton ); // Add action to do reset the form JButton resetButton = new JButton( "Reset", resetImage ); resetButton.setActionCommand( "reset" ); resetButton.setToolTipText( "Clear all fields" ); resetButton.addActionListener( this ); buttonsPanel.add( resetButton ); // Add an action to close the window. JButton closeButton = new JButton( "Close", closeImage ); //centrePanel.add( closeButton ); closeButton.addActionListener( this ); closeButton.setActionCommand( "close" ); closeButton.setToolTipText( "Close window" ); buttonsPanel.add( closeButton); centrePanel.add( buttonsPanel, BorderLayout.SOUTH); } // initMenus
protected void initMenus() { // get the icons // Get icons. ImageIcon closeImage = new ImageIcon( ImageHolder.class.getResource( "close.gif" ) ); ImageIcon saveImage = new ImageIcon( ImageHolder.class.getResource( "savefile.gif" ) ); ImageIcon readImage = new ImageIcon( ImageHolder.class.getResource( "openfile.gif" ) ); // ImageIcon helpImage = new ImageIcon( ImageHolder.class.getResource( "help.gif" ) ); ImageIcon updateImage = new ImageIcon( ImageHolder.class.getResource("ssapservers.gif") ); ImageIcon resetImage = new ImageIcon( ImageHolder.class.getResource("reset.gif") ); // The Menu bar // Add the menuBar. JMenuBar menuBar = new JMenuBar(); setJMenuBar( menuBar ); // Create the File menu. JMenu fileMenu = new JMenu( "File" ); fileMenu.setMnemonic( KeyEvent.VK_F ); menuBar.add( fileMenu ); JMenuItem saveFile = new JMenuItem("(S)ave Param List to File", saveImage); saveFile.setMnemonic( KeyEvent.VK_S ); saveFile.addActionListener(this); saveFile.setActionCommand( "save" ); fileMenu.add(saveFile); JMenuItem readFile = new JMenuItem("Read Param List from (F)ile", readImage); fileMenu.add(readFile); readFile.setMnemonic( KeyEvent.VK_F ); readFile.addActionListener(this); readFile.setActionCommand( "restore" ); JMenuItem loadFile = new JMenuItem("(U)pdate Params from servers", updateImage); fileMenu.add(loadFile); loadFile.setMnemonic( KeyEvent.VK_U ); loadFile.addActionListener(this); loadFile.setActionCommand( "load" ); JMenuItem resetFile = new JMenuItem("(R)eset all values", resetImage); fileMenu.add(loadFile); resetFile.setMnemonic( KeyEvent.VK_R ); resetFile.addActionListener(this); resetFile.setActionCommand( "reset" ); // Create the Help menu. HelpFrame.createButtonHelpMenu( "ssa-window", "Help on window", menuBar, null ); // The Buttons bar // the action buttons JPanel buttonsPanel = new JPanel( new GridLayout(1,5) ); // Add action to save the parameter list into a file JButton saveButton = new JButton( "Save" , saveImage ); saveButton.setActionCommand( "save" ); saveButton.setToolTipText( "Save parameter list to a file" ); saveButton.addActionListener( this ); buttonsPanel.add( saveButton ); // Add action to save the parameter list into a file JButton restoreButton = new JButton( "Read" , readImage); restoreButton.setActionCommand( "restore" ); restoreButton.setToolTipText( "Restore parameter list from a file" ); restoreButton.addActionListener( this ); buttonsPanel.add( restoreButton ); // Add action to query the servers for parameters JButton queryButton = new JButton( "Update" , updateImage); queryButton.setActionCommand( "refresh" ); queryButton.setToolTipText( "Query the servers for a current list of parameters" ); queryButton.addActionListener( this ); buttonsPanel.add( queryButton ); // Add action to do reset the form JButton resetButton = new JButton( "Reset", resetImage ); resetButton.setActionCommand( "reset" ); resetButton.setToolTipText( "Clear all fields" ); resetButton.addActionListener( this ); buttonsPanel.add( resetButton ); // Add an action to close the window. JButton closeButton = new JButton( "Close", closeImage ); //centrePanel.add( closeButton ); closeButton.addActionListener( this ); closeButton.setActionCommand( "close" ); closeButton.setToolTipText( "Close window" ); buttonsPanel.add( closeButton); centrePanel.add( buttonsPanel, BorderLayout.SOUTH); } // initMenus
diff --git a/mod/jodd-wot/test/jodd/petite/WireTest.java b/mod/jodd-wot/test/jodd/petite/WireTest.java index 279a100d6..f36d76649 100644 --- a/mod/jodd-wot/test/jodd/petite/WireTest.java +++ b/mod/jodd-wot/test/jodd/petite/WireTest.java @@ -1,210 +1,210 @@ // Copyright (c) 2003-2011, Jodd Team (jodd.org). All Rights Reserved. package jodd.petite; import junit.framework.TestCase; import jodd.petite.config.AutomagicPetiteConfigurator; import jodd.petite.test.Boo; import jodd.petite.test.BooC; import jodd.petite.test.BooC2; import jodd.petite.test.Foo; import jodd.petite.test.Zoo; import jodd.petite.test.Goo; import jodd.petite.test.Loo; import jodd.petite.test.Ioo; import jodd.petite.test.impl.DefaultIoo; import jodd.petite.scope.ProtoScope; import java.util.List; public class WireTest extends TestCase { @Override protected void setUp() throws Exception { super.setUp(); Foo.instanceCounter = 0; } public void testContainer() { PetiteContainer pc = new PetiteContainer(); AutomagicPetiteConfigurator configurator = new AutomagicPetiteConfigurator(); - configurator.setIncludedEntries(new String[] {"jodd.petite.*"}); - configurator.setExcludedEntries(new String[] {"jodd.petite.data.*"}); + configurator.setIncludedEntries("jodd.petite.*"); + configurator.setExcludedEntries("jodd.petite.data.*", "jodd.petite.test3.*"); configurator.configure(pc); assertEquals(1, pc.getTotalBeans()); assertEquals(1, pc.getTotalScopes()); assertEquals(0, Foo.instanceCounter); Foo foo = (Foo) pc.getBean("foo"); assertNotNull(foo); assertEquals(1, foo.hello()); foo = (Foo) pc.getBean("foo"); assertEquals(1, foo.hello()); // register again the same class, but this time with proto scope pc.registerBean("foo2", Foo.class, ProtoScope.class); assertEquals(2, pc.getTotalBeans()); assertEquals(2, pc.getTotalScopes()); assertEquals(2, ((Foo) pc.getBean("foo2")).hello()); assertEquals(3, ((Foo) pc.getBean("foo2")).hello()); // register boo pc.registerBean(Boo.class); assertEquals(3, pc.getTotalBeans()); assertEquals(2, pc.getTotalScopes()); Boo boo; try { //noinspection UnusedAssignment boo = (Boo) pc.getBean("boo"); fail(); } catch (PetiteException pex) { // zoo class is missing } pc.registerBean(Zoo.class); assertEquals(4, pc.getTotalBeans()); assertEquals(2, pc.getTotalScopes()); boo = (Boo) pc.getBean("boo"); assertNotNull(boo); assertNotNull(boo.getFoo()); assertNotNull(boo.zoo); assertSame(boo.zoo.boo, boo); assertEquals(3, boo.getFoo().hello()); assertEquals(1, boo.getFoo().getCounter()); } public void testCreate() { PetiteContainer pc = new PetiteContainer(); pc.registerBean(Foo.class); pc.registerBean(Zoo.class); pc.registerBean(Boo.class); assertEquals(3, pc.getTotalBeans()); assertEquals(1, pc.getTotalScopes()); assertEquals(0, Foo.instanceCounter); Boo boo = pc.createBean(Boo.class); assertNotNull(boo); assertNotNull(boo.getFoo()); assertNotNull(boo.zoo); assertNotSame(boo.zoo.boo, boo); // not equal instances!!! assertEquals(1, boo.getFoo().hello()); assertEquals(1, boo.getCount()); } public void testCtor() { PetiteContainer pc = new PetiteContainer(); pc.registerBean(BooC.class); pc.registerBean(Foo.class); assertEquals(2, pc.getTotalBeans()); assertEquals(1, pc.getTotalScopes()); assertEquals(0, Foo.instanceCounter); BooC boo = (BooC) pc.getBean("booC"); assertNotNull(boo); assertNotNull(boo.getFoo()); assertEquals(1, boo.getFoo().hello()); pc.registerBean("boo", BooC2.class); pc.registerBean(Zoo.class); assertEquals(4, pc.getTotalBeans()); assertEquals(1, pc.getTotalScopes()); assertEquals(1, Foo.instanceCounter); try { pc.getBean("boo"); fail(); } catch (PetiteException pex) { // ignore // cyclic dependency } } public void testAutowire() { PetiteContainer pc = new PetiteContainer(); pc.registerBean(Goo.class, ProtoScope.class); pc.registerBean(Loo.class); assertEquals(2, pc.getTotalBeans()); Goo goo = (Goo) pc.getBean("goo"); assertNotNull(goo); assertNotNull(goo.looCustom); assertNull(goo.foo); pc.registerBean(Foo.class); goo = (Goo) pc.getBean("goo"); assertNotNull(goo); assertNotNull(goo.looCustom); assertNull(goo.foo); pc = new PetiteContainer(); pc.getConfig().setDefaultWiringMode(WiringMode.AUTOWIRE); pc.registerBean(Goo.class, ProtoScope.class); pc.registerBean(Loo.class); pc.registerBean(Foo.class); goo = (Goo) pc.getBean("goo"); assertNotNull(goo); assertNotNull(goo.looCustom); assertNotNull(goo.foo); pc.removeBean(Goo.class); } public void testInterface() { PetiteContainer pc = new PetiteContainer(); pc.registerBean(Foo.class); pc.registerBean("ioo", DefaultIoo.class); assertEquals(2, pc.getTotalBeans()); Ioo ioo = (Ioo) pc.getBean("ioo"); assertNotNull(ioo); assertNotNull(ioo.getFoo()); assertEquals(DefaultIoo.class, ioo.getClass()); } public void testSelf() { PetiteContainer pc = new PetiteContainer(); pc.addSelf(); assertEquals(1, pc.getTotalBeans()); PetiteContainer pc2 = (PetiteContainer) pc.getBean(PetiteContainer.PETITE_CONTAINER_REF_NAME); assertEquals(pc2, pc); } public void testInit() { PetiteContainer pc = new PetiteContainer(); pc.registerBean(Foo.class); pc.registerBean(Zoo.class); pc.registerBean(Boo.class); pc.registerBean("boo2", Boo.class); Boo boo = (Boo) pc.getBean("boo"); assertNotNull(boo.getFoo()); assertEquals(1, boo.getCount()); Boo boo2 = (Boo) pc.getBean("boo2"); assertNotSame(boo, boo2); assertEquals(1, boo2.getCount()); assertSame(boo.getFoo(), boo2.getFoo()); List<String> order = boo.orders; assertEquals(6, order.size()); assertEquals("first", order.get(0)); assertEquals("second", order.get(1)); // Collections.sort() is stable: equals methods are not reordered. assertEquals("third", order.get(2)); assertEquals("init", order.get(3)); assertEquals("beforeLast", order.get(4)); assertEquals("last", order.get(5)); } }
true
true
public void testContainer() { PetiteContainer pc = new PetiteContainer(); AutomagicPetiteConfigurator configurator = new AutomagicPetiteConfigurator(); configurator.setIncludedEntries(new String[] {"jodd.petite.*"}); configurator.setExcludedEntries(new String[] {"jodd.petite.data.*"}); configurator.configure(pc); assertEquals(1, pc.getTotalBeans()); assertEquals(1, pc.getTotalScopes()); assertEquals(0, Foo.instanceCounter); Foo foo = (Foo) pc.getBean("foo"); assertNotNull(foo); assertEquals(1, foo.hello()); foo = (Foo) pc.getBean("foo"); assertEquals(1, foo.hello()); // register again the same class, but this time with proto scope pc.registerBean("foo2", Foo.class, ProtoScope.class); assertEquals(2, pc.getTotalBeans()); assertEquals(2, pc.getTotalScopes()); assertEquals(2, ((Foo) pc.getBean("foo2")).hello()); assertEquals(3, ((Foo) pc.getBean("foo2")).hello()); // register boo pc.registerBean(Boo.class); assertEquals(3, pc.getTotalBeans()); assertEquals(2, pc.getTotalScopes()); Boo boo; try { //noinspection UnusedAssignment boo = (Boo) pc.getBean("boo"); fail(); } catch (PetiteException pex) { // zoo class is missing } pc.registerBean(Zoo.class); assertEquals(4, pc.getTotalBeans()); assertEquals(2, pc.getTotalScopes()); boo = (Boo) pc.getBean("boo"); assertNotNull(boo); assertNotNull(boo.getFoo()); assertNotNull(boo.zoo); assertSame(boo.zoo.boo, boo); assertEquals(3, boo.getFoo().hello()); assertEquals(1, boo.getFoo().getCounter()); }
public void testContainer() { PetiteContainer pc = new PetiteContainer(); AutomagicPetiteConfigurator configurator = new AutomagicPetiteConfigurator(); configurator.setIncludedEntries("jodd.petite.*"); configurator.setExcludedEntries("jodd.petite.data.*", "jodd.petite.test3.*"); configurator.configure(pc); assertEquals(1, pc.getTotalBeans()); assertEquals(1, pc.getTotalScopes()); assertEquals(0, Foo.instanceCounter); Foo foo = (Foo) pc.getBean("foo"); assertNotNull(foo); assertEquals(1, foo.hello()); foo = (Foo) pc.getBean("foo"); assertEquals(1, foo.hello()); // register again the same class, but this time with proto scope pc.registerBean("foo2", Foo.class, ProtoScope.class); assertEquals(2, pc.getTotalBeans()); assertEquals(2, pc.getTotalScopes()); assertEquals(2, ((Foo) pc.getBean("foo2")).hello()); assertEquals(3, ((Foo) pc.getBean("foo2")).hello()); // register boo pc.registerBean(Boo.class); assertEquals(3, pc.getTotalBeans()); assertEquals(2, pc.getTotalScopes()); Boo boo; try { //noinspection UnusedAssignment boo = (Boo) pc.getBean("boo"); fail(); } catch (PetiteException pex) { // zoo class is missing } pc.registerBean(Zoo.class); assertEquals(4, pc.getTotalBeans()); assertEquals(2, pc.getTotalScopes()); boo = (Boo) pc.getBean("boo"); assertNotNull(boo); assertNotNull(boo.getFoo()); assertNotNull(boo.zoo); assertSame(boo.zoo.boo, boo); assertEquals(3, boo.getFoo().hello()); assertEquals(1, boo.getFoo().getCounter()); }
diff --git a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/sample/SampleWSBase.java b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/sample/SampleWSBase.java index 0d9fdc4e..3bd324e4 100644 --- a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/sample/SampleWSBase.java +++ b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/sample/SampleWSBase.java @@ -1,122 +1,123 @@ /******************************************************************************* * Copyright (c) 2010 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.ws.ui.bot.test.sample; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.text.MessageFormat; import java.util.logging.Level; import javax.xml.namespace.QName; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor; import org.jboss.tools.ws.ui.bot.test.WSTestBase; import org.jboss.tools.ws.ui.bot.test.uiutils.actions.NewSampleWSWizardAction; import org.jboss.tools.ws.ui.bot.test.uiutils.actions.NewSimpleWSWizardAction; import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.SampleWSWizard; import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.SimpleWSWizard; import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.Type; import org.jboss.tools.ws.ui.bot.test.wsclient.WSClient; /** * Test base for all sample Web Services bot tests * @author jjankovi * */ public class SampleWSBase extends WSTestBase { protected static final String SOAP_REQUEST = getSoapRequest("<ns1:sayHello xmlns:ns1=\"http://{0}/\"><arg0>{1}</arg0></ns1:sayHello>"); protected static final String SERVER_URL = "localhost:8080"; protected IProject getProject(String project) { return ResourcesPlugin.getWorkspace().getRoot().getProject(project); } protected IFile getDD(String project) { return getProject(project).getFile("WebContent/WEB-INF/web.xml"); } protected SWTBotEditor createSampleService(Type type, String project, String name, String pkg, String cls, String appCls) { SampleWSWizard w = new NewSampleWSWizardAction(type).run(); w.setProjectName(project).setServiceName(name); w.setPackageName(pkg).setClassName(cls); if (type == Type.REST) { w.setApplicationClassName(appCls); w.addRESTEasyLibraryFromRuntime(); } w.finish(); util.waitForNonIgnoredJobs(); return bot.editorByTitle(cls + ".java"); } protected SWTBotEditor createSimpleService(Type type, String project, String name, String pkg, String cls, String appCls) { SimpleWSWizard w = new NewSimpleWSWizardAction(type).run(); w.setProjectName(project).setServiceName(name); w.setPackageName(pkg).setClassName(cls); if (type == Type.REST) { w.addRESTEasyLibraryFromRuntime(); w.setApplicationClassName(appCls); } w.finish(); util.waitForNonIgnoredJobs(); return bot.editorByTitle(cls + ".java"); } protected void checkService(Type type, String project, String svcName, String svcPkg, String svcClass, String msgContent, String appCls) { SWTBotEditor ed = bot.editorByTitle(svcClass + ".java"); ed.show(); String code = ed.toTextEditor().getText(); assertContains("package " + svcPkg + ";", code); String dd = resourceHelper.readFile(getDD(project)); switch (type) { case REST: assertContains("@Path(\"/" + svcName + "\")", code); assertContains("@GET()", code); assertContains("@Produces(\"text/plain\")", code); assertContains("<servlet-name>Resteasy</servlet-name>", dd); assertContains("<param-value>" + svcPkg + "." + appCls + "</param-value>", dd); break; case SOAP: assertContains("<servlet-name>" + svcName + "</servlet-name>", dd); break; } + deploymentHelper.removeProjectFromServer(project); deploymentHelper.runProject(project); switch (type) { case REST: try { URL u = new URL("http://" + SERVER_URL + "/" + project + "/" + svcName); String s = resourceHelper.readStream(u.openConnection().getInputStream()); assertEquals(msgContent, s); } catch (MalformedURLException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } catch (IOException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } break; case SOAP: try { WSClient c = new WSClient(new URL("http://" + SERVER_URL + "/" + project + "/" + svcName), new QName("http://" + svcPkg + "/", svcClass + "Service"), new QName("http://" + svcPkg + "/", svcClass + "Port")); assertContains("Hello " + msgContent + "!", c.callService(MessageFormat.format(SOAP_REQUEST, svcPkg, msgContent))); } catch (MalformedURLException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } break; } } }
true
true
protected void checkService(Type type, String project, String svcName, String svcPkg, String svcClass, String msgContent, String appCls) { SWTBotEditor ed = bot.editorByTitle(svcClass + ".java"); ed.show(); String code = ed.toTextEditor().getText(); assertContains("package " + svcPkg + ";", code); String dd = resourceHelper.readFile(getDD(project)); switch (type) { case REST: assertContains("@Path(\"/" + svcName + "\")", code); assertContains("@GET()", code); assertContains("@Produces(\"text/plain\")", code); assertContains("<servlet-name>Resteasy</servlet-name>", dd); assertContains("<param-value>" + svcPkg + "." + appCls + "</param-value>", dd); break; case SOAP: assertContains("<servlet-name>" + svcName + "</servlet-name>", dd); break; } deploymentHelper.runProject(project); switch (type) { case REST: try { URL u = new URL("http://" + SERVER_URL + "/" + project + "/" + svcName); String s = resourceHelper.readStream(u.openConnection().getInputStream()); assertEquals(msgContent, s); } catch (MalformedURLException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } catch (IOException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } break; case SOAP: try { WSClient c = new WSClient(new URL("http://" + SERVER_URL + "/" + project + "/" + svcName), new QName("http://" + svcPkg + "/", svcClass + "Service"), new QName("http://" + svcPkg + "/", svcClass + "Port")); assertContains("Hello " + msgContent + "!", c.callService(MessageFormat.format(SOAP_REQUEST, svcPkg, msgContent))); } catch (MalformedURLException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } break; } }
protected void checkService(Type type, String project, String svcName, String svcPkg, String svcClass, String msgContent, String appCls) { SWTBotEditor ed = bot.editorByTitle(svcClass + ".java"); ed.show(); String code = ed.toTextEditor().getText(); assertContains("package " + svcPkg + ";", code); String dd = resourceHelper.readFile(getDD(project)); switch (type) { case REST: assertContains("@Path(\"/" + svcName + "\")", code); assertContains("@GET()", code); assertContains("@Produces(\"text/plain\")", code); assertContains("<servlet-name>Resteasy</servlet-name>", dd); assertContains("<param-value>" + svcPkg + "." + appCls + "</param-value>", dd); break; case SOAP: assertContains("<servlet-name>" + svcName + "</servlet-name>", dd); break; } deploymentHelper.removeProjectFromServer(project); deploymentHelper.runProject(project); switch (type) { case REST: try { URL u = new URL("http://" + SERVER_URL + "/" + project + "/" + svcName); String s = resourceHelper.readStream(u.openConnection().getInputStream()); assertEquals(msgContent, s); } catch (MalformedURLException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } catch (IOException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } break; case SOAP: try { WSClient c = new WSClient(new URL("http://" + SERVER_URL + "/" + project + "/" + svcName), new QName("http://" + svcPkg + "/", svcClass + "Service"), new QName("http://" + svcPkg + "/", svcClass + "Port")); assertContains("Hello " + msgContent + "!", c.callService(MessageFormat.format(SOAP_REQUEST, svcPkg, msgContent))); } catch (MalformedURLException e) { LOGGER.log(Level.WARNING, e.getMessage(), e); } break; } }
diff --git a/test/unit/edu/sc/seis/sod/StatusTest.java b/test/unit/edu/sc/seis/sod/StatusTest.java index 11ca7be63..ac52fbb2c 100644 --- a/test/unit/edu/sc/seis/sod/StatusTest.java +++ b/test/unit/edu/sc/seis/sod/StatusTest.java @@ -1,23 +1,23 @@ /** * StatusTest.java * * @author Created by Omnicore CodeGuide */ package edu.sc.seis.sod; import junit.framework.TestCase; public class StatusTest extends TestCase { - public void testGetFromInt() throws NoSuchFieldException{ + public void testGetFromInt(){ for (int i = 0; i < Status.ALL.length; i++) { for (int j = 0; j < Status.ALL[i].length; j++) { assertEquals("Check status for "+i+", "+j, Status.ALL[i][j], Status.getFromShort(Status.ALL[i][j].getAsShort())); } } } }
true
true
public void testGetFromInt() throws NoSuchFieldException{ for (int i = 0; i < Status.ALL.length; i++) { for (int j = 0; j < Status.ALL[i].length; j++) { assertEquals("Check status for "+i+", "+j, Status.ALL[i][j], Status.getFromShort(Status.ALL[i][j].getAsShort())); } } }
public void testGetFromInt(){ for (int i = 0; i < Status.ALL.length; i++) { for (int j = 0; j < Status.ALL[i].length; j++) { assertEquals("Check status for "+i+", "+j, Status.ALL[i][j], Status.getFromShort(Status.ALL[i][j].getAsShort())); } } }
diff --git a/modules/dar/src/main/java/org/cipango/dar/DefaultApplicationRouter.java b/modules/dar/src/main/java/org/cipango/dar/DefaultApplicationRouter.java index 6026167..80963f1 100644 --- a/modules/dar/src/main/java/org/cipango/dar/DefaultApplicationRouter.java +++ b/modules/dar/src/main/java/org/cipango/dar/DefaultApplicationRouter.java @@ -1,235 +1,235 @@ // ======================================================================== // Copyright 2008-2009 NEXCOM Systems // ------------------------------------------------------------------------ // 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.cipango.dar; import java.io.File; import java.io.Serializable; import java.net.URI; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.SortedSet; import java.util.TreeSet; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.ar.SipApplicationRouter; import javax.servlet.sip.ar.SipApplicationRouterInfo; import javax.servlet.sip.ar.SipApplicationRoutingDirective; import javax.servlet.sip.ar.SipApplicationRoutingRegion; import javax.servlet.sip.ar.SipRouteModifier; import javax.servlet.sip.ar.SipTargetedRequestInfo; import org.mortbay.log.Log; /** * Default Application Router. * Looks for its configuration from the property javax.servlet.sip.ar.dar.configuration * or etc/dar.properties if not defined. */ public class DefaultApplicationRouter implements SipApplicationRouter { public static final String __J_S_DAR_CONFIGURATION = "javax.servlet.sip.ar.dar.configuration"; public static final String MATCH_ON_NEW_OUTGOING_REQUESTS = "org.cipango.dar.matchOnNewOutgoingRequests"; public static final String DEFAULT_CONFIGURATION = "etc/dar.properties"; private Map<String, RouterInfo[]> _routerInfoMap; private String _configuration; private SortedSet<String> _applicationNames = new TreeSet<String>(); private boolean _matchOnNewOutgoingRequests; public String[] getApplicationNames() { return _applicationNames.toArray(new String[] {}); } public void applicationDeployed(List<String> newlyDeployedApplicationNames) { _applicationNames.addAll(newlyDeployedApplicationNames); init(); } public void applicationUndeployed(List<String> toRemove) { _applicationNames.removeAll(toRemove); init(); } public void destroy() { } public SipApplicationRouterInfo getNextApplication(SipServletRequest initialRequest, SipApplicationRoutingRegion region, SipApplicationRoutingDirective directive, SipTargetedRequestInfo toto, Serializable stateInfo) { - if (!_matchOnNewOutgoingRequests && initialRequest.getInitialRemoteAddr() == null) + if (!_matchOnNewOutgoingRequests && initialRequest.getRemoteAddr() == null) return null; if (_routerInfoMap == null || _routerInfoMap.isEmpty()) { if (stateInfo != null || _applicationNames.isEmpty() || directive != SipApplicationRoutingDirective.NEW) return null; return new SipApplicationRouterInfo(_applicationNames.first(), SipApplicationRoutingRegion.NEUTRAL_REGION, initialRequest.getFrom().getURI().toString(), null, SipRouteModifier.NO_ROUTE, 1); } String method = initialRequest.getMethod(); RouterInfo[] infos = _routerInfoMap.get(method.toUpperCase()); if (infos == null) return null; int index = 0; if (stateInfo != null) index = (Integer) stateInfo; if (index >= 0 && index < infos.length) { RouterInfo info = infos[index]; String identity = info.getIdentity(); if (identity.startsWith("DAR:")) { try { identity = initialRequest.getAddressHeader(identity.substring("DAR:".length())).getURI().toString(); } catch (Exception e) { Log.debug("Failed to parse router info identity: " + info.getIdentity(), e); } } return new SipApplicationRouterInfo(info.getName(), info.getRegion(), identity, null, SipRouteModifier.NO_ROUTE, index + 1); } return null; } public String getDefaultApplication() { if ((_routerInfoMap == null || _routerInfoMap.isEmpty()) && !_applicationNames.isEmpty()) return _applicationNames.first(); return null; } public void setRouterInfos(Map<String, RouterInfo[]> infoMap) { _routerInfoMap = infoMap; } public Map<String, RouterInfo[]> getRouterInfos() { return _routerInfoMap; } public String getConfig() { StringBuilder sb = new StringBuilder(); Iterator<String> it = _routerInfoMap.keySet().iterator(); while (it.hasNext()) { String method = (String) it.next(); RouterInfo[] routerInfos = _routerInfoMap.get(method); sb.append(method).append(": "); for (int i = 0; routerInfos != null && i < routerInfos.length; i++) { RouterInfo routerInfo = routerInfos[i]; sb.append('('); sb.append('"').append(routerInfo.getName()).append("\", "); sb.append('"').append(routerInfo.getIdentity()).append("\", "); sb.append('"').append(routerInfo.getRegion().getType()).append("\", "); sb.append('"').append(routerInfo.getUri()).append("\", "); sb.append('"').append(routerInfo.getRouteModifier()).append("\", "); sb.append('"').append(i).append('"'); sb.append(')'); if (i + 1 < routerInfos.length) sb.append(", "); } sb.append('\n'); } return sb.toString(); } public RouterInfo[] getRouterInfo(String key) { return _routerInfoMap.get(key); } public void init() { _matchOnNewOutgoingRequests = !System.getProperty(MATCH_ON_NEW_OUTGOING_REQUESTS, "true").equalsIgnoreCase("false"); if (_configuration == null) { String configuration = System.getProperty(__J_S_DAR_CONFIGURATION); if (configuration != null) { _configuration = configuration; } else if (System.getProperty("jetty.home") != null) { File home = new File(System.getProperty("jetty.home")); _configuration = new File(home, DEFAULT_CONFIGURATION).toURI().toString(); } if (_configuration == null) _configuration = DEFAULT_CONFIGURATION; } try { DARConfiguration config = new DARConfiguration(new URI(_configuration)); config.configure(this); } catch (Exception e) { Log.debug("DAR configuration error: " + e); } if ((_routerInfoMap == null || _routerInfoMap.isEmpty()) && !_applicationNames.isEmpty()) Log.info("No DAR configuration. Using application: " + _applicationNames.first()); } public void setConfiguration(String configuration) { _configuration = configuration; } public void init(Properties properties) { init(); } public String getConfiguration() { return _configuration; } public boolean isMatchOnNewOutgoingRequests() { return _matchOnNewOutgoingRequests; } }
true
true
public SipApplicationRouterInfo getNextApplication(SipServletRequest initialRequest, SipApplicationRoutingRegion region, SipApplicationRoutingDirective directive, SipTargetedRequestInfo toto, Serializable stateInfo) { if (!_matchOnNewOutgoingRequests && initialRequest.getInitialRemoteAddr() == null) return null; if (_routerInfoMap == null || _routerInfoMap.isEmpty()) { if (stateInfo != null || _applicationNames.isEmpty() || directive != SipApplicationRoutingDirective.NEW) return null; return new SipApplicationRouterInfo(_applicationNames.first(), SipApplicationRoutingRegion.NEUTRAL_REGION, initialRequest.getFrom().getURI().toString(), null, SipRouteModifier.NO_ROUTE, 1); } String method = initialRequest.getMethod(); RouterInfo[] infos = _routerInfoMap.get(method.toUpperCase()); if (infos == null) return null; int index = 0; if (stateInfo != null) index = (Integer) stateInfo; if (index >= 0 && index < infos.length) { RouterInfo info = infos[index]; String identity = info.getIdentity(); if (identity.startsWith("DAR:")) { try { identity = initialRequest.getAddressHeader(identity.substring("DAR:".length())).getURI().toString(); } catch (Exception e) { Log.debug("Failed to parse router info identity: " + info.getIdentity(), e); } } return new SipApplicationRouterInfo(info.getName(), info.getRegion(), identity, null, SipRouteModifier.NO_ROUTE, index + 1); } return null; }
public SipApplicationRouterInfo getNextApplication(SipServletRequest initialRequest, SipApplicationRoutingRegion region, SipApplicationRoutingDirective directive, SipTargetedRequestInfo toto, Serializable stateInfo) { if (!_matchOnNewOutgoingRequests && initialRequest.getRemoteAddr() == null) return null; if (_routerInfoMap == null || _routerInfoMap.isEmpty()) { if (stateInfo != null || _applicationNames.isEmpty() || directive != SipApplicationRoutingDirective.NEW) return null; return new SipApplicationRouterInfo(_applicationNames.first(), SipApplicationRoutingRegion.NEUTRAL_REGION, initialRequest.getFrom().getURI().toString(), null, SipRouteModifier.NO_ROUTE, 1); } String method = initialRequest.getMethod(); RouterInfo[] infos = _routerInfoMap.get(method.toUpperCase()); if (infos == null) return null; int index = 0; if (stateInfo != null) index = (Integer) stateInfo; if (index >= 0 && index < infos.length) { RouterInfo info = infos[index]; String identity = info.getIdentity(); if (identity.startsWith("DAR:")) { try { identity = initialRequest.getAddressHeader(identity.substring("DAR:".length())).getURI().toString(); } catch (Exception e) { Log.debug("Failed to parse router info identity: " + info.getIdentity(), e); } } return new SipApplicationRouterInfo(info.getName(), info.getRegion(), identity, null, SipRouteModifier.NO_ROUTE, index + 1); } return null; }
diff --git a/src/org/xdty/smilehelper/FloatWindowService.java b/src/org/xdty/smilehelper/FloatWindowService.java index b1a1375..fab5d4e 100755 --- a/src/org/xdty/smilehelper/FloatWindowService.java +++ b/src/org/xdty/smilehelper/FloatWindowService.java @@ -1,182 +1,182 @@ package org.xdty.smilehelper; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import android.app.ActivityManager; import android.app.ActivityManager.RunningTaskInfo; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.database.Cursor; import android.os.Handler; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class FloatWindowService extends Service { /** * 用于在线程中创建或移除悬浮窗。 */ private Handler handler = new Handler(); /** * 定时器,定时进行检测当前应该创建还是移除悬浮窗。 */ private Timer timer; /** * 数据库存储 */ private DatabaseHelper mDatabaseHelper; /** * 数据库信息保存到数组中 */ private static ArrayList<String> mAppList; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // 获取数据库列表,保存到mAppList中 mDatabaseHelper = new DatabaseHelper(getApplicationContext()); Cursor cursor = mDatabaseHelper.selectForChecked(true); mAppList = new ArrayList<String>(); if (cursor.getCount()==0) { mAppList.add("null"); } else { while (cursor.moveToNext()) { mAppList.add(cursor.getString(2)); } } // 开启定时器,每隔0.5秒刷新一次 if (timer == null) { timer = new Timer(); timer.scheduleAtFixedRate(new RefreshTask(), 0, 500); } new RefreshTask(); return super.onStartCommand(intent, flags, startId); } /** * 获取当前界面顶部的Acivity名称 * @return 返回完整的类名 */ private String getTopAppName() { ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1); return rti.get(0).topActivity.getClassName(); } /** * 获取当前界面顶部的Acivity包名称 * @return 返回包名 */ private String getTopPackageName() { ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> rti = mActivityManager.getRunningTasks(1); return rti.get(0).topActivity.getPackageName(); } /** * 判断是否为被添加进appList */ private boolean isInList() { return mAppList.isEmpty() ? false : mAppList.contains(getTopAppName()); } @Override public void onDestroy() { super.onDestroy(); // Service被终止的同时也停止定时器继续运行 timer.cancel(); timer = null; } class RefreshTask extends TimerTask { @Override public void run() { if (!isHome() && !MyWindowManager.isWindowShowing() && !isClose()) { handler.post(new Runnable() { @Override public void run() { if (MyWindowManager.getAddState()) { MyWindowManager.createAddWindow(getApplicationContext()); } else if (isInList()) { MyWindowManager.createSmallWindow(getApplicationContext()); } } }); } - else if (isHome() && MyWindowManager.isWindowShowing()) { + else if ((!isInList()||isHome()) && MyWindowManager.isWindowShowing()) { handler.post(new Runnable() { @Override public void run() { MyWindowManager.removeSmallWindow(getApplicationContext()); MyWindowManager.removeBigWindow(getApplicationContext()); MyWindowManager.removeAddWindow(getApplicationContext()); } }); } //闪动效果 // else { // MyWindowManager.removeSmallWindow(getApplicationContext()); // MyWindowManager.removeBigWindow(getApplicationContext()); // MyWindowManager.removeAddWindow(getApplicationContext()); // } // // 当前界面是桌面,且有悬浮窗显示,则更新内存数据。 // else if (isHome() && MyWindowManager.isWindowShowing()) { // handler.post(new Runnable() { // @Override // public void run() { // MyWindowManager.updateUsedPercent(getApplicationContext()); // } // }); // } } } private boolean isClose() { return FloatWindowSmallView.close; } /** * 判断当前界面是否是桌面 */ private boolean isHome() { return getHomes().contains(getTopPackageName()); } /** * 获得属于桌面的应用的应用包名称 * * @return 返回包含所有包名的字符串列表 */ private List<String> getHomes() { List<String> names = new ArrayList<String>(); PackageManager packageManager = this.getPackageManager(); Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); List<ResolveInfo> resolveInfo = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo ri : resolveInfo) { names.add(ri.activityInfo.packageName); } return names; } }
true
true
public void run() { if (!isHome() && !MyWindowManager.isWindowShowing() && !isClose()) { handler.post(new Runnable() { @Override public void run() { if (MyWindowManager.getAddState()) { MyWindowManager.createAddWindow(getApplicationContext()); } else if (isInList()) { MyWindowManager.createSmallWindow(getApplicationContext()); } } }); } else if (isHome() && MyWindowManager.isWindowShowing()) { handler.post(new Runnable() { @Override public void run() { MyWindowManager.removeSmallWindow(getApplicationContext()); MyWindowManager.removeBigWindow(getApplicationContext()); MyWindowManager.removeAddWindow(getApplicationContext()); } }); } //闪动效果 // else { // MyWindowManager.removeSmallWindow(getApplicationContext()); // MyWindowManager.removeBigWindow(getApplicationContext()); // MyWindowManager.removeAddWindow(getApplicationContext()); // } // // 当前界面是桌面,且有悬浮窗显示,则更新内存数据。 // else if (isHome() && MyWindowManager.isWindowShowing()) { // handler.post(new Runnable() { // @Override // public void run() { // MyWindowManager.updateUsedPercent(getApplicationContext()); // } // }); // } }
public void run() { if (!isHome() && !MyWindowManager.isWindowShowing() && !isClose()) { handler.post(new Runnable() { @Override public void run() { if (MyWindowManager.getAddState()) { MyWindowManager.createAddWindow(getApplicationContext()); } else if (isInList()) { MyWindowManager.createSmallWindow(getApplicationContext()); } } }); } else if ((!isInList()||isHome()) && MyWindowManager.isWindowShowing()) { handler.post(new Runnable() { @Override public void run() { MyWindowManager.removeSmallWindow(getApplicationContext()); MyWindowManager.removeBigWindow(getApplicationContext()); MyWindowManager.removeAddWindow(getApplicationContext()); } }); } //闪动效果 // else { // MyWindowManager.removeSmallWindow(getApplicationContext()); // MyWindowManager.removeBigWindow(getApplicationContext()); // MyWindowManager.removeAddWindow(getApplicationContext()); // } // // 当前界面是桌面,且有悬浮窗显示,则更新内存数据。 // else if (isHome() && MyWindowManager.isWindowShowing()) { // handler.post(new Runnable() { // @Override // public void run() { // MyWindowManager.updateUsedPercent(getApplicationContext()); // } // }); // } }
diff --git a/freeplane/src/org/freeplane/main/application/ApplicationViewController.java b/freeplane/src/org/freeplane/main/application/ApplicationViewController.java index 52953a2fe..6dfcb07c1 100644 --- a/freeplane/src/org/freeplane/main/application/ApplicationViewController.java +++ b/freeplane/src/org/freeplane/main/application/ApplicationViewController.java @@ -1,518 +1,523 @@ /* * Freeplane - mind map editor * Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev * * This file is created by Dimitry Polivaev in 2008. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.freeplane.main.application; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Cursor; import java.awt.EventQueue; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.net.URI; import java.net.URL; import java.text.MessageFormat; import javax.swing.ImageIcon; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLayeredPane; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.KeyStroke; import javax.swing.ToolTipManager; import javax.swing.UIManager; import org.freeplane.core.controller.Controller; import org.freeplane.core.frame.IMapViewManager; import org.freeplane.core.frame.ViewController; import org.freeplane.core.resources.IFreeplanePropertyListener; import org.freeplane.core.resources.ResourceController; import org.freeplane.core.ui.components.FreeplaneMenuBar; import org.freeplane.core.ui.components.LimitedWidthTooltipUI; import org.freeplane.core.ui.components.UITools; import org.freeplane.core.util.Compat; class ApplicationViewController extends ViewController { private static final String TOOL_TIP_MANAGER = "toolTipManager."; private static final String TOOL_TIP_MANAGER_DISMISS_DELAY = "toolTipManager.dismissDelay"; private static final String TOOL_TIP_MANAGER_INITIAL_DELAY = "toolTipManager.initialDelay"; private static final String TOOL_TIP_MANAGER_RESHOW_DELAY = "toolTipManager.reshowDelay"; public static final String RESOURCES_USE_TABBED_PANE = "use_tabbed_pane"; private static final String SPLIT_PANE_LAST_LEFT_POSITION = "split_pane_last_left_position"; private static final String SPLIT_PANE_LAST_POSITION = "split_pane_last_position"; private static final String SPLIT_PANE_LAST_RIGHT_POSITION = "split_pane_last_right_position"; private static final String SPLIT_PANE_LAST_TOP_POSITION = "split_pane_last_top_position"; private static final String SPLIT_PANE_LEFT_POSITION = "split_pane_left_position"; private static final String SPLIT_PANE_POSITION = "split_pane_position"; private static final String SPLIT_PANE_RIGHT_POSITION = "split_pane_right_position"; private static final String SPLIT_PANE_TOP_POSITION = "split_pane_top_position"; final private Controller controller; final private JFrame frame; private MapViewTabs mapViewManager; private JComponent mContentComponent = null; /** Contains the value where the Note Window should be displayed (right, left, top, bottom) */ private String mLocationPreferenceValue; /** Contains the Note Window Component */ private JComponent mMindMapComponent; private JSplitPane mSplitPane; final private NavigationNextMapAction navigationNextMap; final private NavigationPreviousMapAction navigationPreviousMap; final private ResourceController resourceController; public ApplicationViewController(final Controller controller, final IMapViewManager mapViewController, final JFrame frame) { super(controller, mapViewController); this.controller = controller; navigationPreviousMap = new NavigationPreviousMapAction(controller); controller.addAction(navigationPreviousMap); navigationNextMap = new NavigationNextMapAction(controller); controller.addAction(navigationNextMap); resourceController = ResourceController.getResourceController(); this.frame = frame; getContentPane().setLayout(new BorderLayout()); // --- Set Note Window Location --- mLocationPreferenceValue = resourceController.getProperty("location", "bottom"); if (ResourceController.getResourceController().getBooleanProperty("no_scrollbar")) { getScrollPane().setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); getScrollPane().setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); } else { getScrollPane().setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); getScrollPane().setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); } mContentComponent = getScrollPane(); final boolean shouldUseTabbedPane = ResourceController.getResourceController().getBooleanProperty( ApplicationViewController.RESOURCES_USE_TABBED_PANE); if (shouldUseTabbedPane) { mapViewManager = new MapViewTabs(controller, this, mContentComponent); } else { getContentPane().add(mContentComponent, BorderLayout.CENTER); } getContentPane().add(getStatusBar(), BorderLayout.SOUTH); initFrame(frame); } /** * Called from the Controller, when the Location of the Note Window is changed on the Menu->View->Note Window Location */ @Override public void changeNoteWindowLocation(final boolean isSplitWindowOnorOff) { // -- Remove Note Window from old location -- if (isSplitWindowOnorOff == true) { // --- Remove and put it back in the new location the Note Window -- removeSplitPane(); } // --- Get the new location -- mLocationPreferenceValue = resourceController.getProperty("location"); // -- Display Note Window in the new location -- if (isSplitWindowOnorOff == true) { // --- Place the Note Window in the new place -- insertComponentIntoSplitPane(mMindMapComponent); } } public String getAdjustableProperty(final String label) { return resourceController.getAdjustableProperty(label); } /* * (non-Javadoc) * @see freeplane.main.FreeplaneMain#getContentPane() */ @Override public Container getContentPane() { return frame.getContentPane(); } @Override public FreeplaneMenuBar getFreeplaneMenuBar() { return (FreeplaneMenuBar) frame.getJMenuBar(); } /* * (non-Javadoc) * @see freeplane.main.FreeplaneMain#getJFrame() */ @Override public JFrame getJFrame() { return frame; } /* * (non-Javadoc) * @see freeplane.main.FreeplaneMain#getLayeredPane() */ public JLayeredPane getLayeredPane() { return frame.getLayeredPane(); } @Override public JSplitPane insertComponentIntoSplitPane(final JComponent pMindMapComponent) { if (mSplitPane != null) { return mSplitPane; } removeContentComponent(); // --- Save the Component -- mMindMapComponent = pMindMapComponent; // --- Devider position variables -- int splitPanePosition = -1; int lastSplitPanePosition = -1; if ("right".equals(mLocationPreferenceValue)) { mSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, getScrollPane(), pMindMapComponent); splitPanePosition = resourceController.getIntProperty(SPLIT_PANE_RIGHT_POSITION, -1); lastSplitPanePosition = resourceController.getIntProperty(SPLIT_PANE_LAST_RIGHT_POSITION, -1); } else if ("left".equals(mLocationPreferenceValue)) { mSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, pMindMapComponent, getScrollPane()); splitPanePosition = resourceController.getIntProperty(SPLIT_PANE_LEFT_POSITION, -1); lastSplitPanePosition = resourceController.getIntProperty(SPLIT_PANE_LAST_LEFT_POSITION, -1); } else if ("top".equals(mLocationPreferenceValue)) { mSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pMindMapComponent, getScrollPane()); splitPanePosition = resourceController.getIntProperty(SPLIT_PANE_TOP_POSITION, -1); lastSplitPanePosition = resourceController.getIntProperty(SPLIT_PANE_LAST_TOP_POSITION, -1); } else if ("bottom".equals(mLocationPreferenceValue)) { mSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, getScrollPane(), pMindMapComponent); splitPanePosition = resourceController.getIntProperty(SPLIT_PANE_POSITION, -1); lastSplitPanePosition = resourceController.getIntProperty(SPLIT_PANE_LAST_POSITION, -1); } mSplitPane.setContinuousLayout(true); mSplitPane.setOneTouchExpandable(false); /* * This means that the mind map area gets all the space that results * from resizing the window. */ mSplitPane.setResizeWeight(1.0d); final InputMap map = (InputMap) UIManager.get("SplitPane.ancestorInputMap"); final KeyStroke keyStrokeF6 = KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0); final KeyStroke keyStrokeF8 = KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0); map.remove(keyStrokeF6); map.remove(keyStrokeF8); mContentComponent = mSplitPane; setContentComponent(); if (splitPanePosition != -1 && lastSplitPanePosition != -1) { mSplitPane.setDividerLocation(splitPanePosition); mSplitPane.setLastDividerLocation(lastSplitPanePosition); } else { EventQueue.invokeLater(new Runnable() { public void run() { mSplitPane.setDividerLocation(0.5); } }); } return mSplitPane; } @Override public boolean isApplet() { return false; } @Override public void openDocument(final URI uri) throws IOException { String propertyString; final String osName = System.getProperty("os.name"); if (osName.substring(0, 3).equals("Win")) { propertyString = "default_browser_command_windows"; if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) { propertyString += "_9x"; } else { propertyString += "_nt"; } } else if (osName.startsWith("Mac OS")) { propertyString = "default_browser_command_mac"; } else { propertyString = "default_browser_command_other_os"; } final Object[] messageArguments = { uri.toString() }; final MessageFormat formatter = new MessageFormat(ResourceController.getResourceController().getProperty( propertyString)); String browserCommand = formatter.format(messageArguments); Runtime.getRuntime().exec(browserCommand); } /** * Open url in WWW browser. This method hides some differences between * operating systems. */ @Override public void openDocument(final URL url) throws Exception { - String correctedUrl = url.toExternalForm(); - if (url.getProtocol().equals("file")) { - correctedUrl = correctedUrl.replace('\\', '/').replaceAll(" ", "%20"); - } final String osName = System.getProperty("os.name"); if (osName.substring(0, 3).equals("Win")) { String propertyString = "default_browser_command_windows"; if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) { propertyString += "_9x"; } else { propertyString += "_nt"; } - String command = null; + String[] command = null; try { final Object[] messageArguments = { url.toString() }; final MessageFormat formatter = new MessageFormat(ResourceController.getResourceController() .getProperty(propertyString)); String browserCommand = formatter.format(messageArguments); if (url.getProtocol().equals("file")) { - command = "rundll32 url.dll,FileProtocolHandler " + url.toString(); + command = new String[]{"rundll32", "url.dll,FileProtocolHandler", url.toString()}; if (System.getProperty("os.name").startsWith("Windows 2000")) { - command = "rundll32 shell32.dll,ShellExec_RunDLL " + url.toString(); + command = new String[]{"rundll32", "shell32.dll,ShellExec_RunDLL", url.toString()}; } } else if (url.toString().startsWith("mailto:")) { - command = "rundll32 url.dll,FileProtocolHandler " + url.toString(); + command = new String[]{"rundll32", "url.dll,FileProtocolHandler", url.toString()}; } else { - command = browserCommand; + Runtime.getRuntime().exec(browserCommand); + return; } Runtime.getRuntime().exec(command); } catch (final IOException x) { UITools .errorMessage("Could not invoke browser.\n\nFreeplane excecuted the following statement on a command line:\n\"" + command + "\".\n\nYou may look at the user or default property called '" + propertyString + "'."); System.err.println("Caught: " + x); } } else if (osName.startsWith("Mac OS")) { String browserCommand = null; try { + String correctedUrl = url.toExternalForm(); + if (url.getProtocol().equals("file")) { + correctedUrl = correctedUrl.replace('\\', '/').replaceAll(" ", "%20"); + } final Object[] messageArguments = { correctedUrl, url.toString() }; final MessageFormat formatter = new MessageFormat(ResourceController.getResourceController() .getProperty("default_browser_command_mac")); browserCommand = formatter.format(messageArguments); Runtime.getRuntime().exec(browserCommand); } catch (final IOException ex2) { UITools .errorMessage("Could not invoke browser.\n\nFreeplane excecuted the following statement on a command line:\n\"" + browserCommand + "\".\n\nYou may look at the user or default property called 'default_browser_command_mac'."); System.err.println("Caught: " + ex2); } } else { String browserCommand = null; try { + String correctedUrl = url.toExternalForm(); + if (url.getProtocol().equals("file")) { + correctedUrl = correctedUrl.replace('\\', '/').replaceAll(" ", "%20"); + } final Object[] messageArguments = { correctedUrl, url.toString() }; final MessageFormat formatter = new MessageFormat(ResourceController.getResourceController() .getProperty("default_browser_command_other_os")); browserCommand = formatter.format(messageArguments); Runtime.getRuntime().exec(browserCommand); } catch (final IOException ex2) { UITools .errorMessage("Could not invoke browser.\n\nFreeplane excecuted the following statement on a command line:\n\"" + browserCommand + "\".\n\nYou may look at the user or default property called 'default_browser_command_other_os'."); System.err.println("Caught: " + ex2); } } } @Override public boolean quit() { if (!super.quit()) { return false; } frame.dispose(); return true; } private void removeContentComponent() { if (mapViewManager != null) { mapViewManager.removeContentComponent(); } else { getContentPane().remove(mContentComponent); frame.getRootPane().revalidate(); } } @Override public void removeSplitPane() { if (mSplitPane == null) { return; } saveSplitPanePosition(); removeContentComponent(); mContentComponent = getScrollPane(); setContentComponent(); mSplitPane = null; } @Override public void saveProperties() { saveSplitPanePosition(); resourceController.setProperty("map_view_zoom", Float.toString(getZoom())); if(! isFullScreenEnabled()){ final int winState = frame.getExtendedState() & ~Frame.ICONIFIED; if (JFrame.MAXIMIZED_BOTH != (winState & JFrame.MAXIMIZED_BOTH)) { resourceController.setProperty("appwindow_x", String.valueOf(frame.getX())); resourceController.setProperty("appwindow_y", String.valueOf(frame.getY())); resourceController.setProperty("appwindow_width", String.valueOf(frame.getWidth())); resourceController.setProperty("appwindow_height", String.valueOf(frame.getHeight())); } resourceController.setProperty("appwindow_state", String.valueOf(winState)); } } private void saveSplitPanePosition() { if (mSplitPane == null) { return; } if ("right".equals(mLocationPreferenceValue)) { resourceController.setProperty(SPLIT_PANE_RIGHT_POSITION, "" + mSplitPane.getDividerLocation()); resourceController.setProperty(SPLIT_PANE_LAST_RIGHT_POSITION, "" + mSplitPane.getLastDividerLocation()); } else if ("left".equals(mLocationPreferenceValue)) { resourceController.setProperty(SPLIT_PANE_LEFT_POSITION, "" + mSplitPane.getDividerLocation()); resourceController.setProperty(SPLIT_PANE_LAST_LEFT_POSITION, "" + mSplitPane.getLastDividerLocation()); } else if ("top".equals(mLocationPreferenceValue)) { resourceController.setProperty(SPLIT_PANE_TOP_POSITION, "" + mSplitPane.getDividerLocation()); resourceController.setProperty(SPLIT_PANE_LAST_TOP_POSITION, "" + mSplitPane.getLastDividerLocation()); } else { // "bottom".equals(mLocationPreferenceValue) also covered resourceController.setProperty(SPLIT_PANE_POSITION, "" + mSplitPane.getDividerLocation()); resourceController.setProperty(SPLIT_PANE_LAST_POSITION, "" + mSplitPane.getLastDividerLocation()); } } private void setContentComponent() { if (mapViewManager != null) { mapViewManager.setContentComponent(mContentComponent); } else { getContentPane().add(mContentComponent, BorderLayout.CENTER); frame.getRootPane().revalidate(); } } @Override protected void setFreeplaneMenuBar(final FreeplaneMenuBar menuBar) { frame.setJMenuBar(menuBar); } /* * (non-Javadoc) * @see freeplane.main.FreeplaneMain#setTitle(java.lang.String) */ @Override public void setTitle(final String title) { frame.setTitle(title); } @Override public void setWaitingCursor(final boolean waiting) { if (waiting) { frame.getRootPane().getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); frame.getRootPane().getGlassPane().setVisible(true); } else { frame.getRootPane().getGlassPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); frame.getRootPane().getGlassPane().setVisible(false); } } @Override protected void viewNumberChanged(final int number) { navigationPreviousMap.setEnabled(number > 0); navigationNextMap.setEnabled(number > 0); } public void initFrame(final JFrame frame) { final ImageIcon mWindowIcon; if (Compat.isLowerJdk(Compat.VERSION_1_6_0)) { mWindowIcon = new ImageIcon(ResourceController.getResourceController().getResource( "/images/Freeplane_frame_icon.png")); } else { mWindowIcon = new ImageIcon(ResourceController.getResourceController().getResource( "/images/Freeplane_frame_icon_32x32.png")); } frame.setIconImage(mWindowIcon.getImage()); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { controller.quit(new ActionEvent(this, 0, "quit")); } /* * fc, 14.3.2008: Completely removed, as it damaged the focus if for * example the note window was active. */ }); frame.setFocusTraversalKeysEnabled(false); final int win_width = ResourceController.getResourceController().getIntProperty("appwindow_width", 0); final int win_height = ResourceController.getResourceController().getIntProperty("appwindow_height", 0); final int win_x = ResourceController.getResourceController().getIntProperty("appwindow_x", 0); final int win_y = ResourceController.getResourceController().getIntProperty("appwindow_y", 0); UITools.setBounds(frame, win_x, win_y, win_width, win_height); setFrameSize(frame.getBounds()); int win_state = Integer .parseInt(ResourceController.getResourceController().getProperty("appwindow_state", "0")); win_state = ((win_state & Frame.ICONIFIED) != 0) ? Frame.NORMAL : win_state; frame.setExtendedState(win_state); setTooltipDelays(); LimitedWidthTooltipUI.initialize(); ResourceController.getResourceController().addPropertyChangeListener(new IFreeplanePropertyListener() { public void propertyChanged(final String propertyName, final String newValue, final String oldValue) { if (propertyName.startsWith(TOOL_TIP_MANAGER)) { setTooltipDelays(); } } }); } private void setTooltipDelays() { final ToolTipManager toolTipManager = ToolTipManager.sharedInstance(); final int initialDelay = ResourceController.getResourceController().getIntProperty( TOOL_TIP_MANAGER_INITIAL_DELAY, 0); toolTipManager.setInitialDelay(initialDelay); final int dismissDelay = ResourceController.getResourceController().getIntProperty( TOOL_TIP_MANAGER_DISMISS_DELAY, 0); toolTipManager.setDismissDelay(dismissDelay); final int reshowDelay = ResourceController.getResourceController().getIntProperty( TOOL_TIP_MANAGER_RESHOW_DELAY, 0); toolTipManager.setReshowDelay(reshowDelay); final int maxWidth = ResourceController.getResourceController().getIntProperty( "toolTipManager.max_tooltip_width", Integer.MAX_VALUE); LimitedWidthTooltipUI.setMaximumWidth(maxWidth); } }
false
true
public void openDocument(final URL url) throws Exception { String correctedUrl = url.toExternalForm(); if (url.getProtocol().equals("file")) { correctedUrl = correctedUrl.replace('\\', '/').replaceAll(" ", "%20"); } final String osName = System.getProperty("os.name"); if (osName.substring(0, 3).equals("Win")) { String propertyString = "default_browser_command_windows"; if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) { propertyString += "_9x"; } else { propertyString += "_nt"; } String command = null; try { final Object[] messageArguments = { url.toString() }; final MessageFormat formatter = new MessageFormat(ResourceController.getResourceController() .getProperty(propertyString)); String browserCommand = formatter.format(messageArguments); if (url.getProtocol().equals("file")) { command = "rundll32 url.dll,FileProtocolHandler " + url.toString(); if (System.getProperty("os.name").startsWith("Windows 2000")) { command = "rundll32 shell32.dll,ShellExec_RunDLL " + url.toString(); } } else if (url.toString().startsWith("mailto:")) { command = "rundll32 url.dll,FileProtocolHandler " + url.toString(); } else { command = browserCommand; } Runtime.getRuntime().exec(command); } catch (final IOException x) { UITools .errorMessage("Could not invoke browser.\n\nFreeplane excecuted the following statement on a command line:\n\"" + command + "\".\n\nYou may look at the user or default property called '" + propertyString + "'."); System.err.println("Caught: " + x); } } else if (osName.startsWith("Mac OS")) { String browserCommand = null; try { final Object[] messageArguments = { correctedUrl, url.toString() }; final MessageFormat formatter = new MessageFormat(ResourceController.getResourceController() .getProperty("default_browser_command_mac")); browserCommand = formatter.format(messageArguments); Runtime.getRuntime().exec(browserCommand); } catch (final IOException ex2) { UITools .errorMessage("Could not invoke browser.\n\nFreeplane excecuted the following statement on a command line:\n\"" + browserCommand + "\".\n\nYou may look at the user or default property called 'default_browser_command_mac'."); System.err.println("Caught: " + ex2); } } else { String browserCommand = null; try { final Object[] messageArguments = { correctedUrl, url.toString() }; final MessageFormat formatter = new MessageFormat(ResourceController.getResourceController() .getProperty("default_browser_command_other_os")); browserCommand = formatter.format(messageArguments); Runtime.getRuntime().exec(browserCommand); } catch (final IOException ex2) { UITools .errorMessage("Could not invoke browser.\n\nFreeplane excecuted the following statement on a command line:\n\"" + browserCommand + "\".\n\nYou may look at the user or default property called 'default_browser_command_other_os'."); System.err.println("Caught: " + ex2); } } }
public void openDocument(final URL url) throws Exception { final String osName = System.getProperty("os.name"); if (osName.substring(0, 3).equals("Win")) { String propertyString = "default_browser_command_windows"; if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) { propertyString += "_9x"; } else { propertyString += "_nt"; } String[] command = null; try { final Object[] messageArguments = { url.toString() }; final MessageFormat formatter = new MessageFormat(ResourceController.getResourceController() .getProperty(propertyString)); String browserCommand = formatter.format(messageArguments); if (url.getProtocol().equals("file")) { command = new String[]{"rundll32", "url.dll,FileProtocolHandler", url.toString()}; if (System.getProperty("os.name").startsWith("Windows 2000")) { command = new String[]{"rundll32", "shell32.dll,ShellExec_RunDLL", url.toString()}; } } else if (url.toString().startsWith("mailto:")) { command = new String[]{"rundll32", "url.dll,FileProtocolHandler", url.toString()}; } else { Runtime.getRuntime().exec(browserCommand); return; } Runtime.getRuntime().exec(command); } catch (final IOException x) { UITools .errorMessage("Could not invoke browser.\n\nFreeplane excecuted the following statement on a command line:\n\"" + command + "\".\n\nYou may look at the user or default property called '" + propertyString + "'."); System.err.println("Caught: " + x); } } else if (osName.startsWith("Mac OS")) { String browserCommand = null; try { String correctedUrl = url.toExternalForm(); if (url.getProtocol().equals("file")) { correctedUrl = correctedUrl.replace('\\', '/').replaceAll(" ", "%20"); } final Object[] messageArguments = { correctedUrl, url.toString() }; final MessageFormat formatter = new MessageFormat(ResourceController.getResourceController() .getProperty("default_browser_command_mac")); browserCommand = formatter.format(messageArguments); Runtime.getRuntime().exec(browserCommand); } catch (final IOException ex2) { UITools .errorMessage("Could not invoke browser.\n\nFreeplane excecuted the following statement on a command line:\n\"" + browserCommand + "\".\n\nYou may look at the user or default property called 'default_browser_command_mac'."); System.err.println("Caught: " + ex2); } } else { String browserCommand = null; try { String correctedUrl = url.toExternalForm(); if (url.getProtocol().equals("file")) { correctedUrl = correctedUrl.replace('\\', '/').replaceAll(" ", "%20"); } final Object[] messageArguments = { correctedUrl, url.toString() }; final MessageFormat formatter = new MessageFormat(ResourceController.getResourceController() .getProperty("default_browser_command_other_os")); browserCommand = formatter.format(messageArguments); Runtime.getRuntime().exec(browserCommand); } catch (final IOException ex2) { UITools .errorMessage("Could not invoke browser.\n\nFreeplane excecuted the following statement on a command line:\n\"" + browserCommand + "\".\n\nYou may look at the user or default property called 'default_browser_command_other_os'."); System.err.println("Caught: " + ex2); } } }
diff --git a/org.eclipse.help/src/org/eclipse/help/internal/xhtml/UAContentMergeProcessor.java b/org.eclipse.help/src/org/eclipse/help/internal/xhtml/UAContentMergeProcessor.java index 786531559..885847e21 100644 --- a/org.eclipse.help/src/org/eclipse/help/internal/xhtml/UAContentMergeProcessor.java +++ b/org.eclipse.help/src/org/eclipse/help/internal/xhtml/UAContentMergeProcessor.java @@ -1,294 +1,297 @@ /*************************************************************************************************** * Copyright (c) 2004, 2006 IBM Corporation and others. All rights reserved. This program and the * accompanying materials are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: IBM Corporation - initial API and implementation **************************************************************************************************/ package org.eclipse.help.internal.xhtml; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.help.internal.HelpPlugin; import org.eclipse.help.internal.util.ResourceLocator; import org.osgi.framework.Bundle; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Handles content manipulation to resolve includes. * */ public class UAContentMergeProcessor { protected static final String CONTENT_EXTENSION = "org.eclipse.help.contentExtension"; //$NON-NLS-1$ protected static IExtensionRegistry registry; protected static IConfigurationElement[] contentExtensionElements; static { registry = Platform.getExtensionRegistry(); contentExtensionElements = getContentExtensions(); } private Hashtable unresolvedConfigExt = new Hashtable(); private String pluginID = null; private String file = null; private Document document = null; private String locale = null; protected UAContentMergeProcessor(String pluginID, String file, Document document, String locale) { this.pluginID = pluginID; this.file = file; this.document = document; this.locale = locale; } public Document resolveIncludes() { NodeList includes = document.getElementsByTagNameNS("*", "include"); //$NON-NLS-1$ //$NON-NLS-2$ Node[] nodes = getArray(includes); for (int i = 0; i < nodes.length; i++) { Element includeElement = (Element) nodes[i]; UAInclude include = new UAInclude(includeElement); Element targetElement = findIncludeTarget(include); if (targetElement == null) { String message = "Could not resolve following include: "; //$NON-NLS-1$; HelpPlugin.logWarning(message); return null; } Node targetNode = document.importNode(targetElement, true); includeElement.getParentNode().replaceChild(targetNode, includeElement); } return document; } private Element findIncludeTarget(UAInclude include) { String path = include.getPath(); int index = path.indexOf("/"); //$NON-NLS-1$ if (index < 0) return null; String pluginID = path.substring(0, index); int lastIndex = path.lastIndexOf("/"); //$NON-NLS-1$ String pluginRelativePath = path.substring(index + 1, lastIndex); String include_id = path.substring(lastIndex + 1, path.length()); Bundle bundle = Platform.getBundle(pluginID); ArrayList pathPrefix = ResourceLocator.getPathPrefix(locale); - URL flatFileURL = ResourceLocator.find(bundle, new Path(pluginRelativePath), pathPrefix); - if (flatFileURL != null) - try { - InputStream inputStream = flatFileURL.openStream(); - UAContentParser parser = new UAContentParser(inputStream); - Document dom = parser.getDocument(); - return DOMUtil.getElementById(dom, include_id, "*"); //$NON-NLS-1$ - } catch (IOException e) { - return null; + if (bundle != null) { + URL flatFileURL = ResourceLocator.find(bundle, new Path(pluginRelativePath), pathPrefix); + if (flatFileURL != null) { + try { + InputStream inputStream = flatFileURL.openStream(); + UAContentParser parser = new UAContentParser(inputStream); + Document dom = parser.getDocument(); + return DOMUtil.getElementById(dom, include_id, "*"); //$NON-NLS-1$ + } catch (IOException e) { + return null; + } } + } return null; } public static Node[] getArray(NodeList nodeList) { Node[] nodes = new Node[nodeList.getLength()]; for (int i = 0; i < nodeList.getLength(); i++) nodes[i] = nodeList.item(i); return nodes; } protected static IConfigurationElement[] getContentExtensions() { IConfigurationElement[] contentExtensionElements = registry .getConfigurationElementsFor(CONTENT_EXTENSION); return contentExtensionElements; } public Document resolveContentExtensions() { for (int i = 0; i < contentExtensionElements.length; i++) resolveContentExtension(contentExtensionElements[i]); return document; } private void resolveContentExtension(IConfigurationElement contentExtElement) { Document contentExtensionDom = loadContentExtension(contentExtElement); if (contentExtensionDom == null) return; resolveContentExtension(contentExtensionDom, contentExtElement); } private void resolveContentExtension(Document contentExtensionDom, IConfigurationElement contentExtElement) { Bundle bundle = BundleUtil.getBundleFromConfigurationElement(contentExtElement); Element[] topicExtensions = DOMUtil.getElementsByTagName(contentExtensionDom, "topicExtension"); //$NON-NLS-1$ if (topicExtensions != null) { for (int i = 0; i < topicExtensions.length; i++) doResolveContentExtension(topicExtensions[i], bundle); } Element[] topicReplaces = DOMUtil.getElementsByTagName(contentExtensionDom, "topicReplace"); //$NON-NLS-1$ if (topicReplaces != null) { for (int i = 0; i < topicReplaces.length; i++) doResolveContentReplace(topicReplaces[i], bundle); } } private void doResolveContentExtension(Element topicExtension, Bundle bundle) { UATopicExtension topicExtensionModel = new UATopicExtension(topicExtension, bundle); boolean isExtensionToCurrentPage = resolveTopicExtension(topicExtensionModel); if (isExtensionToCurrentPage) { if (topicExtension.hasAttribute("failed")) { //$NON-NLS-1$ if (!unresolvedConfigExt.containsKey(topicExtension)) unresolvedConfigExt.put(topicExtension, bundle); } else { unresolvedConfigExt.remove(topicExtension); tryResolvingExtensions(); } } } private void tryResolvingExtensions() { Enumeration keys = unresolvedConfigExt.keys(); while (keys.hasMoreElements()) { Element topicExtensionElement = (Element) keys.nextElement(); doResolveContentExtension(topicExtensionElement, (Bundle) unresolvedConfigExt .get(topicExtensionElement)); } } /** * Insert the topic extension content into the target page if the target page happens to be this * page. * * @param extensionContent * @return */ private boolean resolveTopicExtension(UATopicExtension topicExtension) { Element anchorElement = findAnchor(topicExtension, locale); if (anchorElement == null) { if (topicExtension.getElement().hasAttribute("failed")) //$NON-NLS-1$ return true; else return false; } Element[] elements = topicExtension.getElements(); for (int i = 0; i < elements.length; i++) { Node targetNode = document.importNode(elements[i], true); anchorElement.getParentNode().insertBefore(targetNode, anchorElement); } return true; } private Element findAnchor(UATopicExtension topicExtension, String locale) { String path = topicExtension.getPath(); int index = path.indexOf("/"); //$NON-NLS-1$ if (index < 0) return null; String pluginID = path.substring(0, index); int lastIndex = path.lastIndexOf("/"); //$NON-NLS-1$ String pluginRelativePath = path.substring(index + 1, lastIndex); String anchor_id = path.substring(lastIndex + 1, path.length()); if (this.pluginID.equals(pluginID) && this.file.equals(pluginRelativePath)) { Element anchor = DOMUtil.getElementById(document, anchor_id, "*"); //$NON-NLS-1$ if (anchor == null) topicExtension.getElement().setAttribute("failed", "true"); //$NON-NLS-1$ //$NON-NLS-2$ return anchor; } return null; } protected Document loadContentExtension(IConfigurationElement cfgElement) { String content = cfgElement.getAttribute("file"); //$NON-NLS-1$ content = BundleUtil.getResourceLocation(content, cfgElement); Document document = new UAContentParser(content).getDocument(); return document; } private void doResolveContentReplace(Element topicReplace, Bundle bundle) { UATopicExtension topicReplaceModel = new UATopicExtension(topicReplace, bundle); boolean isExtensionToCurrentPage = resolveTopicReplace(topicReplaceModel); if (isExtensionToCurrentPage) { if (topicReplace.hasAttribute("failed")) { //$NON-NLS-1$ if (!unresolvedConfigExt.containsKey(topicReplace)) unresolvedConfigExt.put(topicReplace, bundle); } else { unresolvedConfigExt.remove(topicReplace); // tryResolvingExtensions(); } } } private boolean resolveTopicReplace(UATopicExtension topicReplace) { Element replaceElement = findReplaceElementById(topicReplace, locale); if (replaceElement == null) { if (topicReplace.getElement().hasAttribute("failed")) //$NON-NLS-1$ return true; else return false; } Element[] elements = topicReplace.getElements(); for (int i = 0; i < elements.length; i++) { Node targetNode = document.importNode(elements[i], true); replaceElement.getParentNode().insertBefore(targetNode, replaceElement); } replaceElement.getParentNode().removeChild(replaceElement); return true; } private Element findReplaceElementById(UATopicExtension topicReplace, String locale) { String path = topicReplace.getPath(); int index = path.indexOf("/"); //$NON-NLS-1$ if (index < 0) return null; String pluginID = path.substring(0, index); int lastIndex = path.lastIndexOf("/"); //$NON-NLS-1$ String pluginRelativePath = path.substring(index + 1, lastIndex); String element_id = path.substring(lastIndex + 1, path.length()); if (this.pluginID.equals(pluginID) && this.file.equals(pluginRelativePath)) { Element elementToReplace = DOMUtil.getElementById(document, element_id, "*"); //$NON-NLS-1$ if (elementToReplace == null) topicReplace.getElement().setAttribute("failed", "true"); //$NON-NLS-1$ //$NON-NLS-2$ return elementToReplace; } return null; } }
false
true
private Element findIncludeTarget(UAInclude include) { String path = include.getPath(); int index = path.indexOf("/"); //$NON-NLS-1$ if (index < 0) return null; String pluginID = path.substring(0, index); int lastIndex = path.lastIndexOf("/"); //$NON-NLS-1$ String pluginRelativePath = path.substring(index + 1, lastIndex); String include_id = path.substring(lastIndex + 1, path.length()); Bundle bundle = Platform.getBundle(pluginID); ArrayList pathPrefix = ResourceLocator.getPathPrefix(locale); URL flatFileURL = ResourceLocator.find(bundle, new Path(pluginRelativePath), pathPrefix); if (flatFileURL != null) try { InputStream inputStream = flatFileURL.openStream(); UAContentParser parser = new UAContentParser(inputStream); Document dom = parser.getDocument(); return DOMUtil.getElementById(dom, include_id, "*"); //$NON-NLS-1$ } catch (IOException e) { return null; } return null; }
private Element findIncludeTarget(UAInclude include) { String path = include.getPath(); int index = path.indexOf("/"); //$NON-NLS-1$ if (index < 0) return null; String pluginID = path.substring(0, index); int lastIndex = path.lastIndexOf("/"); //$NON-NLS-1$ String pluginRelativePath = path.substring(index + 1, lastIndex); String include_id = path.substring(lastIndex + 1, path.length()); Bundle bundle = Platform.getBundle(pluginID); ArrayList pathPrefix = ResourceLocator.getPathPrefix(locale); if (bundle != null) { URL flatFileURL = ResourceLocator.find(bundle, new Path(pluginRelativePath), pathPrefix); if (flatFileURL != null) { try { InputStream inputStream = flatFileURL.openStream(); UAContentParser parser = new UAContentParser(inputStream); Document dom = parser.getDocument(); return DOMUtil.getElementById(dom, include_id, "*"); //$NON-NLS-1$ } catch (IOException e) { return null; } } } return null; }
diff --git a/common/com/pahimar/ee3/core/handlers/TransmutationTargetOverlayHandler.java b/common/com/pahimar/ee3/core/handlers/TransmutationTargetOverlayHandler.java index 11afbf0e..9498f1e9 100644 --- a/common/com/pahimar/ee3/core/handlers/TransmutationTargetOverlayHandler.java +++ b/common/com/pahimar/ee3/core/handlers/TransmutationTargetOverlayHandler.java @@ -1,149 +1,149 @@ package com.pahimar.ee3.core.handlers; import java.util.EnumSet; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import com.pahimar.ee3.client.renderer.RenderUtils; import com.pahimar.ee3.configuration.ConfigurationSettings; import com.pahimar.ee3.core.util.TransmutationHelper; import com.pahimar.ee3.item.ITransmutationStone; import com.pahimar.ee3.lib.Reference; import cpw.mods.fml.client.FMLClientHandler; import cpw.mods.fml.common.ITickHandler; import cpw.mods.fml.common.TickType; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /** * Equivalent-Exchange-3 * * TransmutationTargetOverlayHandler * * @author pahimar * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) * */ @SideOnly(Side.CLIENT) public class TransmutationTargetOverlayHandler implements ITickHandler { @Override public void tickStart(EnumSet<TickType> type, Object... tickData) { } @Override public void tickEnd(EnumSet<TickType> type, Object... tickData) { Minecraft minecraft = FMLClientHandler.instance().getClient(); EntityPlayer player = minecraft.thePlayer; ItemStack currentItemStack = null; if (type.contains(TickType.RENDER)) { if (player != null) { currentItemStack = player.inventory.getCurrentItem(); if (Minecraft.isGuiEnabled() && minecraft.inGameHasFocus) { if (currentItemStack != null && currentItemStack.getItem() instanceof ITransmutationStone && ConfigurationSettings.ENABLE_OVERLAY_WORLD_TRANSMUTATION) { renderStoneHUD(minecraft, player, currentItemStack, (Float) tickData[0]); } } } } } @Override public EnumSet<TickType> ticks() { return EnumSet.of(TickType.CLIENT, TickType.RENDER); } @Override public String getLabel() { return Reference.MOD_NAME + ": " + this.getClass().getSimpleName(); } private static void renderStoneHUD(Minecraft minecraft, EntityPlayer player, ItemStack stack, float partialTicks) { float overlayScale = ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE; float blockScale = overlayScale / 2; float overlayOpacity = ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY; GL11.glPushMatrix(); ScaledResolution sr = new ScaledResolution(minecraft.gameSettings, minecraft.displayWidth, minecraft.displayHeight); - GL11.glClear(256); + GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, sr.getScaledWidth_double(), sr.getScaledHeight_double(), 0.0D, 1000.0D, 3000.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -2000.0F); GL11.glPushMatrix(); RenderHelper.enableGUIStandardItemLighting(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_COLOR_MATERIAL); GL11.glEnable(GL11.GL_LIGHTING); int hudOverlayX = 0; int hudOverlayY = 0; int hudBlockX = 0; int hudBlockY = 0; switch (ConfigurationSettings.TARGET_BLOCK_OVERLAY_POSITION) { case 0: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 1: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 2: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } case 3: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } default: { break; } } RenderUtils.renderItemIntoGUI(minecraft.fontRenderer, stack, hudOverlayX, hudOverlayY, overlayOpacity, overlayScale); if (TransmutationHelper.targetBlockStack != null && TransmutationHelper.targetBlockStack.getItem() instanceof ItemBlock) { RenderUtils.renderRotatingBlockIntoGUI(minecraft.fontRenderer, TransmutationHelper.targetBlockStack, hudBlockX, hudBlockY, -90, blockScale); } GL11.glDisable(GL11.GL_LIGHTING); GL11.glPopMatrix(); GL11.glPopMatrix(); } }
true
true
private static void renderStoneHUD(Minecraft minecraft, EntityPlayer player, ItemStack stack, float partialTicks) { float overlayScale = ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE; float blockScale = overlayScale / 2; float overlayOpacity = ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY; GL11.glPushMatrix(); ScaledResolution sr = new ScaledResolution(minecraft.gameSettings, minecraft.displayWidth, minecraft.displayHeight); GL11.glClear(256); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, sr.getScaledWidth_double(), sr.getScaledHeight_double(), 0.0D, 1000.0D, 3000.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -2000.0F); GL11.glPushMatrix(); RenderHelper.enableGUIStandardItemLighting(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_COLOR_MATERIAL); GL11.glEnable(GL11.GL_LIGHTING); int hudOverlayX = 0; int hudOverlayY = 0; int hudBlockX = 0; int hudBlockY = 0; switch (ConfigurationSettings.TARGET_BLOCK_OVERLAY_POSITION) { case 0: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 1: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 2: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } case 3: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } default: { break; } } RenderUtils.renderItemIntoGUI(minecraft.fontRenderer, stack, hudOverlayX, hudOverlayY, overlayOpacity, overlayScale); if (TransmutationHelper.targetBlockStack != null && TransmutationHelper.targetBlockStack.getItem() instanceof ItemBlock) { RenderUtils.renderRotatingBlockIntoGUI(minecraft.fontRenderer, TransmutationHelper.targetBlockStack, hudBlockX, hudBlockY, -90, blockScale); } GL11.glDisable(GL11.GL_LIGHTING); GL11.glPopMatrix(); GL11.glPopMatrix(); }
private static void renderStoneHUD(Minecraft minecraft, EntityPlayer player, ItemStack stack, float partialTicks) { float overlayScale = ConfigurationSettings.TARGET_BLOCK_OVERLAY_SCALE; float blockScale = overlayScale / 2; float overlayOpacity = ConfigurationSettings.TARGET_BLOCK_OVERLAY_OPACITY; GL11.glPushMatrix(); ScaledResolution sr = new ScaledResolution(minecraft.gameSettings, minecraft.displayWidth, minecraft.displayHeight); GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); GL11.glOrtho(0.0D, sr.getScaledWidth_double(), sr.getScaledHeight_double(), 0.0D, 1000.0D, 3000.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -2000.0F); GL11.glPushMatrix(); RenderHelper.enableGUIStandardItemLighting(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glEnable(GL11.GL_COLOR_MATERIAL); GL11.glEnable(GL11.GL_LIGHTING); int hudOverlayX = 0; int hudOverlayY = 0; int hudBlockX = 0; int hudBlockY = 0; switch (ConfigurationSettings.TARGET_BLOCK_OVERLAY_POSITION) { case 0: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 1: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = 0; hudBlockY = (int) (16 * overlayScale / 2 - 8); break; } case 2: { hudOverlayX = 0; hudBlockX = (int) (16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } case 3: { hudOverlayX = (int) (sr.getScaledWidth() - 16 * overlayScale); hudBlockX = (int) (sr.getScaledWidth() - 16 * overlayScale / 2 - 8); hudOverlayY = (int) (sr.getScaledHeight() - 16 * overlayScale); hudBlockY = (int) (sr.getScaledHeight() - 16 * overlayScale / 2 - 8); break; } default: { break; } } RenderUtils.renderItemIntoGUI(minecraft.fontRenderer, stack, hudOverlayX, hudOverlayY, overlayOpacity, overlayScale); if (TransmutationHelper.targetBlockStack != null && TransmutationHelper.targetBlockStack.getItem() instanceof ItemBlock) { RenderUtils.renderRotatingBlockIntoGUI(minecraft.fontRenderer, TransmutationHelper.targetBlockStack, hudBlockX, hudBlockY, -90, blockScale); } GL11.glDisable(GL11.GL_LIGHTING); GL11.glPopMatrix(); GL11.glPopMatrix(); }
diff --git a/src/main/java/com/syncthemall/enml4j/impl/DefaultTodoTagConverter.java b/src/main/java/com/syncthemall/enml4j/impl/DefaultTodoTagConverter.java index e7c5095..d85c903 100644 --- a/src/main/java/com/syncthemall/enml4j/impl/DefaultTodoTagConverter.java +++ b/src/main/java/com/syncthemall/enml4j/impl/DefaultTodoTagConverter.java @@ -1,101 +1,102 @@ /** * The MIT License * * Copyright (c) 2013 Pierre-Denis Vanduynslager * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.syncthemall.enml4j.impl; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Characters; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; import com.evernote.edam.type.Note; import com.syncthemall.enml4j.converter.BaseConverter; import com.syncthemall.enml4j.converter.Converter; import com.syncthemall.enml4j.util.Elements; /** * Default {@code Converter} implementation to convert {@code <en-todo>} ENML tags. * <p> * This {@link Converter} will replace an {@code <en-todo>} tag with an {@code <input type="checkbox"></input>} HTML tag. <br> * The {@code <input type="checkbox">} will be checked if the {@code <en-todo>} tag is. * <p> * * For example : {@code <en-todo checked="true"></en-todo>}<br> * will be replaced by :<br> * {@code <input type="checkbox" checked=""></input>} * * @see <a href="http://en.wikipedia.org/wiki/Data_URI_scheme">Data_URI_scheme</a> * @see <a href="http://dev.evernote.com/start/core/enml.php">Understanding the Evernote Markup Language</a> * @see <a href="http://docs.oracle.com/javaee/5/tutorial/doc/bnbdv.html">Streaming API for XML</a> */ public class DefaultTodoTagConverter extends BaseConverter { /** * Replace an {@code <en-todo>} tag by an {@code <input type="checkbox"></input>} tag. */ public final Elements convertElement(final StartElement start, final Note note) { List<Attribute> attrs = new ArrayList<Attribute>(); attrs.add(getEventFactory().createAttribute("type", "checkbox")); - if (start.getAttributeByName(new QName("checked")).getValue().equalsIgnoreCase("true")) { + Attribute checkedAttr = start.getAttributeByName(new QName("checked")); + if (checkedAttr != null && Boolean.parseBoolean(checkedAttr.getValue())) { attrs.add(getEventFactory().createAttribute("checked", "")); } return new Elements(getEventFactory().createStartElement(start.getName().getPrefix(), start.getName().getNamespaceURI(), "input", attrs.iterator(), start.getNamespaces()), getEventFactory() .createEndElement("", "", "type")); } /** * This {@code Converter} does not add any tag after the {@code <input></input>} tag created. */ public final List<XMLEvent> insertAfter(final StartElement start, final Note note) { return null; } /** * This {@code Converter} does not add any tag before the {@code <input></input>} tag created. */ public final List<XMLEvent> insertBefore(final StartElement start, final Note note) { return null; } /** * This {@code Converter} does not insert any tag in the {@code <input></input>} tag created. */ public final List<XMLEvent> insertIn(final StartElement start, final Note note) { return null; } /** * This {@code Converter} does not replace text in the {@code <input></input>} tag created. */ public final Characters convertCharacter(final Characters characters, final StartElement start, final Note note) { return characters; } }
true
true
public final Elements convertElement(final StartElement start, final Note note) { List<Attribute> attrs = new ArrayList<Attribute>(); attrs.add(getEventFactory().createAttribute("type", "checkbox")); if (start.getAttributeByName(new QName("checked")).getValue().equalsIgnoreCase("true")) { attrs.add(getEventFactory().createAttribute("checked", "")); } return new Elements(getEventFactory().createStartElement(start.getName().getPrefix(), start.getName().getNamespaceURI(), "input", attrs.iterator(), start.getNamespaces()), getEventFactory() .createEndElement("", "", "type")); }
public final Elements convertElement(final StartElement start, final Note note) { List<Attribute> attrs = new ArrayList<Attribute>(); attrs.add(getEventFactory().createAttribute("type", "checkbox")); Attribute checkedAttr = start.getAttributeByName(new QName("checked")); if (checkedAttr != null && Boolean.parseBoolean(checkedAttr.getValue())) { attrs.add(getEventFactory().createAttribute("checked", "")); } return new Elements(getEventFactory().createStartElement(start.getName().getPrefix(), start.getName().getNamespaceURI(), "input", attrs.iterator(), start.getNamespaces()), getEventFactory() .createEndElement("", "", "type")); }
diff --git a/tapestry-framework/src/java/org/apache/tapestry/components/Any.java b/tapestry-framework/src/java/org/apache/tapestry/components/Any.java index cf4645b92..2915e5e22 100644 --- a/tapestry-framework/src/java/org/apache/tapestry/components/Any.java +++ b/tapestry-framework/src/java/org/apache/tapestry/components/Any.java @@ -1,63 +1,63 @@ // Copyright 2004, 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.tapestry.components; import org.apache.hivemind.ApplicationRuntimeException; import org.apache.tapestry.AbstractComponent; import org.apache.tapestry.IMarkupWriter; import org.apache.tapestry.IRequestCycle; /** * A component that can substitute for any HTML element. [<a * href="../../../../../ComponentReference/Any.html">Component Reference</a>] * * @author Howard Lewis Ship */ public abstract class Any extends AbstractComponent { protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle) { String element = getElement(); if (element == null) throw new ApplicationRuntimeException(ComponentMessages.anyElementNotDefined(), this, null, null); boolean rewinding = cycle.isRewinding(); if (!rewinding) { - if (getBodyCount() > 0) + if (getBodyCount() > 0 || "script".equals(element)) writer.begin(element); else writer.beginEmpty(element); renderInformalParameters(writer, cycle); if (getId() != null && !isParameterBound("id")) renderIdAttribute(writer, cycle); } renderBody(writer, cycle); - if (!rewinding && getBodyCount() > 0) + if (!rewinding && (getBodyCount() > 0 || "script".equals(element))) { writer.end(); } } public abstract String getElement(); }
false
true
protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle) { String element = getElement(); if (element == null) throw new ApplicationRuntimeException(ComponentMessages.anyElementNotDefined(), this, null, null); boolean rewinding = cycle.isRewinding(); if (!rewinding) { if (getBodyCount() > 0) writer.begin(element); else writer.beginEmpty(element); renderInformalParameters(writer, cycle); if (getId() != null && !isParameterBound("id")) renderIdAttribute(writer, cycle); } renderBody(writer, cycle); if (!rewinding && getBodyCount() > 0) { writer.end(); } }
protected void renderComponent(IMarkupWriter writer, IRequestCycle cycle) { String element = getElement(); if (element == null) throw new ApplicationRuntimeException(ComponentMessages.anyElementNotDefined(), this, null, null); boolean rewinding = cycle.isRewinding(); if (!rewinding) { if (getBodyCount() > 0 || "script".equals(element)) writer.begin(element); else writer.beginEmpty(element); renderInformalParameters(writer, cycle); if (getId() != null && !isParameterBound("id")) renderIdAttribute(writer, cycle); } renderBody(writer, cycle); if (!rewinding && (getBodyCount() > 0 || "script".equals(element))) { writer.end(); } }
diff --git a/nuxeo-connect-standalone/src/main/java/org/nuxeo/connect/update/xml/XmlSerializer.java b/nuxeo-connect-standalone/src/main/java/org/nuxeo/connect/update/xml/XmlSerializer.java index 2eeb8937..b0d13717 100644 --- a/nuxeo-connect-standalone/src/main/java/org/nuxeo/connect/update/xml/XmlSerializer.java +++ b/nuxeo-connect-standalone/src/main/java/org/nuxeo/connect/update/xml/XmlSerializer.java @@ -1,194 +1,191 @@ /* * (C) Copyright 2006-2012 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * bstefanescu, mguillaume, jcarsique */ package org.nuxeo.connect.update.xml; import org.nuxeo.connect.update.PackageDependency; import org.nuxeo.connect.update.model.Field; import org.nuxeo.connect.update.model.Form; import org.nuxeo.connect.update.model.PackageDefinition; /** * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> */ public class XmlSerializer extends XmlWriter { public XmlSerializer() { } public XmlSerializer(String tab) { super(tab); } public String toXML(PackageDefinition def) { start("package"); if (def.getType() != null) { attr("type", def.getType().getValue()); } try { - def.getClass().getMethod( - "org.nuxeo.connect.update.model.PackageDefinition.getVisibility"); + def.getClass().getMethod("getVisibility"); if (def.getVisibility() != null) { attr("visibility", def.getVisibility().toString()); } } catch (NoSuchMethodException e) { // Ignore visibility with old Connect Client versions } attr("name", def.getName()); if (def.getVersion() != null) { attr("version", def.getVersion().toString()); } startContent(); element("title", def.getTitle()); element("description", def.getDescription()); element("vendor", def.getVendor()); element("classifier", def.getClassifier()); element("home-page", def.getHomePage()); element("hotreload-support", Boolean.valueOf(def.supportsHotReload()).toString()); element("supported", Boolean.valueOf(def.isSupported()).toString()); element("require-terms-and-conditions-acceptance", Boolean.valueOf(def.requireTermsAndConditionsAcceptance()).toString()); element("production-state", def.getProductionState().toString()); element("nuxeo-validation", def.getValidationState().toString()); if (def.getInstaller() != null) { start("installer"); attr("class", def.getInstaller().getType()); attr("restart", String.valueOf(def.getInstaller().getRequireRestart())); end(); } if (def.getUninstaller() != null) { start("uninstaller"); attr("class", def.getUninstaller().getType()); attr("restart", String.valueOf(def.getUninstaller().getRequireRestart())); end(); } element("validator", def.getValidator()); if (def.getPlatforms() != null && def.getPlatforms().length > 0) { start("platforms"); startContent(); for (String platform : def.getPlatforms()) { element("platform", platform); } end("platforms"); } if (def.getDependencies() != null && def.getDependencies().length > 0) { start("dependencies"); startContent(); for (PackageDependency dep : def.getDependencies()) { element("package", dep.toString()); } end("dependencies"); } try { - def.getClass().getMethod( - "org.nuxeo.connect.update.model.PackageDefinition.getConflicts"); + def.getClass().getMethod("getConflicts"); if (def.getConflicts() != null && def.getConflicts().length > 0) { start("conflicts"); startContent(); for (PackageDependency conflict : def.getConflicts()) { element("package", conflict.toString()); } end("conflicts"); } } catch (NoSuchMethodException e) { // Ignore conflicts with old Connect Client versions } try { - def.getClass().getMethod( - "org.nuxeo.connect.update.model.PackageDefinition.getProvides"); + def.getClass().getMethod("getProvides"); if (def.getProvides() != null && def.getProvides().length > 0) { start("provides"); startContent(); for (PackageDependency provide : def.getProvides()) { element("package", provide.toString()); } end("provides"); } } catch (NoSuchMethodException e) { // Ignore provides with old Connect Client versions } end("package"); return sb.toString(); } public void buildXML(Form form) { start("form"); startContent(); element("title", form.getTitle()); element("image", form.getImage()); element("description", form.getDescription()); if (form.getFields() != null && form.getFields().length > 0) { start("fields"); startContent(); for (Field field : form.getFields()) { start("field"); attr("name", field.getName()); attr("type", field.getType()); if (field.isRequired()) { attr("required", "true"); } if (field.isReadOnly()) { attr("readonly", "true"); } if (field.isVertical()) { attr("vertical", "true"); } startContent(); element("label", field.getLabel()); element("value", field.getValue()); end("field"); } end("fields"); } end("form"); } public String toXML(FormDefinition form) { buildXML(form); return sb.toString(); } public String toXML(FormDefinition... forms) { start("forms"); startContent(); for (FormDefinition form : forms) { buildXML(form); } end("forms"); return sb.toString(); } public String toXML(FormsDefinition forms) { start("forms"); startContent(); for (Form form : forms.getForms()) { buildXML(form); } end("forms"); return sb.toString(); } }
false
true
public String toXML(PackageDefinition def) { start("package"); if (def.getType() != null) { attr("type", def.getType().getValue()); } try { def.getClass().getMethod( "org.nuxeo.connect.update.model.PackageDefinition.getVisibility"); if (def.getVisibility() != null) { attr("visibility", def.getVisibility().toString()); } } catch (NoSuchMethodException e) { // Ignore visibility with old Connect Client versions } attr("name", def.getName()); if (def.getVersion() != null) { attr("version", def.getVersion().toString()); } startContent(); element("title", def.getTitle()); element("description", def.getDescription()); element("vendor", def.getVendor()); element("classifier", def.getClassifier()); element("home-page", def.getHomePage()); element("hotreload-support", Boolean.valueOf(def.supportsHotReload()).toString()); element("supported", Boolean.valueOf(def.isSupported()).toString()); element("require-terms-and-conditions-acceptance", Boolean.valueOf(def.requireTermsAndConditionsAcceptance()).toString()); element("production-state", def.getProductionState().toString()); element("nuxeo-validation", def.getValidationState().toString()); if (def.getInstaller() != null) { start("installer"); attr("class", def.getInstaller().getType()); attr("restart", String.valueOf(def.getInstaller().getRequireRestart())); end(); } if (def.getUninstaller() != null) { start("uninstaller"); attr("class", def.getUninstaller().getType()); attr("restart", String.valueOf(def.getUninstaller().getRequireRestart())); end(); } element("validator", def.getValidator()); if (def.getPlatforms() != null && def.getPlatforms().length > 0) { start("platforms"); startContent(); for (String platform : def.getPlatforms()) { element("platform", platform); } end("platforms"); } if (def.getDependencies() != null && def.getDependencies().length > 0) { start("dependencies"); startContent(); for (PackageDependency dep : def.getDependencies()) { element("package", dep.toString()); } end("dependencies"); } try { def.getClass().getMethod( "org.nuxeo.connect.update.model.PackageDefinition.getConflicts"); if (def.getConflicts() != null && def.getConflicts().length > 0) { start("conflicts"); startContent(); for (PackageDependency conflict : def.getConflicts()) { element("package", conflict.toString()); } end("conflicts"); } } catch (NoSuchMethodException e) { // Ignore conflicts with old Connect Client versions } try { def.getClass().getMethod( "org.nuxeo.connect.update.model.PackageDefinition.getProvides"); if (def.getProvides() != null && def.getProvides().length > 0) { start("provides"); startContent(); for (PackageDependency provide : def.getProvides()) { element("package", provide.toString()); } end("provides"); } } catch (NoSuchMethodException e) { // Ignore provides with old Connect Client versions } end("package"); return sb.toString(); }
public String toXML(PackageDefinition def) { start("package"); if (def.getType() != null) { attr("type", def.getType().getValue()); } try { def.getClass().getMethod("getVisibility"); if (def.getVisibility() != null) { attr("visibility", def.getVisibility().toString()); } } catch (NoSuchMethodException e) { // Ignore visibility with old Connect Client versions } attr("name", def.getName()); if (def.getVersion() != null) { attr("version", def.getVersion().toString()); } startContent(); element("title", def.getTitle()); element("description", def.getDescription()); element("vendor", def.getVendor()); element("classifier", def.getClassifier()); element("home-page", def.getHomePage()); element("hotreload-support", Boolean.valueOf(def.supportsHotReload()).toString()); element("supported", Boolean.valueOf(def.isSupported()).toString()); element("require-terms-and-conditions-acceptance", Boolean.valueOf(def.requireTermsAndConditionsAcceptance()).toString()); element("production-state", def.getProductionState().toString()); element("nuxeo-validation", def.getValidationState().toString()); if (def.getInstaller() != null) { start("installer"); attr("class", def.getInstaller().getType()); attr("restart", String.valueOf(def.getInstaller().getRequireRestart())); end(); } if (def.getUninstaller() != null) { start("uninstaller"); attr("class", def.getUninstaller().getType()); attr("restart", String.valueOf(def.getUninstaller().getRequireRestart())); end(); } element("validator", def.getValidator()); if (def.getPlatforms() != null && def.getPlatforms().length > 0) { start("platforms"); startContent(); for (String platform : def.getPlatforms()) { element("platform", platform); } end("platforms"); } if (def.getDependencies() != null && def.getDependencies().length > 0) { start("dependencies"); startContent(); for (PackageDependency dep : def.getDependencies()) { element("package", dep.toString()); } end("dependencies"); } try { def.getClass().getMethod("getConflicts"); if (def.getConflicts() != null && def.getConflicts().length > 0) { start("conflicts"); startContent(); for (PackageDependency conflict : def.getConflicts()) { element("package", conflict.toString()); } end("conflicts"); } } catch (NoSuchMethodException e) { // Ignore conflicts with old Connect Client versions } try { def.getClass().getMethod("getProvides"); if (def.getProvides() != null && def.getProvides().length > 0) { start("provides"); startContent(); for (PackageDependency provide : def.getProvides()) { element("package", provide.toString()); } end("provides"); } } catch (NoSuchMethodException e) { // Ignore provides with old Connect Client versions } end("package"); return sb.toString(); }
diff --git a/src/cytoscape/visual/CalculatorCatalogFactory.java b/src/cytoscape/visual/CalculatorCatalogFactory.java index adba90047..26a41ef2e 100644 --- a/src/cytoscape/visual/CalculatorCatalogFactory.java +++ b/src/cytoscape/visual/CalculatorCatalogFactory.java @@ -1,163 +1,161 @@ /** Copyright (c) 2002 Institute for Systems Biology and the Whitehead Institute ** ** This library is free software; you can redistribute it and/or modify it ** under the terms of the GNU Lesser General Public License as published ** by the Free Software Foundation; either version 2.1 of the License, or ** any later version. ** ** This library is distributed in the hope that it will be useful, but ** WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF ** MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and ** documentation provided hereunder is on an "as is" basis, and the ** Institute for Systems Biology and the Whitehead Institute ** have no obligations to provide maintenance, support, ** updates, enhancements or modifications. In no event shall the ** Institute for Systems Biology and the Whitehead Institute ** be liable to any party for direct, indirect, special, ** incidental or consequential damages, including lost profits, arising ** out of the use of this software and its documentation, even if the ** Institute for Systems Biology and the Whitehead Institute ** have been advised of the possibility of such damage. See ** the GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this library; if not, write to the Free Software Foundation, ** Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. **/ //---------------------------------------------------------------------------- // $Revision$ // $Date$ // $Author$ //---------------------------------------------------------------------------- package cytoscape.visual; import java.util.Properties; import java.io.*; import java.beans.*; import cytoscape.Cytoscape; import cytoscape.CytoscapeInit; import cytoscape.visual.calculators.NodeLabelCalculator; import cytoscape.visual.calculators.GenericNodeLabelCalculator; import cytoscape.visual.mappings.*; /** * This class provides a static method for reading a CalculatorCatalog object * from file, using parameters specified in a supplied CytoscapeConfig. * What's provided here is the set of files from which to read the calculator * information, as well as the construction of a suitable default visual style * if one does not already exist. */ public abstract class CalculatorCatalogFactory { static File propertiesFile; static Properties vizmapProps; /** * Loads a CalculatorCatalog object from the various properties files * specified by the options in the supplied CytoscapeConfig object. * The catalog will be properly initialized with known mapping types * and a default visual style (named "default"). */ public static CalculatorCatalog loadCalculatorCatalog () { final CalculatorCatalog calculatorCatalog = new CalculatorCatalog(); // register mappings calculatorCatalog.addMapping("Discrete Mapper", DiscreteMapping.class); calculatorCatalog.addMapping("Continuous Mapper", ContinuousMapping.class); calculatorCatalog.addMapping("Passthrough Mapper", PassThroughMapping.class); //load in calculators from file //we look for, in order, a file in CYTOSCAPE_HOME, one in the current directory, //then one in the user's home directory. Note that this is a different order than //for cytoscape.props, because we always write vizmaps to the home directory boolean propsFound = false; vizmapProps = new Properties(); //2. Try the current working directory if ( !propsFound ) { try { File file = new File( System.getProperty ("user.dir"), "vizmap.props" ); vizmapProps.load( new FileInputStream( file ) ); propertiesFile = file; System.out.println( "vizmaps found at: "+propertiesFile ); propsFound = true; } catch ( Exception e ) { - e.printStackTrace(); propsFound = false; } } //3. Try VIZMAP_HOME if ( !propsFound ) { try { File file = new File( System.getProperty ("CYTOSCAPE_HOME"), "vizmap.props" ); vizmapProps.load( new FileInputStream( file ) ); propertiesFile = file; System.out.println( "vizmaps found at: "+propertiesFile ); propsFound = true; } catch ( Exception e ) { // error propsFound = false; } } //4. Try ~/.vizmap if ( !propsFound ) { try { File file = CytoscapeInit.getConfigFile( "vizmap.props" ); vizmapProps.load( new FileInputStream( file ) ); propertiesFile = file; System.out.println( "vizmaps found at: "+propertiesFile ); propsFound = true; } catch ( Exception e ) { // error - e.printStackTrace(); propsFound = false; } } if ( vizmapProps == null ) { System.out.println( "vizmaps not found" ); vizmapProps = new Properties(); } //now load using the constructed Properties object CalculatorIO.loadCalculators( vizmapProps, calculatorCatalog); //make sure a default visual style exists, creating as needed //this must be done before loading the old-style visual mappings, //since that class works with the default visual style VisualStyle defaultVS = calculatorCatalog.getVisualStyle("default"); if (defaultVS == null) { defaultVS = new VisualStyle("default"); //setup the default to at least put canonical names on the nodes String cName = "Common Names"; NodeLabelCalculator nlc = calculatorCatalog.getNodeLabelCalculator(cName); if (nlc == null) { PassThroughMapping m = new PassThroughMapping(new String(), cytoscape.data.Semantics.COMMON_NAME); nlc = new GenericNodeLabelCalculator(cName, m); } defaultVS.getNodeAppearanceCalculator().setNodeLabelCalculator(nlc); calculatorCatalog.addVisualStyle(defaultVS); } Cytoscape.getSwingPropertyChangeSupport().addPropertyChangeListener ( new PropertyChangeListener () { public void propertyChange ( PropertyChangeEvent e ) { if ( e.getPropertyName() == Cytoscape.CYTOSCAPE_EXIT ) { System.out.println( "Save Vizmaps back to: "+propertiesFile ); CalculatorIO.storeCatalog( calculatorCatalog, propertiesFile ); } } } ); return calculatorCatalog; } }
false
true
public static CalculatorCatalog loadCalculatorCatalog () { final CalculatorCatalog calculatorCatalog = new CalculatorCatalog(); // register mappings calculatorCatalog.addMapping("Discrete Mapper", DiscreteMapping.class); calculatorCatalog.addMapping("Continuous Mapper", ContinuousMapping.class); calculatorCatalog.addMapping("Passthrough Mapper", PassThroughMapping.class); //load in calculators from file //we look for, in order, a file in CYTOSCAPE_HOME, one in the current directory, //then one in the user's home directory. Note that this is a different order than //for cytoscape.props, because we always write vizmaps to the home directory boolean propsFound = false; vizmapProps = new Properties(); //2. Try the current working directory if ( !propsFound ) { try { File file = new File( System.getProperty ("user.dir"), "vizmap.props" ); vizmapProps.load( new FileInputStream( file ) ); propertiesFile = file; System.out.println( "vizmaps found at: "+propertiesFile ); propsFound = true; } catch ( Exception e ) { e.printStackTrace(); propsFound = false; } } //3. Try VIZMAP_HOME if ( !propsFound ) { try { File file = new File( System.getProperty ("CYTOSCAPE_HOME"), "vizmap.props" ); vizmapProps.load( new FileInputStream( file ) ); propertiesFile = file; System.out.println( "vizmaps found at: "+propertiesFile ); propsFound = true; } catch ( Exception e ) { // error propsFound = false; } } //4. Try ~/.vizmap if ( !propsFound ) { try { File file = CytoscapeInit.getConfigFile( "vizmap.props" ); vizmapProps.load( new FileInputStream( file ) ); propertiesFile = file; System.out.println( "vizmaps found at: "+propertiesFile ); propsFound = true; } catch ( Exception e ) { // error e.printStackTrace(); propsFound = false; } } if ( vizmapProps == null ) { System.out.println( "vizmaps not found" ); vizmapProps = new Properties(); } //now load using the constructed Properties object CalculatorIO.loadCalculators( vizmapProps, calculatorCatalog); //make sure a default visual style exists, creating as needed //this must be done before loading the old-style visual mappings, //since that class works with the default visual style VisualStyle defaultVS = calculatorCatalog.getVisualStyle("default"); if (defaultVS == null) { defaultVS = new VisualStyle("default"); //setup the default to at least put canonical names on the nodes String cName = "Common Names"; NodeLabelCalculator nlc = calculatorCatalog.getNodeLabelCalculator(cName); if (nlc == null) { PassThroughMapping m = new PassThroughMapping(new String(), cytoscape.data.Semantics.COMMON_NAME); nlc = new GenericNodeLabelCalculator(cName, m); } defaultVS.getNodeAppearanceCalculator().setNodeLabelCalculator(nlc); calculatorCatalog.addVisualStyle(defaultVS); } Cytoscape.getSwingPropertyChangeSupport().addPropertyChangeListener ( new PropertyChangeListener () { public void propertyChange ( PropertyChangeEvent e ) { if ( e.getPropertyName() == Cytoscape.CYTOSCAPE_EXIT ) { System.out.println( "Save Vizmaps back to: "+propertiesFile ); CalculatorIO.storeCatalog( calculatorCatalog, propertiesFile ); } } } ); return calculatorCatalog; }
public static CalculatorCatalog loadCalculatorCatalog () { final CalculatorCatalog calculatorCatalog = new CalculatorCatalog(); // register mappings calculatorCatalog.addMapping("Discrete Mapper", DiscreteMapping.class); calculatorCatalog.addMapping("Continuous Mapper", ContinuousMapping.class); calculatorCatalog.addMapping("Passthrough Mapper", PassThroughMapping.class); //load in calculators from file //we look for, in order, a file in CYTOSCAPE_HOME, one in the current directory, //then one in the user's home directory. Note that this is a different order than //for cytoscape.props, because we always write vizmaps to the home directory boolean propsFound = false; vizmapProps = new Properties(); //2. Try the current working directory if ( !propsFound ) { try { File file = new File( System.getProperty ("user.dir"), "vizmap.props" ); vizmapProps.load( new FileInputStream( file ) ); propertiesFile = file; System.out.println( "vizmaps found at: "+propertiesFile ); propsFound = true; } catch ( Exception e ) { propsFound = false; } } //3. Try VIZMAP_HOME if ( !propsFound ) { try { File file = new File( System.getProperty ("CYTOSCAPE_HOME"), "vizmap.props" ); vizmapProps.load( new FileInputStream( file ) ); propertiesFile = file; System.out.println( "vizmaps found at: "+propertiesFile ); propsFound = true; } catch ( Exception e ) { // error propsFound = false; } } //4. Try ~/.vizmap if ( !propsFound ) { try { File file = CytoscapeInit.getConfigFile( "vizmap.props" ); vizmapProps.load( new FileInputStream( file ) ); propertiesFile = file; System.out.println( "vizmaps found at: "+propertiesFile ); propsFound = true; } catch ( Exception e ) { // error propsFound = false; } } if ( vizmapProps == null ) { System.out.println( "vizmaps not found" ); vizmapProps = new Properties(); } //now load using the constructed Properties object CalculatorIO.loadCalculators( vizmapProps, calculatorCatalog); //make sure a default visual style exists, creating as needed //this must be done before loading the old-style visual mappings, //since that class works with the default visual style VisualStyle defaultVS = calculatorCatalog.getVisualStyle("default"); if (defaultVS == null) { defaultVS = new VisualStyle("default"); //setup the default to at least put canonical names on the nodes String cName = "Common Names"; NodeLabelCalculator nlc = calculatorCatalog.getNodeLabelCalculator(cName); if (nlc == null) { PassThroughMapping m = new PassThroughMapping(new String(), cytoscape.data.Semantics.COMMON_NAME); nlc = new GenericNodeLabelCalculator(cName, m); } defaultVS.getNodeAppearanceCalculator().setNodeLabelCalculator(nlc); calculatorCatalog.addVisualStyle(defaultVS); } Cytoscape.getSwingPropertyChangeSupport().addPropertyChangeListener ( new PropertyChangeListener () { public void propertyChange ( PropertyChangeEvent e ) { if ( e.getPropertyName() == Cytoscape.CYTOSCAPE_EXIT ) { System.out.println( "Save Vizmaps back to: "+propertiesFile ); CalculatorIO.storeCatalog( calculatorCatalog, propertiesFile ); } } } ); return calculatorCatalog; }
diff --git a/src/framework/utils/ApplicationInstaller.java b/src/framework/utils/ApplicationInstaller.java index 9b66e08e..bb3f6493 100644 --- a/src/framework/utils/ApplicationInstaller.java +++ b/src/framework/utils/ApplicationInstaller.java @@ -1,64 +1,64 @@ package framework.utils; import junit.framework.Assert; import test.cli.cloudify.CommandTestUtils; public class ApplicationInstaller extends RecipeInstaller { private static final int DEFAULT_INSTALL_APPLICATION_TIMEOUT = 30; private String applicationName; public ApplicationInstaller(String restUrl, String applicationName) { super(restUrl, DEFAULT_INSTALL_APPLICATION_TIMEOUT); this.applicationName = applicationName; } @Override public String getInstallCommand() { return "install-application"; } @Override public void assertInstall(String output) { final String excpectedResult = "Application " + applicationName + " installed successfully"; if (!isExpectToFail()) { AssertUtils.assertTrue(output.toLowerCase().contains(excpectedResult.toLowerCase())); } else { AssertUtils.assertTrue(output.toLowerCase().contains("operation failed")); } } @Override public String getUninstallCommand() { return "uninstall-application"; } @Override public String getRecipeName() { return applicationName; } @Override public void assertUninstall(String output) { final String excpectedResult = "Application " + applicationName + " uninstalled successfully"; AssertUtils.assertTrue(output.toLowerCase().contains(excpectedResult.toLowerCase())); } public void uninstallIfFound() { if (getRestUrl() != null) { - String command = "connect " + getRestUrl() + ";list-services"; + String command = "connect " + getRestUrl() + ";list-application"; String output; try { output = CommandTestUtils.runCommandAndWait(command); if (output.contains(applicationName)) { uninstall(); } } catch (final Exception e) { LogUtils.log(e.getMessage(), e); Assert.fail(e.getMessage()); } } } }
true
true
public void uninstallIfFound() { if (getRestUrl() != null) { String command = "connect " + getRestUrl() + ";list-services"; String output; try { output = CommandTestUtils.runCommandAndWait(command); if (output.contains(applicationName)) { uninstall(); } } catch (final Exception e) { LogUtils.log(e.getMessage(), e); Assert.fail(e.getMessage()); } } }
public void uninstallIfFound() { if (getRestUrl() != null) { String command = "connect " + getRestUrl() + ";list-application"; String output; try { output = CommandTestUtils.runCommandAndWait(command); if (output.contains(applicationName)) { uninstall(); } } catch (final Exception e) { LogUtils.log(e.getMessage(), e); Assert.fail(e.getMessage()); } } }
diff --git a/src/com/orange/groupbuy/api/service/GroupBuyServiceFactory.java b/src/com/orange/groupbuy/api/service/GroupBuyServiceFactory.java index 9affb3f..f49671d 100644 --- a/src/com/orange/groupbuy/api/service/GroupBuyServiceFactory.java +++ b/src/com/orange/groupbuy/api/service/GroupBuyServiceFactory.java @@ -1,128 +1,128 @@ package com.orange.groupbuy.api.service; import com.orange.common.api.service.CommonService; import com.orange.common.api.service.CommonServiceFactory; import com.orange.groupbuy.api.service.category.GetAllCategoryService; import com.orange.groupbuy.api.service.category.GetShoppingCategoryService; import com.orange.groupbuy.api.service.product.CompareProductService; import com.orange.groupbuy.api.service.product.SegmentService; import com.orange.groupbuy.api.service.user.AddUserShoppingItemService; import com.orange.groupbuy.api.service.user.BindUserService; import com.orange.groupbuy.api.service.user.CountShoppingItemProductsByUser; import com.orange.groupbuy.api.service.user.DeleteUserShoppingItemService; import com.orange.groupbuy.api.service.user.GetUserShoppingItemListService; import com.orange.groupbuy.api.service.user.UpdateUserShoppingItemService; import com.orange.groupbuy.constant.ServiceConstant; public class GroupBuyServiceFactory extends CommonServiceFactory { @Override public CommonService createServiceObjectByMethod(String method) { if (method == null){ return new VerifyUserService(); } if (method.equalsIgnoreCase(ServiceConstant.METHOD_REGISTERDEVICE)){ return new RegisterDeviceService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_DEVICELOGIN)){ return new DeviceLoginService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATE_SUBSCRIPTION)){ return new UpdateSubscriptionService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHPRICE)) { return new FindAllProductsWithPrice(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHREBATE)) { return new FindAllProductsWithRebate(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHBOUGHT)) { return new FindAllProductsWithBought(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHLOCATION)) { return new FindAllProductsWithLocation(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETAPPUPDATE)) { return new AppUpdateService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSGROUPBYCATEGORY)) { return new FindAllProductGroupByCategory(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_SEARCHPRODUCT)) { return new SearchService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTS)) { return new FindProductService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATEKEYWORD)) { return new UpdateKeywordService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_REGISTERUSER)) { return new RegisterUserService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_LOGIN)) { return new LoginUserService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATEUSER)) { return new UpdateUserService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_ADDSHOPPINGITEM)) { return new AddUserShoppingItemService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATESHOPPINGITEM)) { return new UpdateUserShoppingItemService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_DELETESHOPPINGITEM)) { return new DeleteUserShoppingItemService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_ACTIONONPRODUCT)) { return new ActionOnProductService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_WRITEPRODUCTCOMMENT)) { return new WriteCommentService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETPRODUCTCOMMENTS)) { return new GetCommentsService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_DELETESOLRINDEX)) { return new DeleteSolrIndexService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTBYSCORE)) { return new FindProductByTopScoreService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETALLCATEGORY)) { return new GetAllCategoryService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETSHOPPINGCATEGORY)) { return new GetShoppingCategoryService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTBYSHOPPINGITEM)) { return new FindProductByShoppingItemService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_GETUSERSHOPPINGITEMLIST)) { return new GetUserShoppingItemListService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_COUNTSHOPPINGITEMPRODUCTS)) { return new CountShoppingItemProductsByUser(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_BIND_USER_SERVICE)){ return new BindUserService(); } - else if (method.equalsIgnoreCase(ServiceConstant.METHOD_SEGMENTSERVICE)) { + else if (method.equalsIgnoreCase(ServiceConstant.METHOD_SEGMENTTEXT)) { return new SegmentService(); } - else if (method.equalsIgnoreCase(ServiceConstant.METHOD_COMPAREPRODUCT_SERVICE)) { + else if (method.equalsIgnoreCase(ServiceConstant.METHOD_COMPAREPRODUCT)) { return new CompareProductService(); } else return null; } }
false
true
public CommonService createServiceObjectByMethod(String method) { if (method == null){ return new VerifyUserService(); } if (method.equalsIgnoreCase(ServiceConstant.METHOD_REGISTERDEVICE)){ return new RegisterDeviceService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_DEVICELOGIN)){ return new DeviceLoginService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATE_SUBSCRIPTION)){ return new UpdateSubscriptionService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHPRICE)) { return new FindAllProductsWithPrice(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHREBATE)) { return new FindAllProductsWithRebate(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHBOUGHT)) { return new FindAllProductsWithBought(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHLOCATION)) { return new FindAllProductsWithLocation(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETAPPUPDATE)) { return new AppUpdateService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSGROUPBYCATEGORY)) { return new FindAllProductGroupByCategory(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_SEARCHPRODUCT)) { return new SearchService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTS)) { return new FindProductService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATEKEYWORD)) { return new UpdateKeywordService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_REGISTERUSER)) { return new RegisterUserService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_LOGIN)) { return new LoginUserService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATEUSER)) { return new UpdateUserService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_ADDSHOPPINGITEM)) { return new AddUserShoppingItemService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATESHOPPINGITEM)) { return new UpdateUserShoppingItemService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_DELETESHOPPINGITEM)) { return new DeleteUserShoppingItemService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_ACTIONONPRODUCT)) { return new ActionOnProductService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_WRITEPRODUCTCOMMENT)) { return new WriteCommentService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETPRODUCTCOMMENTS)) { return new GetCommentsService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_DELETESOLRINDEX)) { return new DeleteSolrIndexService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTBYSCORE)) { return new FindProductByTopScoreService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETALLCATEGORY)) { return new GetAllCategoryService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETSHOPPINGCATEGORY)) { return new GetShoppingCategoryService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTBYSHOPPINGITEM)) { return new FindProductByShoppingItemService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_GETUSERSHOPPINGITEMLIST)) { return new GetUserShoppingItemListService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_COUNTSHOPPINGITEMPRODUCTS)) { return new CountShoppingItemProductsByUser(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_BIND_USER_SERVICE)){ return new BindUserService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_SEGMENTSERVICE)) { return new SegmentService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_COMPAREPRODUCT_SERVICE)) { return new CompareProductService(); } else return null; }
public CommonService createServiceObjectByMethod(String method) { if (method == null){ return new VerifyUserService(); } if (method.equalsIgnoreCase(ServiceConstant.METHOD_REGISTERDEVICE)){ return new RegisterDeviceService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_DEVICELOGIN)){ return new DeviceLoginService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATE_SUBSCRIPTION)){ return new UpdateSubscriptionService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHPRICE)) { return new FindAllProductsWithPrice(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHREBATE)) { return new FindAllProductsWithRebate(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHBOUGHT)) { return new FindAllProductsWithBought(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSWITHLOCATION)) { return new FindAllProductsWithLocation(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETAPPUPDATE)) { return new AppUpdateService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTSGROUPBYCATEGORY)) { return new FindAllProductGroupByCategory(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_SEARCHPRODUCT)) { return new SearchService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTS)) { return new FindProductService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATEKEYWORD)) { return new UpdateKeywordService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_REGISTERUSER)) { return new RegisterUserService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_LOGIN)) { return new LoginUserService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATEUSER)) { return new UpdateUserService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_ADDSHOPPINGITEM)) { return new AddUserShoppingItemService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_UPDATESHOPPINGITEM)) { return new UpdateUserShoppingItemService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_DELETESHOPPINGITEM)) { return new DeleteUserShoppingItemService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_ACTIONONPRODUCT)) { return new ActionOnProductService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_WRITEPRODUCTCOMMENT)) { return new WriteCommentService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETPRODUCTCOMMENTS)) { return new GetCommentsService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_DELETESOLRINDEX)) { return new DeleteSolrIndexService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTBYSCORE)) { return new FindProductByTopScoreService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETALLCATEGORY)) { return new GetAllCategoryService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_GETSHOPPINGCATEGORY)) { return new GetShoppingCategoryService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_FINDPRODUCTBYSHOPPINGITEM)) { return new FindProductByShoppingItemService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_GETUSERSHOPPINGITEMLIST)) { return new GetUserShoppingItemListService(); } else if(method.equalsIgnoreCase(ServiceConstant.METHOD_COUNTSHOPPINGITEMPRODUCTS)) { return new CountShoppingItemProductsByUser(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_BIND_USER_SERVICE)){ return new BindUserService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_SEGMENTTEXT)) { return new SegmentService(); } else if (method.equalsIgnoreCase(ServiceConstant.METHOD_COMPAREPRODUCT)) { return new CompareProductService(); } else return null; }
diff --git a/app/models/Tag.java b/app/models/Tag.java index 1897061..97196c1 100644 --- a/app/models/Tag.java +++ b/app/models/Tag.java @@ -1,63 +1,64 @@ package models; import java.util.*; import play.db.ebean.*; import play.data.validation.Constraints.*; import play.data.format.Formats.*; import javax.persistence.*; import java.util.regex.PatternSyntaxException; @Table(uniqueConstraints=@UniqueConstraint(columnNames={"title"})) @Entity public class Tag extends Model { @Id public Long id; @Required @NonEmpty @MinLength(3) @MaxLength(40) public String title; public Tag(String title) { this.title = title; } public static Finder<Long, Tag> find = new Finder(Long.class, Tag.class); public static List<Tag> all() { return find.all(); } public static Tag create(Tag tag) { tag.save(); return tag; } public static List<Tag> createOrFindAllFromString(String list) { List<Tag> tags = new ArrayList<Tag>(); String[] tagArray = new String[]{list}; try { tagArray = list.split("\\s+"); } catch (PatternSyntaxException ex) { // TODO } for(String title : tagArray) { Tag tag = findByTitle(title) == null ? create(new Tag(title)) : findByTitle(title); - tags.add(findByTitle(title)); + if(!tags.contains(findByTitle(title))) + tags.add(findByTitle(title)); } return tags; } public static void delete(Long id) { find.ref(id).delete(); } public static Tag findByTitle(String title) { return find.where().eq("title", title).findUnique(); } }
true
true
public static List<Tag> createOrFindAllFromString(String list) { List<Tag> tags = new ArrayList<Tag>(); String[] tagArray = new String[]{list}; try { tagArray = list.split("\\s+"); } catch (PatternSyntaxException ex) { // TODO } for(String title : tagArray) { Tag tag = findByTitle(title) == null ? create(new Tag(title)) : findByTitle(title); tags.add(findByTitle(title)); } return tags; }
public static List<Tag> createOrFindAllFromString(String list) { List<Tag> tags = new ArrayList<Tag>(); String[] tagArray = new String[]{list}; try { tagArray = list.split("\\s+"); } catch (PatternSyntaxException ex) { // TODO } for(String title : tagArray) { Tag tag = findByTitle(title) == null ? create(new Tag(title)) : findByTitle(title); if(!tags.contains(findByTitle(title))) tags.add(findByTitle(title)); } return tags; }
diff --git a/src/java/org/apache/cassandra/cql/QueryProcessor.java b/src/java/org/apache/cassandra/cql/QueryProcessor.java index 71142cd0a..28ee3534c 100644 --- a/src/java/org/apache/cassandra/cql/QueryProcessor.java +++ b/src/java/org/apache/cassandra/cql/QueryProcessor.java @@ -1,1018 +1,1018 @@ /* * * 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.cassandra.cql; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeoutException; import org.apache.cassandra.auth.Permission; import org.apache.cassandra.concurrent.Stage; import org.apache.cassandra.concurrent.StageManager; import org.apache.cassandra.config.*; import org.apache.cassandra.cli.CliUtils; import org.apache.cassandra.db.CounterColumn; import org.apache.cassandra.db.*; import org.apache.cassandra.db.context.CounterContext; import org.apache.cassandra.db.filter.QueryPath; import org.apache.cassandra.db.marshal.AbstractType; import org.apache.cassandra.db.marshal.AsciiType; import org.apache.cassandra.db.marshal.MarshalException; import org.apache.cassandra.db.marshal.TypeParser; import org.apache.cassandra.dht.*; import org.apache.cassandra.service.ClientState; import org.apache.cassandra.service.StorageProxy; import org.apache.cassandra.service.StorageService; import org.apache.cassandra.service.MigrationManager; import org.apache.cassandra.thrift.*; import org.apache.cassandra.thrift.Column; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.Pair; import org.apache.cassandra.utils.SemanticVersion; import com.google.common.base.Predicates; import com.google.common.collect.Maps; import org.antlr.runtime.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.cassandra.thrift.ThriftValidation.validateColumnFamily; public class QueryProcessor { public static final SemanticVersion CQL_VERSION = new SemanticVersion("2.0.0"); private static final Logger logger = LoggerFactory.getLogger(QueryProcessor.class); private static final long timeLimitForSchemaAgreement = 10 * 1000; public static final String DEFAULT_KEY_NAME = bufferToString(CFMetaData.DEFAULT_KEY_NAME); private static List<org.apache.cassandra.db.Row> getSlice(CFMetaData metadata, SelectStatement select, List<ByteBuffer> variables) throws InvalidRequestException, TimedOutException, UnavailableException { QueryPath queryPath = new QueryPath(select.getColumnFamily()); List<ReadCommand> commands = new ArrayList<ReadCommand>(); // ...of a list of column names if (!select.isColumnRange()) { Collection<ByteBuffer> columnNames = getColumnNames(select, metadata, variables); validateColumnNames(columnNames); for (Term rawKey: select.getKeys()) { ByteBuffer key = rawKey.getByteBuffer(metadata.getKeyValidator(),variables); validateKey(key); commands.add(new SliceByNamesReadCommand(metadata.ksName, key, queryPath, columnNames)); } } // ...a range (slice) of column names else { AbstractType<?> comparator = select.getComparator(metadata.ksName); ByteBuffer start = select.getColumnStart().getByteBuffer(comparator,variables); ByteBuffer finish = select.getColumnFinish().getByteBuffer(comparator,variables); for (Term rawKey : select.getKeys()) { ByteBuffer key = rawKey.getByteBuffer(metadata.getKeyValidator(),variables); validateKey(key); validateSliceRange(metadata, start, finish, select.isColumnsReversed()); commands.add(new SliceFromReadCommand(metadata.ksName, key, queryPath, start, finish, select.isColumnsReversed(), select.getColumnsLimit())); } } try { return StorageProxy.read(commands, select.getConsistencyLevel()); } catch (TimeoutException e) { throw new TimedOutException(); } catch (IOException e) { throw new RuntimeException(e); } } private static List<ByteBuffer> getColumnNames(SelectStatement select, CFMetaData metadata, List<ByteBuffer> variables) throws InvalidRequestException { String keyString = getKeyString(metadata); List<ByteBuffer> columnNames = new ArrayList<ByteBuffer>(); for (Term column : select.getColumnNames()) { // skip the key for the slice op; we'll add it to the resultset in extractThriftColumns if (!column.getText().equalsIgnoreCase(keyString)) columnNames.add(column.getByteBuffer(metadata.comparator,variables)); } return columnNames; } private static List<org.apache.cassandra.db.Row> multiRangeSlice(CFMetaData metadata, SelectStatement select, List<ByteBuffer> variables) throws TimedOutException, UnavailableException, InvalidRequestException { List<org.apache.cassandra.db.Row> rows; IPartitioner<?> p = StorageService.getPartitioner(); AbstractType<?> keyType = Schema.instance.getCFMetaData(metadata.ksName, select.getColumnFamily()).getKeyValidator(); ByteBuffer startKeyBytes = (select.getKeyStart() != null) ? select.getKeyStart().getByteBuffer(keyType,variables) : null; ByteBuffer finishKeyBytes = (select.getKeyFinish() != null) ? select.getKeyFinish().getByteBuffer(keyType,variables) : null; RowPosition startKey = RowPosition.forKey(startKeyBytes, p), finishKey = RowPosition.forKey(finishKeyBytes, p); if (startKey.compareTo(finishKey) > 0 && !finishKey.isMinimum(p)) { if (p instanceof RandomPartitioner) throw new InvalidRequestException("Start key sorts after end key. This is not allowed; you probably should not specify end key at all, under RandomPartitioner"); else throw new InvalidRequestException("Start key must sort before (or equal to) finish key in your partitioner!"); } AbstractBounds<RowPosition> bounds = new Bounds<RowPosition>(startKey, finishKey); // XXX: Our use of Thrift structs internally makes me Sad. :( SlicePredicate thriftSlicePredicate = slicePredicateFromSelect(select, metadata, variables); validateSlicePredicate(metadata, thriftSlicePredicate); List<IndexExpression> expressions = new ArrayList<IndexExpression>(); for (Relation columnRelation : select.getColumnRelations()) { // Left and right side of relational expression encoded according to comparator/validator. ByteBuffer entity = columnRelation.getEntity().getByteBuffer(metadata.comparator, variables); ByteBuffer value = columnRelation.getValue().getByteBuffer(select.getValueValidator(metadata.ksName, entity), variables); expressions.add(new IndexExpression(entity, IndexOperator.valueOf(columnRelation.operator().toString()), value)); } int limit = select.isKeyRange() && select.getKeyStart() != null ? select.getNumRecords() + 1 : select.getNumRecords(); try { rows = StorageProxy.getRangeSlice(new RangeSliceCommand(metadata.ksName, select.getColumnFamily(), null, thriftSlicePredicate, bounds, expressions, limit), select.getConsistencyLevel()); } catch (IOException e) { throw new RuntimeException(e); } catch (org.apache.cassandra.thrift.UnavailableException e) { throw new UnavailableException(); } catch (TimeoutException e) { throw new TimedOutException(); } // if start key was set and relation was "greater than" if (select.getKeyStart() != null && !select.includeStartKey() && !rows.isEmpty()) { if (rows.get(0).key.key.equals(startKeyBytes)) rows.remove(0); } // if finish key was set and relation was "less than" if (select.getKeyFinish() != null && !select.includeFinishKey() && !rows.isEmpty()) { int lastIndex = rows.size() - 1; if (rows.get(lastIndex).key.key.equals(finishKeyBytes)) rows.remove(lastIndex); } return rows.subList(0, select.getNumRecords() < rows.size() ? select.getNumRecords() : rows.size()); } private static void batchUpdate(ClientState clientState, List<UpdateStatement> updateStatements, ConsistencyLevel consistency, List<ByteBuffer> variables ) throws InvalidRequestException, UnavailableException, TimedOutException { String globalKeyspace = clientState.getKeyspace(); List<IMutation> rowMutations = new ArrayList<IMutation>(); List<String> cfamsSeen = new ArrayList<String>(); for (UpdateStatement update : updateStatements) { String keyspace = update.keyspace == null ? globalKeyspace : update.keyspace; // Avoid unnecessary authorizations. if (!(cfamsSeen.contains(update.getColumnFamily()))) { clientState.hasColumnFamilyAccess(keyspace, update.getColumnFamily(), Permission.WRITE); cfamsSeen.add(update.getColumnFamily()); } rowMutations.addAll(update.prepareRowMutations(keyspace, clientState, variables)); } for (IMutation mutation : rowMutations) { validateKey(mutation.key()); } try { StorageProxy.mutate(rowMutations, consistency); } catch (org.apache.cassandra.thrift.UnavailableException e) { throw new UnavailableException(); } catch (TimeoutException e) { throw new TimedOutException(); } } private static SlicePredicate slicePredicateFromSelect(SelectStatement select, CFMetaData metadata, List<ByteBuffer> variables) throws InvalidRequestException { SlicePredicate thriftSlicePredicate = new SlicePredicate(); if (select.isColumnRange() || select.getColumnNames().size() == 0) { SliceRange sliceRange = new SliceRange(); sliceRange.start = select.getColumnStart().getByteBuffer(metadata.comparator, variables); sliceRange.finish = select.getColumnFinish().getByteBuffer(metadata.comparator, variables); sliceRange.reversed = select.isColumnsReversed(); sliceRange.count = select.getColumnsLimit(); thriftSlicePredicate.slice_range = sliceRange; } else { thriftSlicePredicate.column_names = getColumnNames(select, metadata, variables); } return thriftSlicePredicate; } /* Test for SELECT-specific taboos */ private static void validateSelect(String keyspace, SelectStatement select, List<ByteBuffer> variables) throws InvalidRequestException { ThriftValidation.validateConsistencyLevel(keyspace, select.getConsistencyLevel(), RequestType.READ); // Finish key w/o start key (KEY < foo) if (!select.isKeyRange() && (select.getKeyFinish() != null)) throw new InvalidRequestException("Key range clauses must include a start key (i.e. KEY > term)"); // Key range and by-key(s) combined (KEY > foo AND KEY = bar) if (select.isKeyRange() && select.getKeys().size() > 0) throw new InvalidRequestException("You cannot combine key range and by-key clauses in a SELECT"); // Start and finish keys, *and* column relations (KEY > foo AND KEY < bar and name1 = value1). if (select.isKeyRange() && (select.getKeyFinish() != null) && (select.getColumnRelations().size() > 0)) throw new InvalidRequestException("You cannot combine key range and by-column clauses in a SELECT"); // Can't use more than one KEY = if (!select.isMultiKey() && select.getKeys().size() > 1) throw new InvalidRequestException("You cannot use more than one KEY = in a SELECT"); if (select.getColumnRelations().size() > 0) { AbstractType<?> comparator = select.getComparator(keyspace); Set<ByteBuffer> indexed = Table.open(keyspace).getColumnFamilyStore(select.getColumnFamily()).indexManager.getIndexedColumns(); for (Relation relation : select.getColumnRelations()) { if ((relation.operator() == RelationType.EQ) && indexed.contains(relation.getEntity().getByteBuffer(comparator, variables))) return; } throw new InvalidRequestException("No indexed columns present in by-columns clause with \"equals\" operator"); } } public static void validateKey(ByteBuffer key) throws InvalidRequestException { if (key == null || key.remaining() == 0) { throw new InvalidRequestException("Key may not be empty"); } // check that key can be handled by FBUtilities.writeShortByteArray if (key.remaining() > FBUtilities.MAX_UNSIGNED_SHORT) { throw new InvalidRequestException("Key length of " + key.remaining() + " is longer than maximum of " + FBUtilities.MAX_UNSIGNED_SHORT); } } public static void validateKeyAlias(CFMetaData cfm, String key) throws InvalidRequestException { assert key.toUpperCase().equals(key); // should always be uppercased by caller String realKeyAlias = bufferToString(cfm.getKeyName()).toUpperCase(); if (!realKeyAlias.equals(key)) throw new InvalidRequestException(String.format("Expected key '%s' to be present in WHERE clause for '%s'", realKeyAlias, cfm.cfName)); } private static void validateColumnNames(Iterable<ByteBuffer> columns) throws InvalidRequestException { for (ByteBuffer name : columns) { if (name.remaining() > IColumn.MAX_NAME_LENGTH) throw new InvalidRequestException(String.format("column name is too long (%s > %s)", name.remaining(), IColumn.MAX_NAME_LENGTH)); if (name.remaining() == 0) throw new InvalidRequestException("zero-length column name"); } } public static void validateColumnName(ByteBuffer column) throws InvalidRequestException { validateColumnNames(Arrays.asList(column)); } public static void validateColumn(CFMetaData metadata, ByteBuffer name, ByteBuffer value) throws InvalidRequestException { validateColumnName(name); AbstractType<?> validator = metadata.getValueValidator(name); try { if (validator != null) validator.validate(value); } catch (MarshalException me) { throw new InvalidRequestException(String.format("Invalid column value for column (name=%s); %s", ByteBufferUtil.bytesToHex(name), me.getMessage())); } } private static void validateSlicePredicate(CFMetaData metadata, SlicePredicate predicate) throws InvalidRequestException { if (predicate.slice_range != null) validateSliceRange(metadata, predicate.slice_range); else validateColumnNames(predicate.column_names); } private static void validateSliceRange(CFMetaData metadata, SliceRange range) throws InvalidRequestException { validateSliceRange(metadata, range.start, range.finish, range.reversed); } private static void validateSliceRange(CFMetaData metadata, ByteBuffer start, ByteBuffer finish, boolean reversed) throws InvalidRequestException { AbstractType<?> comparator = metadata.getComparatorFor(null); Comparator<ByteBuffer> orderedComparator = reversed ? comparator.reverseComparator: comparator; if (start.remaining() > 0 && finish.remaining() > 0 && orderedComparator.compare(start, finish) > 0) throw new InvalidRequestException("range finish must come after start in traversal order"); } // Copypasta from CassandraServer (where it is private). private static void validateSchemaAgreement() throws SchemaDisagreementException { if (describeSchemaVersions().size() > 1) throw new SchemaDisagreementException(); } private static Map<String, List<String>> describeSchemaVersions() { // unreachable hosts don't count towards disagreement return Maps.filterKeys(StorageProxy.describeSchemaVersions(), Predicates.not(Predicates.equalTo(StorageProxy.UNREACHABLE))); } public static CqlResult processStatement(CQLStatement statement,ClientState clientState, List<ByteBuffer> variables ) throws UnavailableException, InvalidRequestException, TimedOutException, SchemaDisagreementException { String keyspace = null; // Some statements won't have (or don't need) a keyspace (think USE, or CREATE). if (statement.type != StatementType.SELECT && StatementType.requiresKeyspace.contains(statement.type)) keyspace = clientState.getKeyspace(); CqlResult result = new CqlResult(); if (logger.isDebugEnabled()) logger.debug("CQL statement type: {}", statement.type.toString()); CFMetaData metadata; switch (statement.type) { case SELECT: SelectStatement select = (SelectStatement)statement.statement; final String oldKeyspace = clientState.getRawKeyspace(); if (select.isSetKeyspace()) { keyspace = CliUtils.unescapeSQLString(select.getKeyspace()); ThriftValidation.validateTable(keyspace); } else if (oldKeyspace == null) throw new InvalidRequestException("no keyspace has been specified"); else keyspace = oldKeyspace; clientState.hasColumnFamilyAccess(keyspace, select.getColumnFamily(), Permission.READ); metadata = validateColumnFamily(keyspace, select.getColumnFamily()); // need to do this in here because we need a CFMD.getKeyName() select.extractKeyAliasFromColumns(metadata); if (select.getKeys().size() > 0) validateKeyAlias(metadata, select.getKeyAlias()); validateSelect(keyspace, select, variables); List<org.apache.cassandra.db.Row> rows; // By-key if (!select.isKeyRange() && (select.getKeys().size() > 0)) { rows = getSlice(metadata, select, variables); } else { rows = multiRangeSlice(metadata, select, variables); } // count resultset is a single column named "count" result.type = CqlResultType.ROWS; if (select.isCountOperation()) { validateCountOperation(select); ByteBuffer countBytes = ByteBufferUtil.bytes("count"); result.schema = new CqlMetadata(Collections.<ByteBuffer, String>emptyMap(), Collections.<ByteBuffer, String>emptyMap(), "AsciiType", "LongType"); List<Column> columns = Collections.singletonList(new Column(countBytes).setValue(ByteBufferUtil.bytes((long) rows.size()))); result.rows = Collections.singletonList(new CqlRow(countBytes, columns)); return result; } // otherwise create resultset from query results result.schema = new CqlMetadata(new HashMap<ByteBuffer, String>(), new HashMap<ByteBuffer, String>(), TypeParser.getShortName(metadata.comparator), TypeParser.getShortName(metadata.getDefaultValidator())); List<CqlRow> cqlRows = new ArrayList<CqlRow>(); for (org.apache.cassandra.db.Row row : rows) { List<Column> thriftColumns = new ArrayList<Column>(); if (select.isColumnRange()) { if (select.isFullWildcard()) { // prepend key thriftColumns.add(new Column(metadata.getKeyName()).setValue(row.key.key).setTimestamp(-1)); result.schema.name_types.put(metadata.getKeyName(), TypeParser.getShortName(AsciiType.instance)); result.schema.value_types.put(metadata.getKeyName(), TypeParser.getShortName(metadata.getKeyValidator())); } // preserve comparator order if (row.cf != null) { for (IColumn c : row.cf.getSortedColumns()) { if (c.isMarkedForDelete()) continue; ColumnDefinition cd = metadata.getColumnDefinition(c.name()); if (cd != null) result.schema.value_types.put(c.name(), TypeParser.getShortName(cd.getValidator())); thriftColumns.add(thriftify(c)); } } } else { String keyString = getKeyString(metadata); // order columns in the order they were asked for for (Term term : select.getColumnNames()) { if (term.getText().equalsIgnoreCase(keyString)) { // preserve case of key as it was requested ByteBuffer requestedKey = ByteBufferUtil.bytes(term.getText()); thriftColumns.add(new Column(requestedKey).setValue(row.key.key).setTimestamp(-1)); result.schema.name_types.put(requestedKey, TypeParser.getShortName(AsciiType.instance)); result.schema.value_types.put(requestedKey, TypeParser.getShortName(metadata.getKeyValidator())); continue; } if (row.cf == null) continue; ByteBuffer name; try { name = term.getByteBuffer(metadata.comparator, variables); } catch (InvalidRequestException e) { throw new AssertionError(e); } ColumnDefinition cd = metadata.getColumnDefinition(name); if (cd != null) result.schema.value_types.put(name, TypeParser.getShortName(cd.getValidator())); IColumn c = row.cf.getColumn(name); if (c == null || c.isMarkedForDelete()) thriftColumns.add(new Column().setName(name)); else thriftColumns.add(thriftify(c)); } } // Create a new row, add the columns to it, and then add it to the list of rows CqlRow cqlRow = new CqlRow(); cqlRow.key = row.key.key; cqlRow.columns = thriftColumns; if (select.isColumnsReversed()) Collections.reverse(cqlRow.columns); cqlRows.add(cqlRow); } result.rows = cqlRows; return result; case INSERT: // insert uses UpdateStatement case UPDATE: UpdateStatement update = (UpdateStatement)statement.statement; ThriftValidation.validateConsistencyLevel(keyspace, update.getConsistencyLevel(), RequestType.WRITE); batchUpdate(clientState, Collections.singletonList(update), update.getConsistencyLevel(), variables); result.type = CqlResultType.VOID; return result; case BATCH: BatchStatement batch = (BatchStatement) statement.statement; ThriftValidation.validateConsistencyLevel(keyspace, batch.getConsistencyLevel(), RequestType.WRITE); if (batch.getTimeToLive() != 0) throw new InvalidRequestException("Global TTL on the BATCH statement is not supported."); for (AbstractModification up : batch.getStatements()) { if (up.isSetConsistencyLevel()) throw new InvalidRequestException( "Consistency level must be set on the BATCH, not individual statements"); if (batch.isSetTimestamp() && up.isSetTimestamp()) throw new InvalidRequestException( "Timestamp must be set either on BATCH or individual statements"); } - List<IMutation> mutations = batch.getMutations(keyspace, clientState); + List<IMutation> mutations = batch.getMutations(keyspace, clientState, variables); for (IMutation mutation : mutations) { validateKey(mutation.key()); } try { StorageProxy.mutate(mutations, batch.getConsistencyLevel()); } catch (org.apache.cassandra.thrift.UnavailableException e) { throw new UnavailableException(); } catch (TimeoutException e) { throw new TimedOutException(); } result.type = CqlResultType.VOID; return result; case USE: clientState.setKeyspace(CliUtils.unescapeSQLString((String) statement.statement)); result.type = CqlResultType.VOID; return result; case TRUNCATE: Pair<String, String> columnFamily = (Pair<String, String>)statement.statement; keyspace = columnFamily.left == null ? clientState.getKeyspace() : columnFamily.left; validateColumnFamily(keyspace, columnFamily.right); clientState.hasColumnFamilyAccess(keyspace, columnFamily.right, Permission.WRITE); try { StorageProxy.truncateBlocking(keyspace, columnFamily.right); } catch (TimeoutException e) { throw (UnavailableException) new UnavailableException().initCause(e); } catch (IOException e) { throw (UnavailableException) new UnavailableException().initCause(e); } result.type = CqlResultType.VOID; return result; case DELETE: DeleteStatement delete = (DeleteStatement)statement.statement; keyspace = delete.keyspace == null ? clientState.getKeyspace() : delete.keyspace; - List<IMutation> deletions = delete.prepareRowMutations(keyspace, clientState); + List<IMutation> deletions = delete.prepareRowMutations(keyspace, clientState, variables); for (IMutation deletion : deletions) { validateKey(deletion.key()); } try { StorageProxy.mutate(deletions, delete.getConsistencyLevel()); } catch (TimeoutException e) { throw new TimedOutException(); } result.type = CqlResultType.VOID; return result; case CREATE_KEYSPACE: CreateKeyspaceStatement create = (CreateKeyspaceStatement)statement.statement; create.validate(); ThriftValidation.validateKeyspaceNotSystem(create.getName()); clientState.hasKeyspaceSchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { KsDef ksd = new KsDef(create.getName(), create.getStrategyClass(), Collections.<CfDef>emptyList()) .setStrategy_options(create.getStrategyOptions()); ThriftValidation.validateKsDef(ksd); ThriftValidation.validateKeyspaceNotYetExisting(create.getName()); MigrationManager.announceNewKeyspace(KSMetaData.fromThrift(ksd)); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case CREATE_COLUMNFAMILY: CreateColumnFamilyStatement createCf = (CreateColumnFamilyStatement)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); CFMetaData cfmd = createCf.getCFMetaData(keyspace, variables); ThriftValidation.validateCfDef(cfmd.toThrift(), null); try { MigrationManager.announceNewColumnFamily(cfmd); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case CREATE_INDEX: CreateIndexStatement createIdx = (CreateIndexStatement)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); CFMetaData oldCfm = Schema.instance.getCFMetaData(keyspace, createIdx.getColumnFamily()); if (oldCfm == null) throw new InvalidRequestException("No such column family: " + createIdx.getColumnFamily()); boolean columnExists = false; ByteBuffer columnName = createIdx.getColumnName().getByteBuffer(); // mutating oldCfm directly would be bad, but mutating a Thrift copy is fine. This also // sets us up to use validateCfDef to check for index name collisions. CfDef cf_def = oldCfm.toThrift(); for (ColumnDef cd : cf_def.column_metadata) { if (cd.name.equals(columnName)) { if (cd.index_type != null) throw new InvalidRequestException("Index already exists"); if (logger.isDebugEnabled()) logger.debug("Updating column {} definition for index {}", oldCfm.comparator.getString(columnName), createIdx.getIndexName()); cd.setIndex_type(IndexType.KEYS); cd.setIndex_name(createIdx.getIndexName()); columnExists = true; break; } } if (!columnExists) throw new InvalidRequestException("No column definition found for column " + oldCfm.comparator.getString(columnName)); CFMetaData.addDefaultIndexNames(cf_def); ThriftValidation.validateCfDef(cf_def, oldCfm); try { MigrationManager.announceColumnFamilyUpdate(CFMetaData.fromThrift(cf_def)); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case DROP_INDEX: DropIndexStatement dropIdx = (DropIndexStatement)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceColumnFamilyUpdate(dropIdx.generateCFMetadataUpdate(clientState.getKeyspace())); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } catch (IOException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case DROP_KEYSPACE: String deleteKeyspace = (String)statement.statement; ThriftValidation.validateKeyspaceNotSystem(deleteKeyspace); clientState.hasKeyspaceSchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceKeyspaceDrop(deleteKeyspace); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case DROP_COLUMNFAMILY: String deleteColumnFamily = (String)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceColumnFamilyDrop(keyspace, deleteColumnFamily); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case ALTER_TABLE: AlterTableStatement alterTable = (AlterTableStatement) statement.statement; validateColumnFamily(keyspace, alterTable.columnFamily); clientState.hasColumnFamilyAccess(alterTable.columnFamily, Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceColumnFamilyUpdate(CFMetaData.fromThrift(alterTable.getCfDef(keyspace))); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; } return null; // We should never get here. } public static CqlResult process(String queryString, ClientState clientState) throws RecognitionException, UnavailableException, InvalidRequestException, TimedOutException, SchemaDisagreementException { logger.trace("CQL QUERY: {}", queryString); return processStatement(getStatement(queryString), clientState, new ArrayList<ByteBuffer>()); } public static CqlPreparedResult prepare(String queryString, ClientState clientState) throws RecognitionException, InvalidRequestException { logger.trace("CQL QUERY: {}", queryString); CQLStatement statement = getStatement(queryString); int statementId = makeStatementId(queryString); logger.trace("Discovered "+ statement.boundTerms + " bound variables."); clientState.getPrepared().put(statementId, statement); logger.trace(String.format("Stored prepared statement #%d with %d bind markers", statementId, statement.boundTerms)); return new CqlPreparedResult(statementId, statement.boundTerms); } public static CqlResult processPrepared(CQLStatement statement, ClientState clientState, List<ByteBuffer> variables) throws UnavailableException, InvalidRequestException, TimedOutException, SchemaDisagreementException { // Check to see if there are any bound variables to verify if (!(variables.isEmpty() && (statement.boundTerms == 0))) { if (variables.size() != statement.boundTerms) throw new InvalidRequestException(String.format("there were %d markers(?) in CQL but %d bound variables", statement.boundTerms, variables.size())); // at this point there is a match in count between markers and variables that is non-zero if (logger.isTraceEnabled()) for (int i = 0; i < variables.size(); i++) logger.trace("[{}] '{}'", i+1, variables.get(i)); } return processStatement(statement, clientState, variables); } private static final int makeStatementId(String cql) { // use the hash of the string till something better is provided return cql.hashCode(); } private static Column thriftify(IColumn c) { ByteBuffer value = (c instanceof CounterColumn) ? ByteBufferUtil.bytes(CounterContext.instance().total(c.value())) : c.value(); return new Column(c.name()).setValue(value).setTimestamp(c.timestamp()); } private static String getKeyString(CFMetaData metadata) { String keyString; try { keyString = ByteBufferUtil.string(metadata.getKeyName()); } catch (CharacterCodingException e) { throw new AssertionError(e); } return keyString; } private static CQLStatement getStatement(String queryStr) throws InvalidRequestException, RecognitionException { // Lexer and parser CharStream stream = new ANTLRStringStream(queryStr); CqlLexer lexer = new CqlLexer(stream); TokenStream tokenStream = new CommonTokenStream(lexer); CqlParser parser = new CqlParser(tokenStream); // Parse the query string to a statement instance CQLStatement statement = parser.query(); // The lexer and parser queue up any errors they may have encountered // along the way, if necessary, we turn them into exceptions here. lexer.throwLastRecognitionError(); parser.throwLastRecognitionError(); return statement; } private static void validateSchemaIsSettled() throws SchemaDisagreementException { long limit = System.currentTimeMillis() + timeLimitForSchemaAgreement; outer: while (limit - System.currentTimeMillis() >= 0) { String currentVersionId = Schema.instance.getVersion().toString(); for (String version : describeSchemaVersions().keySet()) { if (!version.equals(currentVersionId)) continue outer; } // schemas agree return; } throw new SchemaDisagreementException(); } private static void validateCountOperation(SelectStatement select) throws InvalidRequestException { if (select.isWildcard()) return; // valid count(*) if (!select.isColumnRange()) { List<Term> columnNames = select.getColumnNames(); String firstColumn = columnNames.get(0).getText(); if (columnNames.size() == 1 && (firstColumn.equals("*") || firstColumn.equals("1"))) return; // valid count(*) || count(1) } throw new InvalidRequestException("Only COUNT(*) and COUNT(1) operations are currently supported."); } private static String bufferToString(ByteBuffer string) { try { return ByteBufferUtil.string(string); } catch (CharacterCodingException e) { throw new RuntimeException(e.getMessage(), e); } } }
false
true
public static CqlResult processStatement(CQLStatement statement,ClientState clientState, List<ByteBuffer> variables ) throws UnavailableException, InvalidRequestException, TimedOutException, SchemaDisagreementException { String keyspace = null; // Some statements won't have (or don't need) a keyspace (think USE, or CREATE). if (statement.type != StatementType.SELECT && StatementType.requiresKeyspace.contains(statement.type)) keyspace = clientState.getKeyspace(); CqlResult result = new CqlResult(); if (logger.isDebugEnabled()) logger.debug("CQL statement type: {}", statement.type.toString()); CFMetaData metadata; switch (statement.type) { case SELECT: SelectStatement select = (SelectStatement)statement.statement; final String oldKeyspace = clientState.getRawKeyspace(); if (select.isSetKeyspace()) { keyspace = CliUtils.unescapeSQLString(select.getKeyspace()); ThriftValidation.validateTable(keyspace); } else if (oldKeyspace == null) throw new InvalidRequestException("no keyspace has been specified"); else keyspace = oldKeyspace; clientState.hasColumnFamilyAccess(keyspace, select.getColumnFamily(), Permission.READ); metadata = validateColumnFamily(keyspace, select.getColumnFamily()); // need to do this in here because we need a CFMD.getKeyName() select.extractKeyAliasFromColumns(metadata); if (select.getKeys().size() > 0) validateKeyAlias(metadata, select.getKeyAlias()); validateSelect(keyspace, select, variables); List<org.apache.cassandra.db.Row> rows; // By-key if (!select.isKeyRange() && (select.getKeys().size() > 0)) { rows = getSlice(metadata, select, variables); } else { rows = multiRangeSlice(metadata, select, variables); } // count resultset is a single column named "count" result.type = CqlResultType.ROWS; if (select.isCountOperation()) { validateCountOperation(select); ByteBuffer countBytes = ByteBufferUtil.bytes("count"); result.schema = new CqlMetadata(Collections.<ByteBuffer, String>emptyMap(), Collections.<ByteBuffer, String>emptyMap(), "AsciiType", "LongType"); List<Column> columns = Collections.singletonList(new Column(countBytes).setValue(ByteBufferUtil.bytes((long) rows.size()))); result.rows = Collections.singletonList(new CqlRow(countBytes, columns)); return result; } // otherwise create resultset from query results result.schema = new CqlMetadata(new HashMap<ByteBuffer, String>(), new HashMap<ByteBuffer, String>(), TypeParser.getShortName(metadata.comparator), TypeParser.getShortName(metadata.getDefaultValidator())); List<CqlRow> cqlRows = new ArrayList<CqlRow>(); for (org.apache.cassandra.db.Row row : rows) { List<Column> thriftColumns = new ArrayList<Column>(); if (select.isColumnRange()) { if (select.isFullWildcard()) { // prepend key thriftColumns.add(new Column(metadata.getKeyName()).setValue(row.key.key).setTimestamp(-1)); result.schema.name_types.put(metadata.getKeyName(), TypeParser.getShortName(AsciiType.instance)); result.schema.value_types.put(metadata.getKeyName(), TypeParser.getShortName(metadata.getKeyValidator())); } // preserve comparator order if (row.cf != null) { for (IColumn c : row.cf.getSortedColumns()) { if (c.isMarkedForDelete()) continue; ColumnDefinition cd = metadata.getColumnDefinition(c.name()); if (cd != null) result.schema.value_types.put(c.name(), TypeParser.getShortName(cd.getValidator())); thriftColumns.add(thriftify(c)); } } } else { String keyString = getKeyString(metadata); // order columns in the order they were asked for for (Term term : select.getColumnNames()) { if (term.getText().equalsIgnoreCase(keyString)) { // preserve case of key as it was requested ByteBuffer requestedKey = ByteBufferUtil.bytes(term.getText()); thriftColumns.add(new Column(requestedKey).setValue(row.key.key).setTimestamp(-1)); result.schema.name_types.put(requestedKey, TypeParser.getShortName(AsciiType.instance)); result.schema.value_types.put(requestedKey, TypeParser.getShortName(metadata.getKeyValidator())); continue; } if (row.cf == null) continue; ByteBuffer name; try { name = term.getByteBuffer(metadata.comparator, variables); } catch (InvalidRequestException e) { throw new AssertionError(e); } ColumnDefinition cd = metadata.getColumnDefinition(name); if (cd != null) result.schema.value_types.put(name, TypeParser.getShortName(cd.getValidator())); IColumn c = row.cf.getColumn(name); if (c == null || c.isMarkedForDelete()) thriftColumns.add(new Column().setName(name)); else thriftColumns.add(thriftify(c)); } } // Create a new row, add the columns to it, and then add it to the list of rows CqlRow cqlRow = new CqlRow(); cqlRow.key = row.key.key; cqlRow.columns = thriftColumns; if (select.isColumnsReversed()) Collections.reverse(cqlRow.columns); cqlRows.add(cqlRow); } result.rows = cqlRows; return result; case INSERT: // insert uses UpdateStatement case UPDATE: UpdateStatement update = (UpdateStatement)statement.statement; ThriftValidation.validateConsistencyLevel(keyspace, update.getConsistencyLevel(), RequestType.WRITE); batchUpdate(clientState, Collections.singletonList(update), update.getConsistencyLevel(), variables); result.type = CqlResultType.VOID; return result; case BATCH: BatchStatement batch = (BatchStatement) statement.statement; ThriftValidation.validateConsistencyLevel(keyspace, batch.getConsistencyLevel(), RequestType.WRITE); if (batch.getTimeToLive() != 0) throw new InvalidRequestException("Global TTL on the BATCH statement is not supported."); for (AbstractModification up : batch.getStatements()) { if (up.isSetConsistencyLevel()) throw new InvalidRequestException( "Consistency level must be set on the BATCH, not individual statements"); if (batch.isSetTimestamp() && up.isSetTimestamp()) throw new InvalidRequestException( "Timestamp must be set either on BATCH or individual statements"); } List<IMutation> mutations = batch.getMutations(keyspace, clientState); for (IMutation mutation : mutations) { validateKey(mutation.key()); } try { StorageProxy.mutate(mutations, batch.getConsistencyLevel()); } catch (org.apache.cassandra.thrift.UnavailableException e) { throw new UnavailableException(); } catch (TimeoutException e) { throw new TimedOutException(); } result.type = CqlResultType.VOID; return result; case USE: clientState.setKeyspace(CliUtils.unescapeSQLString((String) statement.statement)); result.type = CqlResultType.VOID; return result; case TRUNCATE: Pair<String, String> columnFamily = (Pair<String, String>)statement.statement; keyspace = columnFamily.left == null ? clientState.getKeyspace() : columnFamily.left; validateColumnFamily(keyspace, columnFamily.right); clientState.hasColumnFamilyAccess(keyspace, columnFamily.right, Permission.WRITE); try { StorageProxy.truncateBlocking(keyspace, columnFamily.right); } catch (TimeoutException e) { throw (UnavailableException) new UnavailableException().initCause(e); } catch (IOException e) { throw (UnavailableException) new UnavailableException().initCause(e); } result.type = CqlResultType.VOID; return result; case DELETE: DeleteStatement delete = (DeleteStatement)statement.statement; keyspace = delete.keyspace == null ? clientState.getKeyspace() : delete.keyspace; List<IMutation> deletions = delete.prepareRowMutations(keyspace, clientState); for (IMutation deletion : deletions) { validateKey(deletion.key()); } try { StorageProxy.mutate(deletions, delete.getConsistencyLevel()); } catch (TimeoutException e) { throw new TimedOutException(); } result.type = CqlResultType.VOID; return result; case CREATE_KEYSPACE: CreateKeyspaceStatement create = (CreateKeyspaceStatement)statement.statement; create.validate(); ThriftValidation.validateKeyspaceNotSystem(create.getName()); clientState.hasKeyspaceSchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { KsDef ksd = new KsDef(create.getName(), create.getStrategyClass(), Collections.<CfDef>emptyList()) .setStrategy_options(create.getStrategyOptions()); ThriftValidation.validateKsDef(ksd); ThriftValidation.validateKeyspaceNotYetExisting(create.getName()); MigrationManager.announceNewKeyspace(KSMetaData.fromThrift(ksd)); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case CREATE_COLUMNFAMILY: CreateColumnFamilyStatement createCf = (CreateColumnFamilyStatement)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); CFMetaData cfmd = createCf.getCFMetaData(keyspace, variables); ThriftValidation.validateCfDef(cfmd.toThrift(), null); try { MigrationManager.announceNewColumnFamily(cfmd); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case CREATE_INDEX: CreateIndexStatement createIdx = (CreateIndexStatement)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); CFMetaData oldCfm = Schema.instance.getCFMetaData(keyspace, createIdx.getColumnFamily()); if (oldCfm == null) throw new InvalidRequestException("No such column family: " + createIdx.getColumnFamily()); boolean columnExists = false; ByteBuffer columnName = createIdx.getColumnName().getByteBuffer(); // mutating oldCfm directly would be bad, but mutating a Thrift copy is fine. This also // sets us up to use validateCfDef to check for index name collisions. CfDef cf_def = oldCfm.toThrift(); for (ColumnDef cd : cf_def.column_metadata) { if (cd.name.equals(columnName)) { if (cd.index_type != null) throw new InvalidRequestException("Index already exists"); if (logger.isDebugEnabled()) logger.debug("Updating column {} definition for index {}", oldCfm.comparator.getString(columnName), createIdx.getIndexName()); cd.setIndex_type(IndexType.KEYS); cd.setIndex_name(createIdx.getIndexName()); columnExists = true; break; } } if (!columnExists) throw new InvalidRequestException("No column definition found for column " + oldCfm.comparator.getString(columnName)); CFMetaData.addDefaultIndexNames(cf_def); ThriftValidation.validateCfDef(cf_def, oldCfm); try { MigrationManager.announceColumnFamilyUpdate(CFMetaData.fromThrift(cf_def)); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case DROP_INDEX: DropIndexStatement dropIdx = (DropIndexStatement)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceColumnFamilyUpdate(dropIdx.generateCFMetadataUpdate(clientState.getKeyspace())); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } catch (IOException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case DROP_KEYSPACE: String deleteKeyspace = (String)statement.statement; ThriftValidation.validateKeyspaceNotSystem(deleteKeyspace); clientState.hasKeyspaceSchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceKeyspaceDrop(deleteKeyspace); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case DROP_COLUMNFAMILY: String deleteColumnFamily = (String)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceColumnFamilyDrop(keyspace, deleteColumnFamily); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case ALTER_TABLE: AlterTableStatement alterTable = (AlterTableStatement) statement.statement; validateColumnFamily(keyspace, alterTable.columnFamily); clientState.hasColumnFamilyAccess(alterTable.columnFamily, Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceColumnFamilyUpdate(CFMetaData.fromThrift(alterTable.getCfDef(keyspace))); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; } return null; // We should never get here. }
public static CqlResult processStatement(CQLStatement statement,ClientState clientState, List<ByteBuffer> variables ) throws UnavailableException, InvalidRequestException, TimedOutException, SchemaDisagreementException { String keyspace = null; // Some statements won't have (or don't need) a keyspace (think USE, or CREATE). if (statement.type != StatementType.SELECT && StatementType.requiresKeyspace.contains(statement.type)) keyspace = clientState.getKeyspace(); CqlResult result = new CqlResult(); if (logger.isDebugEnabled()) logger.debug("CQL statement type: {}", statement.type.toString()); CFMetaData metadata; switch (statement.type) { case SELECT: SelectStatement select = (SelectStatement)statement.statement; final String oldKeyspace = clientState.getRawKeyspace(); if (select.isSetKeyspace()) { keyspace = CliUtils.unescapeSQLString(select.getKeyspace()); ThriftValidation.validateTable(keyspace); } else if (oldKeyspace == null) throw new InvalidRequestException("no keyspace has been specified"); else keyspace = oldKeyspace; clientState.hasColumnFamilyAccess(keyspace, select.getColumnFamily(), Permission.READ); metadata = validateColumnFamily(keyspace, select.getColumnFamily()); // need to do this in here because we need a CFMD.getKeyName() select.extractKeyAliasFromColumns(metadata); if (select.getKeys().size() > 0) validateKeyAlias(metadata, select.getKeyAlias()); validateSelect(keyspace, select, variables); List<org.apache.cassandra.db.Row> rows; // By-key if (!select.isKeyRange() && (select.getKeys().size() > 0)) { rows = getSlice(metadata, select, variables); } else { rows = multiRangeSlice(metadata, select, variables); } // count resultset is a single column named "count" result.type = CqlResultType.ROWS; if (select.isCountOperation()) { validateCountOperation(select); ByteBuffer countBytes = ByteBufferUtil.bytes("count"); result.schema = new CqlMetadata(Collections.<ByteBuffer, String>emptyMap(), Collections.<ByteBuffer, String>emptyMap(), "AsciiType", "LongType"); List<Column> columns = Collections.singletonList(new Column(countBytes).setValue(ByteBufferUtil.bytes((long) rows.size()))); result.rows = Collections.singletonList(new CqlRow(countBytes, columns)); return result; } // otherwise create resultset from query results result.schema = new CqlMetadata(new HashMap<ByteBuffer, String>(), new HashMap<ByteBuffer, String>(), TypeParser.getShortName(metadata.comparator), TypeParser.getShortName(metadata.getDefaultValidator())); List<CqlRow> cqlRows = new ArrayList<CqlRow>(); for (org.apache.cassandra.db.Row row : rows) { List<Column> thriftColumns = new ArrayList<Column>(); if (select.isColumnRange()) { if (select.isFullWildcard()) { // prepend key thriftColumns.add(new Column(metadata.getKeyName()).setValue(row.key.key).setTimestamp(-1)); result.schema.name_types.put(metadata.getKeyName(), TypeParser.getShortName(AsciiType.instance)); result.schema.value_types.put(metadata.getKeyName(), TypeParser.getShortName(metadata.getKeyValidator())); } // preserve comparator order if (row.cf != null) { for (IColumn c : row.cf.getSortedColumns()) { if (c.isMarkedForDelete()) continue; ColumnDefinition cd = metadata.getColumnDefinition(c.name()); if (cd != null) result.schema.value_types.put(c.name(), TypeParser.getShortName(cd.getValidator())); thriftColumns.add(thriftify(c)); } } } else { String keyString = getKeyString(metadata); // order columns in the order they were asked for for (Term term : select.getColumnNames()) { if (term.getText().equalsIgnoreCase(keyString)) { // preserve case of key as it was requested ByteBuffer requestedKey = ByteBufferUtil.bytes(term.getText()); thriftColumns.add(new Column(requestedKey).setValue(row.key.key).setTimestamp(-1)); result.schema.name_types.put(requestedKey, TypeParser.getShortName(AsciiType.instance)); result.schema.value_types.put(requestedKey, TypeParser.getShortName(metadata.getKeyValidator())); continue; } if (row.cf == null) continue; ByteBuffer name; try { name = term.getByteBuffer(metadata.comparator, variables); } catch (InvalidRequestException e) { throw new AssertionError(e); } ColumnDefinition cd = metadata.getColumnDefinition(name); if (cd != null) result.schema.value_types.put(name, TypeParser.getShortName(cd.getValidator())); IColumn c = row.cf.getColumn(name); if (c == null || c.isMarkedForDelete()) thriftColumns.add(new Column().setName(name)); else thriftColumns.add(thriftify(c)); } } // Create a new row, add the columns to it, and then add it to the list of rows CqlRow cqlRow = new CqlRow(); cqlRow.key = row.key.key; cqlRow.columns = thriftColumns; if (select.isColumnsReversed()) Collections.reverse(cqlRow.columns); cqlRows.add(cqlRow); } result.rows = cqlRows; return result; case INSERT: // insert uses UpdateStatement case UPDATE: UpdateStatement update = (UpdateStatement)statement.statement; ThriftValidation.validateConsistencyLevel(keyspace, update.getConsistencyLevel(), RequestType.WRITE); batchUpdate(clientState, Collections.singletonList(update), update.getConsistencyLevel(), variables); result.type = CqlResultType.VOID; return result; case BATCH: BatchStatement batch = (BatchStatement) statement.statement; ThriftValidation.validateConsistencyLevel(keyspace, batch.getConsistencyLevel(), RequestType.WRITE); if (batch.getTimeToLive() != 0) throw new InvalidRequestException("Global TTL on the BATCH statement is not supported."); for (AbstractModification up : batch.getStatements()) { if (up.isSetConsistencyLevel()) throw new InvalidRequestException( "Consistency level must be set on the BATCH, not individual statements"); if (batch.isSetTimestamp() && up.isSetTimestamp()) throw new InvalidRequestException( "Timestamp must be set either on BATCH or individual statements"); } List<IMutation> mutations = batch.getMutations(keyspace, clientState, variables); for (IMutation mutation : mutations) { validateKey(mutation.key()); } try { StorageProxy.mutate(mutations, batch.getConsistencyLevel()); } catch (org.apache.cassandra.thrift.UnavailableException e) { throw new UnavailableException(); } catch (TimeoutException e) { throw new TimedOutException(); } result.type = CqlResultType.VOID; return result; case USE: clientState.setKeyspace(CliUtils.unescapeSQLString((String) statement.statement)); result.type = CqlResultType.VOID; return result; case TRUNCATE: Pair<String, String> columnFamily = (Pair<String, String>)statement.statement; keyspace = columnFamily.left == null ? clientState.getKeyspace() : columnFamily.left; validateColumnFamily(keyspace, columnFamily.right); clientState.hasColumnFamilyAccess(keyspace, columnFamily.right, Permission.WRITE); try { StorageProxy.truncateBlocking(keyspace, columnFamily.right); } catch (TimeoutException e) { throw (UnavailableException) new UnavailableException().initCause(e); } catch (IOException e) { throw (UnavailableException) new UnavailableException().initCause(e); } result.type = CqlResultType.VOID; return result; case DELETE: DeleteStatement delete = (DeleteStatement)statement.statement; keyspace = delete.keyspace == null ? clientState.getKeyspace() : delete.keyspace; List<IMutation> deletions = delete.prepareRowMutations(keyspace, clientState, variables); for (IMutation deletion : deletions) { validateKey(deletion.key()); } try { StorageProxy.mutate(deletions, delete.getConsistencyLevel()); } catch (TimeoutException e) { throw new TimedOutException(); } result.type = CqlResultType.VOID; return result; case CREATE_KEYSPACE: CreateKeyspaceStatement create = (CreateKeyspaceStatement)statement.statement; create.validate(); ThriftValidation.validateKeyspaceNotSystem(create.getName()); clientState.hasKeyspaceSchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { KsDef ksd = new KsDef(create.getName(), create.getStrategyClass(), Collections.<CfDef>emptyList()) .setStrategy_options(create.getStrategyOptions()); ThriftValidation.validateKsDef(ksd); ThriftValidation.validateKeyspaceNotYetExisting(create.getName()); MigrationManager.announceNewKeyspace(KSMetaData.fromThrift(ksd)); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case CREATE_COLUMNFAMILY: CreateColumnFamilyStatement createCf = (CreateColumnFamilyStatement)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); CFMetaData cfmd = createCf.getCFMetaData(keyspace, variables); ThriftValidation.validateCfDef(cfmd.toThrift(), null); try { MigrationManager.announceNewColumnFamily(cfmd); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case CREATE_INDEX: CreateIndexStatement createIdx = (CreateIndexStatement)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); CFMetaData oldCfm = Schema.instance.getCFMetaData(keyspace, createIdx.getColumnFamily()); if (oldCfm == null) throw new InvalidRequestException("No such column family: " + createIdx.getColumnFamily()); boolean columnExists = false; ByteBuffer columnName = createIdx.getColumnName().getByteBuffer(); // mutating oldCfm directly would be bad, but mutating a Thrift copy is fine. This also // sets us up to use validateCfDef to check for index name collisions. CfDef cf_def = oldCfm.toThrift(); for (ColumnDef cd : cf_def.column_metadata) { if (cd.name.equals(columnName)) { if (cd.index_type != null) throw new InvalidRequestException("Index already exists"); if (logger.isDebugEnabled()) logger.debug("Updating column {} definition for index {}", oldCfm.comparator.getString(columnName), createIdx.getIndexName()); cd.setIndex_type(IndexType.KEYS); cd.setIndex_name(createIdx.getIndexName()); columnExists = true; break; } } if (!columnExists) throw new InvalidRequestException("No column definition found for column " + oldCfm.comparator.getString(columnName)); CFMetaData.addDefaultIndexNames(cf_def); ThriftValidation.validateCfDef(cf_def, oldCfm); try { MigrationManager.announceColumnFamilyUpdate(CFMetaData.fromThrift(cf_def)); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case DROP_INDEX: DropIndexStatement dropIdx = (DropIndexStatement)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceColumnFamilyUpdate(dropIdx.generateCFMetadataUpdate(clientState.getKeyspace())); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } catch (IOException e) { InvalidRequestException ex = new InvalidRequestException(e.toString()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case DROP_KEYSPACE: String deleteKeyspace = (String)statement.statement; ThriftValidation.validateKeyspaceNotSystem(deleteKeyspace); clientState.hasKeyspaceSchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceKeyspaceDrop(deleteKeyspace); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case DROP_COLUMNFAMILY: String deleteColumnFamily = (String)statement.statement; clientState.hasColumnFamilySchemaAccess(Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceColumnFamilyDrop(keyspace, deleteColumnFamily); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; case ALTER_TABLE: AlterTableStatement alterTable = (AlterTableStatement) statement.statement; validateColumnFamily(keyspace, alterTable.columnFamily); clientState.hasColumnFamilyAccess(alterTable.columnFamily, Permission.WRITE); validateSchemaAgreement(); try { MigrationManager.announceColumnFamilyUpdate(CFMetaData.fromThrift(alterTable.getCfDef(keyspace))); validateSchemaIsSettled(); } catch (ConfigurationException e) { InvalidRequestException ex = new InvalidRequestException(e.getMessage()); ex.initCause(e); throw ex; } result.type = CqlResultType.VOID; return result; } return null; // We should never get here. }
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/util/io/StreamCopyThread.java b/org.eclipse.jgit/src/org/eclipse/jgit/util/io/StreamCopyThread.java index bf47d199..c3683569 100644 --- a/org.eclipse.jgit/src/org/eclipse/jgit/util/io/StreamCopyThread.java +++ b/org.eclipse.jgit/src/org/eclipse/jgit/util/io/StreamCopyThread.java @@ -1,148 +1,142 @@ /* * Copyright (C) 2009-2010, Google Inc. * 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.util.io; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.util.concurrent.atomic.AtomicInteger; /** Thread to copy from an input stream to an output stream. */ public class StreamCopyThread extends Thread { private static final int BUFFER_SIZE = 1024; private final InputStream src; private final OutputStream dst; private final AtomicInteger flushCounter = new AtomicInteger(0); /** * Create a thread to copy data from an input stream to an output stream. * * @param i * stream to copy from. The thread terminates when this stream * reaches EOF. The thread closes this stream before it exits. * @param o * stream to copy into. The destination stream is automatically * closed when the thread terminates. */ public StreamCopyThread(final InputStream i, final OutputStream o) { setName(Thread.currentThread().getName() + "-StreamCopy"); src = i; dst = o; } /** * Request the thread to flush the output stream as soon as possible. * <p> * This is an asynchronous request to the thread. The actual flush will * happen at some future point in time, when the thread wakes up to process * the request. */ public void flush() { flushCounter.incrementAndGet(); interrupt(); } @Override public void run() { try { final byte[] buf = new byte[BUFFER_SIZE]; for (;;) { try { if (needFlush()) dst.flush(); final int n; try { n = src.read(buf); } catch (InterruptedIOException wakey) { - if (flushCounter.get() > 0) - continue; - else - throw wakey; + continue; } if (n < 0) break; for (;;) { try { dst.write(buf, 0, n); } catch (InterruptedIOException wakey) { - if (flushCounter.get() > 0) - continue; - else - throw wakey; + continue; } break; } } catch (IOException e) { break; } } } finally { try { src.close(); } catch (IOException e) { // Ignore IO errors on close } try { dst.close(); } catch (IOException e) { // Ignore IO errors on close } } } private boolean needFlush() { int i = flushCounter.get(); if (i > 0) { flushCounter.decrementAndGet(); return true; } return false; } }
false
true
public void run() { try { final byte[] buf = new byte[BUFFER_SIZE]; for (;;) { try { if (needFlush()) dst.flush(); final int n; try { n = src.read(buf); } catch (InterruptedIOException wakey) { if (flushCounter.get() > 0) continue; else throw wakey; } if (n < 0) break; for (;;) { try { dst.write(buf, 0, n); } catch (InterruptedIOException wakey) { if (flushCounter.get() > 0) continue; else throw wakey; } break; } } catch (IOException e) { break; } } } finally { try { src.close(); } catch (IOException e) { // Ignore IO errors on close } try { dst.close(); } catch (IOException e) { // Ignore IO errors on close } } }
public void run() { try { final byte[] buf = new byte[BUFFER_SIZE]; for (;;) { try { if (needFlush()) dst.flush(); final int n; try { n = src.read(buf); } catch (InterruptedIOException wakey) { continue; } if (n < 0) break; for (;;) { try { dst.write(buf, 0, n); } catch (InterruptedIOException wakey) { continue; } break; } } catch (IOException e) { break; } } } finally { try { src.close(); } catch (IOException e) { // Ignore IO errors on close } try { dst.close(); } catch (IOException e) { // Ignore IO errors on close } } }
diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/CompositeItemWriterTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/CompositeItemWriterTests.java index 552cb8e72..461b6475b 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/CompositeItemWriterTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/item/support/CompositeItemWriterTests.java @@ -1,56 +1,56 @@ package org.springframework.batch.item.support; import static org.easymock.EasyMock.createStrictMock; import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import java.util.ArrayList; import java.util.Collections; import java.util.List; import junit.framework.TestCase; import org.springframework.batch.item.ItemWriter; /** * Tests for {@link CompositeItemWriter} * * @author Robert Kasanicky */ public class CompositeItemWriterTests extends TestCase { // object under test private CompositeItemWriter<Object> itemWriter = new CompositeItemWriter<Object>(); /** * Regular usage scenario. All injected processors should be called. */ public void testProcess() throws Exception { final int NUMBER_OF_WRITERS = 10; List<Object> data = Collections.singletonList(new Object()); List<ItemWriter<? super Object>> writers = new ArrayList<ItemWriter<? super Object>>(); for (int i = 0; i < NUMBER_OF_WRITERS; i++) { @SuppressWarnings("unchecked") - ItemWriter<Object> writer = createStrictMock(ItemWriter.class); + ItemWriter<? super Object> writer = createStrictMock(ItemWriter.class); writer.write(data); expectLastCall().once(); replay(writer); writers.add(writer); } itemWriter.setDelegates(writers); itemWriter.write(data); - for (ItemWriter<Object> writer : writers) { + for (ItemWriter<? super Object> writer : writers) { verify(writer); } } }
false
true
public void testProcess() throws Exception { final int NUMBER_OF_WRITERS = 10; List<Object> data = Collections.singletonList(new Object()); List<ItemWriter<? super Object>> writers = new ArrayList<ItemWriter<? super Object>>(); for (int i = 0; i < NUMBER_OF_WRITERS; i++) { @SuppressWarnings("unchecked") ItemWriter<Object> writer = createStrictMock(ItemWriter.class); writer.write(data); expectLastCall().once(); replay(writer); writers.add(writer); } itemWriter.setDelegates(writers); itemWriter.write(data); for (ItemWriter<Object> writer : writers) { verify(writer); } }
public void testProcess() throws Exception { final int NUMBER_OF_WRITERS = 10; List<Object> data = Collections.singletonList(new Object()); List<ItemWriter<? super Object>> writers = new ArrayList<ItemWriter<? super Object>>(); for (int i = 0; i < NUMBER_OF_WRITERS; i++) { @SuppressWarnings("unchecked") ItemWriter<? super Object> writer = createStrictMock(ItemWriter.class); writer.write(data); expectLastCall().once(); replay(writer); writers.add(writer); } itemWriter.setDelegates(writers); itemWriter.write(data); for (ItemWriter<? super Object> writer : writers) { verify(writer); } }
diff --git a/web/src/main/java/org/apache/ki/web/DefaultWebSecurityManager.java b/web/src/main/java/org/apache/ki/web/DefaultWebSecurityManager.java index 443fe867..650406ea 100644 --- a/web/src/main/java/org/apache/ki/web/DefaultWebSecurityManager.java +++ b/web/src/main/java/org/apache/ki/web/DefaultWebSecurityManager.java @@ -1,192 +1,194 @@ /* * 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.ki.web; import java.util.Collection; import javax.servlet.ServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.ki.mgt.DefaultSecurityManager; import org.apache.ki.realm.Realm; import org.apache.ki.session.mgt.SessionManager; import org.apache.ki.subject.PrincipalCollection; import org.apache.ki.util.LifecycleUtils; import org.apache.ki.web.servlet.KiHttpServletRequest; import org.apache.ki.web.session.DefaultWebSessionManager; import org.apache.ki.web.session.ServletContainerSessionManager; import org.apache.ki.web.session.WebSessionManager; /** * SecurityManager implementation that should be used in web-based applications or any application that requires * HTTP connectivity (SOAP, http remoting, etc). * * @author Les Hazlewood * @since 0.2 */ public class DefaultWebSecurityManager extends DefaultSecurityManager { //TODO - complete JavaDoc private static final Logger log = LoggerFactory.getLogger(DefaultWebSecurityManager.class); public static final String HTTP_SESSION_MODE = "http"; public static final String KI_SESSION_MODE = "ki"; /** * The key that is used to store subject principals in the session. */ public static final String PRINCIPALS_SESSION_KEY = DefaultWebSecurityManager.class.getName() + "_PRINCIPALS_SESSION_KEY"; /** * The key that is used to store whether or not the user is authenticated in the session. */ public static final String AUTHENTICATED_SESSION_KEY = DefaultWebSecurityManager.class.getName() + "_AUTHENTICATED_SESSION_KEY"; private String sessionMode = HTTP_SESSION_MODE; //default public DefaultWebSecurityManager() { super(); WebSessionManager sm = new ServletContainerSessionManager(); setSessionManager(sm); setRememberMeManager(new WebRememberMeManager()); setSubjectFactory(new WebSubjectFactory(this, sm)); } public DefaultWebSecurityManager(Realm singleRealm) { this(); setRealm(singleRealm); } public DefaultWebSecurityManager(Collection<Realm> realms) { this(); setRealms(realms); } /** * Sets the path used to store the remember me cookie. This determines which paths * are able to view the remember me cookie. * * @param rememberMeCookiePath the path to use for the remember me cookie. */ public void setRememberMeCookiePath(String rememberMeCookiePath) { ((WebRememberMeManager) getRememberMeManager()).setCookiePath(rememberMeCookiePath); } /** * Sets the maximum age allowed for the remember me cookie. This basically sets how long * a user will be remembered by the "remember me" feature. Used when calling * {@link javax.servlet.http.Cookie#setMaxAge(int) maxAge}. Please see that JavaDoc for the semantics on the * repercussions of negative, zero, and positive values for the maxAge. * * @param rememberMeMaxAge the maximum age for the remember me cookie. */ public void setRememberMeCookieMaxAge(Integer rememberMeMaxAge) { ((WebRememberMeManager) getRememberMeManager()).setCookieMaxAge(rememberMeMaxAge); } private DefaultWebSessionManager getSessionManagerForCookieAttributes() { SessionManager sessionManager = getSessionManager(); if (!(sessionManager instanceof DefaultWebSessionManager)) { String msg = "The convenience passthrough methods for setting session id cookie attributes " + "are only available when the underlying SessionManager implementation is " + DefaultWebSessionManager.class.getName() + ", which is enabled by default when the " + "sessionMode is 'ki'."; throw new IllegalStateException(msg); } return (DefaultWebSessionManager) sessionManager; } public void setSessionIdCookieName(String name) { getSessionManagerForCookieAttributes().setSessionIdCookieName(name); } public void setSessionIdCookiePath(String path) { getSessionManagerForCookieAttributes().setSessionIdCookiePath(path); } public void setSessionIdCookieMaxAge(int maxAge) { getSessionManagerForCookieAttributes().setSessionIdCookieMaxAge(maxAge); } public void setSessionIdCookieSecure(boolean secure) { getSessionManagerForCookieAttributes().setSessionIdCookieSecure(secure); } public String getSessionMode() { return sessionMode; } public void setSessionMode(String sessionMode) { String mode = sessionMode; if (mode == null) { throw new IllegalArgumentException("sessionMode argument cannot be null."); } mode = sessionMode.toLowerCase(); if (!HTTP_SESSION_MODE.equals(mode) && !KI_SESSION_MODE.equals(mode)) { String msg = "Invalid sessionMode [" + sessionMode + "]. Allowed values are " + "public static final String constants in the " + getClass().getName() + " class: '" + HTTP_SESSION_MODE + "' or '" + KI_SESSION_MODE + "', with '" + HTTP_SESSION_MODE + "' being the default."; throw new IllegalArgumentException(msg); } boolean recreate = this.sessionMode == null || !this.sessionMode.equals(mode); this.sessionMode = mode; if (recreate) { LifecycleUtils.destroy(getSessionManager()); WebSessionManager sessionManager = createSessionManager(mode); setSessionManager(sessionManager); + //the factory needs to reflect this new SessionManager: + setSubjectFactory(new WebSubjectFactory(this,sessionManager)); } } public boolean isHttpSessionMode() { return this.sessionMode == null || this.sessionMode.equals(HTTP_SESSION_MODE); } protected WebSessionManager createSessionManager(String sessionMode) { if (sessionMode == null || sessionMode.equalsIgnoreCase(HTTP_SESSION_MODE)) { if (log.isInfoEnabled()) { log.info(HTTP_SESSION_MODE + " mode - enabling ServletContainerSessionManager (HTTP-only Sessions)"); } return new ServletContainerSessionManager(); } else { if (log.isInfoEnabled()) { log.info(KI_SESSION_MODE + " mode - enabling DefaultWebSessionManager (HTTP + heterogeneous-client sessions)"); } return new DefaultWebSessionManager(); } } @Override protected void beforeLogout(PrincipalCollection subjectIdentifier) { super.beforeLogout(subjectIdentifier); //also ensure a request attribute is set so the Subject is not reacquired later during the request: removeRequestIdentity(); } protected void removeRequestIdentity() { ServletRequest request = WebUtils.getServletRequest(); if ( request != null ) { request.setAttribute(KiHttpServletRequest.IDENTITY_REMOVED_KEY, Boolean.TRUE); } } }
true
true
public void setSessionMode(String sessionMode) { String mode = sessionMode; if (mode == null) { throw new IllegalArgumentException("sessionMode argument cannot be null."); } mode = sessionMode.toLowerCase(); if (!HTTP_SESSION_MODE.equals(mode) && !KI_SESSION_MODE.equals(mode)) { String msg = "Invalid sessionMode [" + sessionMode + "]. Allowed values are " + "public static final String constants in the " + getClass().getName() + " class: '" + HTTP_SESSION_MODE + "' or '" + KI_SESSION_MODE + "', with '" + HTTP_SESSION_MODE + "' being the default."; throw new IllegalArgumentException(msg); } boolean recreate = this.sessionMode == null || !this.sessionMode.equals(mode); this.sessionMode = mode; if (recreate) { LifecycleUtils.destroy(getSessionManager()); WebSessionManager sessionManager = createSessionManager(mode); setSessionManager(sessionManager); } }
public void setSessionMode(String sessionMode) { String mode = sessionMode; if (mode == null) { throw new IllegalArgumentException("sessionMode argument cannot be null."); } mode = sessionMode.toLowerCase(); if (!HTTP_SESSION_MODE.equals(mode) && !KI_SESSION_MODE.equals(mode)) { String msg = "Invalid sessionMode [" + sessionMode + "]. Allowed values are " + "public static final String constants in the " + getClass().getName() + " class: '" + HTTP_SESSION_MODE + "' or '" + KI_SESSION_MODE + "', with '" + HTTP_SESSION_MODE + "' being the default."; throw new IllegalArgumentException(msg); } boolean recreate = this.sessionMode == null || !this.sessionMode.equals(mode); this.sessionMode = mode; if (recreate) { LifecycleUtils.destroy(getSessionManager()); WebSessionManager sessionManager = createSessionManager(mode); setSessionManager(sessionManager); //the factory needs to reflect this new SessionManager: setSubjectFactory(new WebSubjectFactory(this,sessionManager)); } }
diff --git a/discovery/src/main/java/com/proofpoint/discovery/client/HttpDiscoveryClient.java b/discovery/src/main/java/com/proofpoint/discovery/client/HttpDiscoveryClient.java index 98d668ffa..9b8001e07 100644 --- a/discovery/src/main/java/com/proofpoint/discovery/client/HttpDiscoveryClient.java +++ b/discovery/src/main/java/com/proofpoint/discovery/client/HttpDiscoveryClient.java @@ -1,273 +1,273 @@ package com.proofpoint.discovery.client; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.io.CharStreams; import com.google.common.util.concurrent.CheckedFuture; import com.google.inject.Inject; import com.proofpoint.http.client.HttpClient; import com.proofpoint.http.client.Request; import com.proofpoint.http.client.RequestBuilder; import com.proofpoint.http.client.Response; import com.proofpoint.http.client.ResponseHandler; import com.proofpoint.json.JsonCodec; import com.proofpoint.node.NodeInfo; import com.proofpoint.units.Duration; import org.codehaus.jackson.annotate.JsonCreator; import org.codehaus.jackson.annotate.JsonProperty; import javax.ws.rs.core.CacheControl; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.util.List; import java.util.Set; import java.util.concurrent.CancellationException; import java.util.concurrent.TimeUnit; import static com.proofpoint.http.client.JsonBodyGenerator.jsonBodyGenerator; import static com.proofpoint.http.client.RequestBuilder.prepareDelete; import static com.proofpoint.http.client.RequestBuilder.prepareGet; import static com.proofpoint.http.client.RequestBuilder.preparePut; import static com.proofpoint.json.JsonCodec.jsonCodec; import static java.lang.String.format; import static javax.ws.rs.core.Response.Status.NOT_MODIFIED; import static javax.ws.rs.core.Response.Status.OK; public class HttpDiscoveryClient implements DiscoveryClient { private final String environment; private final URI discoveryServiceURI; private final NodeInfo nodeInfo; private final JsonCodec<ServiceDescriptorsRepresentation> serviceDescriptorsCodec; private final JsonCodec<Announcement> announcementCodec; private final HttpClient httpClient; public HttpDiscoveryClient(DiscoveryClientConfig config, NodeInfo nodeInfo, HttpClient httpClient) { this(config, nodeInfo, jsonCodec(ServiceDescriptorsRepresentation.class), jsonCodec(Announcement.class), httpClient); } @Inject public HttpDiscoveryClient(DiscoveryClientConfig config, NodeInfo nodeInfo, JsonCodec<ServiceDescriptorsRepresentation> serviceDescriptorsCodec, JsonCodec<Announcement> announcementCodec, @ForDiscoverClient HttpClient httpClient) { Preconditions.checkNotNull(config, "config is null"); Preconditions.checkNotNull(nodeInfo, "nodeInfo is null"); Preconditions.checkNotNull(serviceDescriptorsCodec, "serviceDescriptorsCodec is null"); Preconditions.checkNotNull(announcementCodec, "announcementCodec is null"); Preconditions.checkNotNull(httpClient, "httpClient is null"); this.nodeInfo = nodeInfo; this.environment = nodeInfo.getEnvironment(); this.discoveryServiceURI = config.getDiscoveryServiceURI(); this.serviceDescriptorsCodec = serviceDescriptorsCodec; this.announcementCodec = announcementCodec; this.httpClient = httpClient; } @Override public CheckedFuture<Duration, DiscoveryException> announce(Set<ServiceAnnouncement> services) { Preconditions.checkNotNull(services, "services is null"); Announcement announcement = new Announcement(nodeInfo.getEnvironment(), nodeInfo.getNodeId(), nodeInfo.getPool(), nodeInfo.getLocation(), services); Request request = preparePut() .setUri(URI.create(discoveryServiceURI + "/v1/announcement/" + nodeInfo.getNodeId())) .setHeader("Content-Type", MediaType.APPLICATION_JSON) .setBodyGenerator(jsonBodyGenerator(announcementCodec, announcement)) .build(); return httpClient.execute(request, new DiscoveryResponseHandler<Duration>("Announcement") { @Override public Duration handle(Request request, Response response) throws DiscoveryException { int statusCode = response.getStatusCode(); if (!isSuccess(statusCode)) { throw new DiscoveryException(String.format("Announcement failed with status code %s: %s", statusCode, getBodyForError(response))); } Duration maxAge = extractMaxAge(response); return maxAge; } }); } private boolean isSuccess(int statusCode) { return statusCode / 100 == 2; } private static String getBodyForError(Response response) { try { return CharStreams.toString(new InputStreamReader(response.getInputStream(), Charsets.UTF_8)); } catch (IOException e) { return "(error getting body)"; } } @Override public CheckedFuture<Void, DiscoveryException> unannounce() { Request request = prepareDelete() .setUri(URI.create(discoveryServiceURI + "/v1/announcement/" + nodeInfo.getNodeId())) .build(); return httpClient.execute(request, new DiscoveryResponseHandler<Void>("Unannouncement")); } @Override public CheckedFuture<ServiceDescriptors, DiscoveryException> getServices(String type, String pool) { Preconditions.checkNotNull(type, "type is null"); Preconditions.checkNotNull(pool, "pool is null"); return lookup(type, pool, null); } @Override public CheckedFuture<ServiceDescriptors, DiscoveryException> refreshServices(ServiceDescriptors serviceDescriptors) { Preconditions.checkNotNull(serviceDescriptors, "serviceDescriptors is null"); return lookup(serviceDescriptors.getType(), serviceDescriptors.getPool(), serviceDescriptors); } private CheckedFuture<ServiceDescriptors, DiscoveryException> lookup(final String type, final String pool, final ServiceDescriptors serviceDescriptors) { Preconditions.checkNotNull(type, "type is null"); RequestBuilder requestBuilder = prepareGet().setUri(URI.create(discoveryServiceURI + "/v1/service/" + type + "/" + pool)); - if (serviceDescriptors != null) { + if (serviceDescriptors != null && serviceDescriptors.getETag() != null) { requestBuilder.setHeader(HttpHeaders.ETAG, serviceDescriptors.getETag()); } return httpClient.execute(requestBuilder.build(), new DiscoveryResponseHandler<ServiceDescriptors>(format("Lookup of %s", type)) { @Override public ServiceDescriptors handle(Request request, Response response) { Duration maxAge = extractMaxAge(response); String eTag = response.getHeader(HttpHeaders.ETAG); if (NOT_MODIFIED.getStatusCode() == response.getStatusCode() && serviceDescriptors != null) { return new ServiceDescriptors(serviceDescriptors, maxAge, eTag); } if (OK.getStatusCode() != response.getStatusCode()) { throw new DiscoveryException(format("Lookup of %s failed with status code %s", type, response.getStatusCode())); } String json; try { json = CharStreams.toString(new InputStreamReader(response.getInputStream(), Charsets.UTF_8)); } catch (IOException e) { throw new DiscoveryException(format("Lookup of %s failed", type), e); } ServiceDescriptorsRepresentation serviceDescriptorsRepresentation = serviceDescriptorsCodec.fromJson(json); if (!environment.equals(serviceDescriptorsRepresentation.getEnvironment())) { throw new DiscoveryException(format("Expected environment to be %s, but was %s", environment, serviceDescriptorsRepresentation.getEnvironment())); } return new ServiceDescriptors( type, pool, serviceDescriptorsRepresentation.getServiceDescriptors(), maxAge, eTag); } }); } private Duration extractMaxAge(Response response) { String header = response.getHeader(HttpHeaders.CACHE_CONTROL); if (header != null) { CacheControl cacheControl = CacheControl.valueOf(header); if (cacheControl.getMaxAge() > 0) { return new Duration(cacheControl.getMaxAge(), TimeUnit.SECONDS); } } return DEFAULT_DELAY; } public static class ServiceDescriptorsRepresentation { private final String environment; private final List<ServiceDescriptor> serviceDescriptors; @JsonCreator public ServiceDescriptorsRepresentation( @JsonProperty("environment") String environment, @JsonProperty("services") List<ServiceDescriptor> serviceDescriptors) { Preconditions.checkNotNull(serviceDescriptors); Preconditions.checkNotNull(environment); this.environment = environment; this.serviceDescriptors = ImmutableList.copyOf(serviceDescriptors); } public String getEnvironment() { return environment; } public List<ServiceDescriptor> getServiceDescriptors() { return serviceDescriptors; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ServiceDescriptorsRepresentation"); sb.append("{environment='").append(environment).append('\''); sb.append(", serviceDescriptorList=").append(serviceDescriptors); sb.append('}'); return sb.toString(); } } private class DiscoveryResponseHandler<T> implements ResponseHandler<T, DiscoveryException> { private final String name; protected DiscoveryResponseHandler(String name) { this.name = name; } @Override public T handle(Request request, Response response) { return null; } @Override public final DiscoveryException handleException(Request request, Exception exception) { if (exception instanceof InterruptedException) { return new DiscoveryException(name + " was interrupted"); } if (exception instanceof CancellationException) { return new DiscoveryException(name + " was canceled"); } if (exception instanceof DiscoveryException) { throw (DiscoveryException) exception; } return new DiscoveryException(name + " failed", exception); } } }
true
true
private CheckedFuture<ServiceDescriptors, DiscoveryException> lookup(final String type, final String pool, final ServiceDescriptors serviceDescriptors) { Preconditions.checkNotNull(type, "type is null"); RequestBuilder requestBuilder = prepareGet().setUri(URI.create(discoveryServiceURI + "/v1/service/" + type + "/" + pool)); if (serviceDescriptors != null) { requestBuilder.setHeader(HttpHeaders.ETAG, serviceDescriptors.getETag()); } return httpClient.execute(requestBuilder.build(), new DiscoveryResponseHandler<ServiceDescriptors>(format("Lookup of %s", type)) { @Override public ServiceDescriptors handle(Request request, Response response) { Duration maxAge = extractMaxAge(response); String eTag = response.getHeader(HttpHeaders.ETAG); if (NOT_MODIFIED.getStatusCode() == response.getStatusCode() && serviceDescriptors != null) { return new ServiceDescriptors(serviceDescriptors, maxAge, eTag); } if (OK.getStatusCode() != response.getStatusCode()) { throw new DiscoveryException(format("Lookup of %s failed with status code %s", type, response.getStatusCode())); } String json; try { json = CharStreams.toString(new InputStreamReader(response.getInputStream(), Charsets.UTF_8)); } catch (IOException e) { throw new DiscoveryException(format("Lookup of %s failed", type), e); } ServiceDescriptorsRepresentation serviceDescriptorsRepresentation = serviceDescriptorsCodec.fromJson(json); if (!environment.equals(serviceDescriptorsRepresentation.getEnvironment())) { throw new DiscoveryException(format("Expected environment to be %s, but was %s", environment, serviceDescriptorsRepresentation.getEnvironment())); } return new ServiceDescriptors( type, pool, serviceDescriptorsRepresentation.getServiceDescriptors(), maxAge, eTag); } }); }
private CheckedFuture<ServiceDescriptors, DiscoveryException> lookup(final String type, final String pool, final ServiceDescriptors serviceDescriptors) { Preconditions.checkNotNull(type, "type is null"); RequestBuilder requestBuilder = prepareGet().setUri(URI.create(discoveryServiceURI + "/v1/service/" + type + "/" + pool)); if (serviceDescriptors != null && serviceDescriptors.getETag() != null) { requestBuilder.setHeader(HttpHeaders.ETAG, serviceDescriptors.getETag()); } return httpClient.execute(requestBuilder.build(), new DiscoveryResponseHandler<ServiceDescriptors>(format("Lookup of %s", type)) { @Override public ServiceDescriptors handle(Request request, Response response) { Duration maxAge = extractMaxAge(response); String eTag = response.getHeader(HttpHeaders.ETAG); if (NOT_MODIFIED.getStatusCode() == response.getStatusCode() && serviceDescriptors != null) { return new ServiceDescriptors(serviceDescriptors, maxAge, eTag); } if (OK.getStatusCode() != response.getStatusCode()) { throw new DiscoveryException(format("Lookup of %s failed with status code %s", type, response.getStatusCode())); } String json; try { json = CharStreams.toString(new InputStreamReader(response.getInputStream(), Charsets.UTF_8)); } catch (IOException e) { throw new DiscoveryException(format("Lookup of %s failed", type), e); } ServiceDescriptorsRepresentation serviceDescriptorsRepresentation = serviceDescriptorsCodec.fromJson(json); if (!environment.equals(serviceDescriptorsRepresentation.getEnvironment())) { throw new DiscoveryException(format("Expected environment to be %s, but was %s", environment, serviceDescriptorsRepresentation.getEnvironment())); } return new ServiceDescriptors( type, pool, serviceDescriptorsRepresentation.getServiceDescriptors(), maxAge, eTag); } }); }
diff --git a/src/haven/SkelSprite.java b/src/haven/SkelSprite.java index 2b97c5fd..6b146ed6 100644 --- a/src/haven/SkelSprite.java +++ b/src/haven/SkelSprite.java @@ -1,117 +1,118 @@ /* * This file is part of the Haven & Hearth game client. * Copyright (C) 2009 Fredrik Tolf <[email protected]>, and * Björn Johannessen <[email protected]> * * Redistribution and/or modification of this file is subject to the * terms of the GNU Lesser General Public License, version 3, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Other parts of this source tree adhere to other copying * rights. Please see the file `COPYING' in the root directory of the * source tree for details. * * A copy the GNU Lesser General Public License is distributed along * with the source tree of which this file is a part in the file * `doc/LPGL-3'. If it is missing for any reason, please see the Free * Software Foundation's website at <http://www.fsf.org/>, or write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, MA 02111-1307 USA */ package haven; import java.util.*; import haven.Skeleton.Pose; import haven.Skeleton.PoseMod; public class SkelSprite extends Sprite { private final Skeleton skel; public final Pose pose; private PoseMod[] mods = new PoseMod[0]; private boolean stat = true; private final Rendered[] parts; public static final Factory fact = new Factory() { public Sprite create(Owner owner, Resource res, Message sdt) { if(res.layer(Skeleton.Res.class) == null) return(null); return(new SkelSprite(owner, res, sdt)); } }; public static int decnum(Message sdt) { if(sdt == null) return(0); int ret = 0, off = 0; while(!sdt.eom()) { ret |= sdt.uint8() << off; off += 8; } return(ret); } private SkelSprite(Owner owner, Resource res, Message sdt) { super(owner, res); skel = res.layer(Skeleton.Res.class).s; pose = skel.new Pose(skel.bindpose); + int fl = sdt.eom()?0xffff0000:SkelSprite.decnum(sdt); Collection<Rendered> rl = new LinkedList<Rendered>(); for(FastMesh.MeshRes mr : res.layers(FastMesh.MeshRes.class)) { - if(mr.mat != null) { + if((mr.mat != null) && ((mr.id < 0) || (((1 << mr.id) & fl) != 0))) { if(mr.m.boned()) { String bnm = mr.m.boneidp(); if(bnm == null) { rl.add(mr.mat.get().apply(new MorphedMesh(mr.m, pose))); } else { rl.add(pose.bonetrans2(skel.bones.get(bnm).idx).apply(mr.mat.get().apply(mr.m))); } } else { rl.add(mr.mat.get().apply(mr.m)); } } } this.parts = rl.toArray(new Rendered[0]); - chposes(decnum(sdt)); + chposes(fl); } private void chposes(int mask) { Collection<PoseMod> poses = new LinkedList<PoseMod>(); stat = true; pose.reset(); for(Skeleton.ResPose p : res.layers(Skeleton.ResPose.class)) { if((p.id < 0) || ((mask & (1 << p.id)) != 0)) { Skeleton.TrackMod mod = p.forskel(skel, p.defmode); if(!mod.stat) stat = false; poses.add(mod); mod.apply(pose); } } pose.gbuild(); this.mods = poses.toArray(new PoseMod[0]); } public Order setup(RenderList rl) { for(Rendered p : parts) rl.add(p, null); /* rl.add(pose.debug, null); */ return(null); } public boolean tick(int dt) { if(!stat) { pose.reset(); for(PoseMod m : mods) { m.tick(dt / 1000.0f); m.apply(pose); } pose.gbuild(); } return(false); } }
false
true
private SkelSprite(Owner owner, Resource res, Message sdt) { super(owner, res); skel = res.layer(Skeleton.Res.class).s; pose = skel.new Pose(skel.bindpose); Collection<Rendered> rl = new LinkedList<Rendered>(); for(FastMesh.MeshRes mr : res.layers(FastMesh.MeshRes.class)) { if(mr.mat != null) { if(mr.m.boned()) { String bnm = mr.m.boneidp(); if(bnm == null) { rl.add(mr.mat.get().apply(new MorphedMesh(mr.m, pose))); } else { rl.add(pose.bonetrans2(skel.bones.get(bnm).idx).apply(mr.mat.get().apply(mr.m))); } } else { rl.add(mr.mat.get().apply(mr.m)); } } } this.parts = rl.toArray(new Rendered[0]); chposes(decnum(sdt)); }
private SkelSprite(Owner owner, Resource res, Message sdt) { super(owner, res); skel = res.layer(Skeleton.Res.class).s; pose = skel.new Pose(skel.bindpose); int fl = sdt.eom()?0xffff0000:SkelSprite.decnum(sdt); Collection<Rendered> rl = new LinkedList<Rendered>(); for(FastMesh.MeshRes mr : res.layers(FastMesh.MeshRes.class)) { if((mr.mat != null) && ((mr.id < 0) || (((1 << mr.id) & fl) != 0))) { if(mr.m.boned()) { String bnm = mr.m.boneidp(); if(bnm == null) { rl.add(mr.mat.get().apply(new MorphedMesh(mr.m, pose))); } else { rl.add(pose.bonetrans2(skel.bones.get(bnm).idx).apply(mr.mat.get().apply(mr.m))); } } else { rl.add(mr.mat.get().apply(mr.m)); } } } this.parts = rl.toArray(new Rendered[0]); chposes(fl); }
diff --git a/src/org/mythtv/db/dvr/ProgramDaoHelper.java b/src/org/mythtv/db/dvr/ProgramDaoHelper.java index cca660e6..1d5253ee 100644 --- a/src/org/mythtv/db/dvr/ProgramDaoHelper.java +++ b/src/org/mythtv/db/dvr/ProgramDaoHelper.java @@ -1,801 +1,801 @@ /** * This file is part of MythTV Android Frontend * * MythTV Android Frontend 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. * * MythTV Android Frontend 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 MythTV Android Frontend. If not, see <http://www.gnu.org/licenses/>. * * This software can be found at <https://github.com/MythTV-Clients/MythTV-Android-Frontend/> */ package org.mythtv.db.dvr; import java.util.ArrayList; import java.util.List; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.mythtv.client.ui.preferences.LocationProfile; import org.mythtv.db.AbstractDaoHelper; import org.mythtv.db.channel.ChannelConstants; import org.mythtv.db.channel.ChannelDaoHelper; import org.mythtv.db.content.LiveStreamConstants; import org.mythtv.db.content.LiveStreamDaoHelper; import org.mythtv.provider.MythtvProvider; import org.mythtv.service.util.DateUtils; import org.mythtv.service.util.MythtvServiceHelper; import org.mythtv.services.api.Bool; import org.mythtv.services.api.channel.ChannelInfo; import org.mythtv.services.api.content.LiveStreamInfo; import org.mythtv.services.api.dvr.Program; import org.mythtv.services.api.dvr.Recording; import org.springframework.http.ResponseEntity; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.RemoteException; import android.util.Log; /** * @author Daniel Frey * */ public abstract class ProgramDaoHelper extends AbstractDaoHelper { protected static final String TAG = ProgramDaoHelper.class.getSimpleName(); protected MythtvServiceHelper mMythtvServiceHelper = MythtvServiceHelper.getInstance(); protected ChannelDaoHelper mChannelDaoHelper = ChannelDaoHelper.getInstance(); protected LiveStreamDaoHelper mLiveStreamDaoHelper = LiveStreamDaoHelper.getInstance(); protected RecordingDaoHelper mRecordingDaoHelper = RecordingDaoHelper.getInstance(); protected ProgramDaoHelper() { super(); } /** * @param context * @param uri * @param projection * @param selection * @param selectionArgs * @param sortOrder * @param table * @return */ protected List<Program> findAll( final Context context, final Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, final String table ) { // Log.v( TAG, "findAll : enter" ); if( null == context ) throw new RuntimeException( "ProgramDaoHelper is not initialized" ); List<Program> programs = new ArrayList<Program>(); Cursor cursor = context.getContentResolver().query( uri, projection, selection, selectionArgs, sortOrder ); while( cursor.moveToNext() ) { Program program = convertCursorToProgram( cursor, table ); programs.add( program ); } cursor.close(); // Log.v( TAG, "findAll : exit" ); return programs; } /** * @return */ public abstract List<Program> findAll( final Context context, final LocationProfile locationProfile ); /** * @param uri * @param projection * @param selection * @param selectionArgs * @param sortOrder * @return */ protected Program findOne( final Context context, final Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder, final String table ) { // Log.v( TAG, "findOne : enter" ); if( null == context ) throw new RuntimeException( "ProgramDaoHelper is not initialized" ); // Log.v( TAG, "findOne : selection=" + selection ); // if( null != selectionArgs ) { // for( String selectionArg : selectionArgs ) { // Log.v( TAG, "findOne : selectionArg=" + selectionArg ); // } // } Program program = null; Cursor cursor = context.getContentResolver().query( uri, projection, selection, selectionArgs, sortOrder ); if( cursor.moveToFirst() ) { program = convertCursorToProgram( cursor, table ); } cursor.close(); // Log.v( TAG, "findOne : exit" ); return program; } /** * @param context * @param locationProfile * @param channelId * @param startTime * @return */ public abstract Program findOne( final Context context, final LocationProfile locationProfile, final int channelId, final DateTime startTime ); /** * @param uri * @param program * @return */ protected int save( final Context context, final Uri uri, final LocationProfile locationProfile, Program program, final String table ) { // Log.v( TAG, "save : enter" ); if( null == context ) throw new RuntimeException( "ProgramDaoHelper is not initialized" ); ContentValues values = convertProgramToContentValues( locationProfile, new DateTime( DateTimeZone.UTC ), program ); String[] projection = new String[] { ProgramConstants._ID }; String selection = table + "." + ProgramConstants.FIELD_CHANNEL_ID + " = ? AND " + table + "." + ProgramConstants.FIELD_START_TIME + " = ?"; String[] selectionArgs = new String[] { String.valueOf( program.getChannelInfo().getChannelId() ), String.valueOf( program.getStartTime().getMillis() ) }; selection = appendLocationHostname( context, locationProfile, selection, table ); int updated = -1; Cursor cursor = context.getContentResolver().query( uri, projection, selection, selectionArgs, null ); if( cursor.moveToFirst() ) { // Log.v( TAG, "save : updating existing program" ); Long id = cursor.getLong( cursor.getColumnIndexOrThrow( ProgramConstants._ID ) ); updated = context.getContentResolver().update( ContentUris.withAppendedId( uri, id ), values, null, null ); } else { Uri inserted = context.getContentResolver().insert( uri, values ); if( null != inserted ) { updated = 1; } } cursor.close(); if( null != program.getRecording() ) { if( program.getRecording().getRecordId() != 0 ) { mRecordingDaoHelper.save( context, RecordingConstants.ContentDetails.getValueFromParent( table ).getContentUri(), locationProfile, program.getStartTime(), program.getRecording(), RecordingConstants.ContentDetails.getValueFromParent( table ).getTableName() ); } } // Log.v( TAG, "save : updated=" + updated ); // Log.v( TAG, "save : exit" ); return updated; } /** * @param program * @return */ public abstract int save( final Context context, final LocationProfile locationProfile, Program program ); /** * @return */ public int deleteAll( final Context context, final Uri uri ) { // Log.v( TAG, "deleteAll : enter" ); if( null == context ) throw new RuntimeException( "ProgramDaoHelper is not initialized" ); int deleted = context.getContentResolver().delete( uri, null, null ); // Log.v( TAG, "deleteAll : deleted=" + deleted ); // Log.v( TAG, "deleteAll : exit" ); return deleted; } /** * @return */ public abstract int deleteAll( final Context context ); /** * @param uri * @param program * @return */ public int delete( final Context context, final Uri uri, final LocationProfile locationProfile, Program program, final String table ) { // Log.v( TAG, "delete : enter" ); if( null == context ) throw new RuntimeException( "ProgramDaoHelper is not initialized" ); String selection = ProgramConstants.FIELD_CHANNEL_ID + " = ? AND " + ProgramConstants.FIELD_START_TIME + " = ?"; String[] selectionArgs = new String[] { String.valueOf( program.getChannelInfo().getChannelId() ), String.valueOf( program.getStartTime().getMillis() ) }; selection = appendLocationHostname( context, locationProfile, selection, null ); int deleted = context.getContentResolver().delete( uri, selection, selectionArgs ); // Log.v( TAG, "delete : deleted=" + deleted ); // Log.v( TAG, "delete : exit" ); return deleted; } /** * @param program * @return */ public abstract int delete( final Context context, final LocationProfile locationProfile, Program program ); /** * @param uri * @param programs * @param table * @return * @throws RemoteException * @throws OperationApplicationException */ protected int load( final Context context, final Uri uri, final LocationProfile locationProfile, List<Program> programs, String table ) throws RemoteException, OperationApplicationException { // Log.v( TAG, "load : enter" ); if( null == context ) throw new RuntimeException( "ProgramDaoHelper is not initialized" ); DateTime today = new DateTime( DateTimeZone.UTC ).withTimeAtStartOfDay(); DateTime lastModified = new DateTime( DateTimeZone.UTC ); // Log.v( TAG, "load : find all existing recordings, table=" + table ); String recordedSelection = ""; recordedSelection = appendLocationHostname( context, locationProfile, recordedSelection, table ); // Log.v( TAG, "load : recordedSelection=" + recordedSelection ); int loaded = -1; int count = 0; ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); String[] programProjection = new String[] { ProgramConstants._ID }; String programSelection = table + "." + ProgramConstants.FIELD_CHANNEL_ID + " = ? AND " + table + "." + ProgramConstants.FIELD_START_TIME + " = ?"; programSelection = appendLocationHostname( context, locationProfile, programSelection, table ); boolean inError; RecordingConstants.ContentDetails details = RecordingConstants.ContentDetails.getValueFromParent( table ); - Log.w(TAG, "load : details - parent=" + details.getParent() + ", tableName=" + details.getTableName() + ", contentUri=" + details.getContentUri().toString() ); +// Log.w(TAG, "load : details - parent=" + details.getParent() + ", tableName=" + details.getTableName() + ", contentUri=" + details.getContentUri().toString() ); for( Program program : programs ) { if( null == program.getStartTime() || null == program.getEndTime() ) { // Log.w(TAG, "load : null starttime and or endtime" ); inError = true; } else { inError = false; } DateTime startTime = new DateTime( program.getStartTime() ); ContentValues programValues = convertProgramToContentValues( locationProfile, lastModified, program ); Cursor programCursor = context.getContentResolver().query( uri, programProjection, programSelection, new String[] { String.valueOf( program.getChannelInfo().getChannelId() ), String.valueOf( startTime.getMillis() ) }, null ); if( programCursor.moveToFirst() ) { // Log.v( TAG, "load : UPDATE PROGRAM " + count + ":" + program.getChannelInfo().getChannelId() + ":" + program.getStartTime() + ":" + program.getHostname() ); Long id = programCursor.getLong( programCursor.getColumnIndexOrThrow( ProgramConstants._ID ) ); ops.add( ContentProviderOperation.newUpdate( ContentUris.withAppendedId( uri, id ) ) .withValues( programValues ) .withYieldAllowed( true ) .build() ); } else { // Log.v( TAG, "load : INSERT PROGRAM " + count + ":" + program.getChannelInfo().getChannelId() + ":" + program.getStartTime() + ":" + program.getHostname() ); ops.add( ContentProviderOperation.newInsert( uri ) .withValues( programValues ) .withYieldAllowed( true ) .build() ); } programCursor.close(); count++; if( null != program.getChannelInfo() ) { String[] channelProjection = new String[] { ChannelConstants._ID }; String channelSelection = ChannelConstants.FIELD_CHAN_ID + " = ?"; channelSelection = appendLocationHostname( context, locationProfile, channelSelection, null ); ContentValues channelValues = ChannelDaoHelper.convertChannelInfoToContentValues( locationProfile, lastModified, program.getChannelInfo() ); Cursor channelCursor = context.getContentResolver().query( ChannelConstants.CONTENT_URI, channelProjection, channelSelection, new String[] { String.valueOf( program.getChannelInfo().getChannelId() ) }, null ); if( !channelCursor.moveToFirst() ) { // Log.v( TAG, "load : adding channel " + program.getChannelInfo().getChannelId() ); // catch all for channels not in regular linups (i.e. added as a result of integrating miro bridge) ops.add( ContentProviderOperation.newInsert( ChannelConstants.CONTENT_URI ) .withValues( channelValues ) .withYieldAllowed( true ) .build() ); count++; } channelCursor.close(); } if( !inError && null != program.getRecording() ) { if( program.getRecording().getRecordId() < 0 ) { String[] recordingProjection = new String[] { details.getTableName() + "_" + RecordingConstants._ID }; String recordingSelection = RecordingConstants.FIELD_RECORD_ID + " = ? AND " + RecordingConstants.FIELD_START_TIME + " = ? AND " + RecordingConstants.FIELD_MASTER_HOSTNAME + " = ?"; String[] recordingSelectionArgs = new String[] { String.valueOf( program.getRecording().getRecordId() ), String.valueOf( program.getStartTime().getMillis() ), locationProfile.getHostname() }; //Log.v( TAG, "load : recording=" + program.getRecording().toString() ); ContentValues recordingValues = RecordingDaoHelper.convertRecordingToContentValues( locationProfile, lastModified, program.getStartTime(), program.getRecording() ); Cursor recordingCursor = context.getContentResolver().query( details.getContentUri(), recordingProjection, recordingSelection, recordingSelectionArgs, null ); if( recordingCursor.moveToFirst() ) { //Log.v( TAG, "load : UPDATE RECORDING " + count + ":" + program.getTitle() + ", recording=" + program.getRecording().getRecordId() ); Long id = recordingCursor.getLong( recordingCursor.getColumnIndexOrThrow( details.getTableName() + "_" + RecordingConstants._ID ) ); ops.add( ContentProviderOperation.newUpdate( ContentUris.withAppendedId( details.getContentUri(), id ) ) .withValues( recordingValues ) .withYieldAllowed( true ) .build() ); } else { //Log.v( TAG, "load : INSERT RECORDING " + count + ":" + program.getTitle() + ", recording=" + program.getRecording().getRecordId() ); ops.add( ContentProviderOperation.newInsert( details.getContentUri() ) .withValues( recordingValues ) .withYieldAllowed( true ) .build() ); } recordingCursor.close(); count++; } } if( count > 100 ) { // Log.i( TAG, "load : applying batch for '" + count + "' transactions, processing programs" ); if( !ops.isEmpty() ) { // Log.v( TAG, "load : applying batch" ); ContentProviderResult[] results = context.getContentResolver().applyBatch( MythtvProvider.AUTHORITY, ops ); loaded += results.length; if( results.length > 0 ) { ops.clear(); // for( ContentProviderResult result : results ) { // Log.i( TAG, "load : batch result=" + result.toString() ); // } } } count = 0; } } if( !ops.isEmpty() ) { // Log.i( TAG, "load : applying final batch for '" + count + "' transactions, after processing programs" ); ContentProviderResult[] results = context.getContentResolver().applyBatch( MythtvProvider.AUTHORITY, ops ); loaded += results.length; if( results.length > 0 ) { ops.clear(); // for( ContentProviderResult result : results ) { // Log.i( TAG, "load : batch result=" + result.toString() ); // } } count = 0; } // Log.v( TAG, "load : remove deleted recordings" ); if( table.equals( ProgramConstants.TABLE_NAME_RECORDED ) ) { String deletedSelection = table + "." + ProgramConstants.FIELD_LAST_MODIFIED + " < ?"; String[] deletedSelectionArgs = new String[] { String.valueOf( today.getMillis() ) }; List<Program> deleted = findAll( context, uri, null, deletedSelection, deletedSelectionArgs, null, table ); for( Program program : deleted ) { // Log.v( TAG, "load : remove deleted recording - " + program.getTitle() + " [" + program.getSubTitle() + "]" ); // Delete any live stream details LiveStreamInfo liveStreamInfo = mLiveStreamDaoHelper.findByProgram( context, locationProfile, program ); if( null != liveStreamInfo ) { // Log.v( TAG, "load : remove live stream" ); RemoveStreamTask removeStreamTask = new RemoveStreamTask(); removeStreamTask.setContext( context ); removeStreamTask.setLocationProfile( locationProfile ); removeStreamTask.execute( liveStreamInfo ); } } } // Log.v( TAG, "load : DELETE PROGRAMS" ); ops.add( ContentProviderOperation.newDelete( uri ) .withSelection( table + "." + ProgramConstants.FIELD_LAST_MODIFIED_DATE + " < ?", new String[] { String.valueOf( today.getMillis() ) } ) .withYieldAllowed( true ) .build() ); // Log.v( TAG, "load : DELETE RECORDINGS" ); ops.add( ContentProviderOperation.newDelete( details.getContentUri() ) .withSelection( details.getTableName() + "." + RecordingConstants.FIELD_LAST_MODIFIED_DATE + " < ?", new String[] { String.valueOf( today.getMillis() ) } ) .withYieldAllowed( true ) .build() ); if( !ops.isEmpty() ) { // Log.i( TAG, "load : applying final batch for '" + count + "' transactions, final batch" ); ContentProviderResult[] results = context.getContentResolver().applyBatch( MythtvProvider.AUTHORITY, ops ); loaded += results.length; if( results.length > 0 ) { ops.clear(); // for( ContentProviderResult result : results ) { // Log.i( TAG, "load : batch result=" + result.toString() ); // } } } // Log.v( TAG, "load : exit" ); return loaded; } /** * @param programs * @return */ public abstract int load( final Context context, final LocationProfile locationProfile, List<Program> programs ) throws RemoteException, OperationApplicationException; /** * @param cursor * @return */ public static Program convertCursorToProgram( Cursor cursor, final String table ) { // Log.v( TAG, "convertCursorToProgram : enter" ); // Long id = null; DateTime startTime = null, endTime = null, lastModified = null, airDate = null; String title = "", subTitle = "", category = "", categoryType = "", seriesId = "", programId = "", fileSize = "", programFlags = "", hostname = "", filename = "", description = "", inetref = "", season = "", episode = "", masterHostname = ""; int repeat = -1, videoProps = -1, audioProps = -1, subProps = -1; float stars = 0.0f; ChannelInfo channelInfo = null; Recording recording = null; LiveStreamInfo liveStreamInfo = null; // if( cursor.getColumnIndex( ProgramConstants._ID ) != -1 ) { // id = cursor.getLong( cursor.getColumnIndex( ProgramConstants._ID ) ); // } if( cursor.getColumnIndex( ProgramConstants.FIELD_START_TIME ) != -1 ) { startTime = new DateTime( cursor.getLong( cursor.getColumnIndex( ProgramConstants.FIELD_START_TIME ) ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_END_TIME ) != -1 ) { endTime = new DateTime( cursor.getLong( cursor.getColumnIndex( ProgramConstants.FIELD_END_TIME ) ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_TITLE ) != -1 ) { title = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_TITLE ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_SUB_TITLE ) != -1 ) { subTitle = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_SUB_TITLE ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_CATEGORY ) != -1 ) { category = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_CATEGORY ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_CATEGORY_TYPE ) != -1 ) { categoryType = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_CATEGORY_TYPE ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_REPEAT ) != -1 ) { repeat = cursor.getInt( cursor.getColumnIndex( ProgramConstants.FIELD_REPEAT ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_VIDEO_PROPS ) != -1 ) { videoProps = cursor.getInt( cursor.getColumnIndex( ProgramConstants.FIELD_VIDEO_PROPS ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_AUDIO_PROPS ) != -1 ) { audioProps = cursor.getInt( cursor.getColumnIndex( ProgramConstants.FIELD_AUDIO_PROPS ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_SUB_PROPS ) != -1 ) { subProps = cursor.getInt( cursor.getColumnIndex( ProgramConstants.FIELD_SUB_PROPS ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_SERIES_ID ) != -1 ) { seriesId = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_SERIES_ID ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_PROGRAM_ID ) != -1 ) { programId = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_PROGRAM_ID ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_STARS ) != -1 ) { stars = cursor.getFloat( cursor.getColumnIndex( ProgramConstants.FIELD_STARS ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_FILE_SIZE ) != -1 ) { fileSize = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_FILE_SIZE ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_LAST_MODIFIED ) != -1 ) { lastModified = new DateTime( cursor.getLong( cursor.getColumnIndex( ProgramConstants.FIELD_LAST_MODIFIED ) ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_PROGRAM_FLAGS ) != -1 ) { programFlags = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_PROGRAM_FLAGS ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_HOSTNAME ) != -1 ) { hostname = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_HOSTNAME ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_FILENAME ) != -1 ) { filename = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_FILENAME ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_AIR_DATE ) != -1 ) { airDate = new DateTime( cursor.getLong( cursor.getColumnIndex( ProgramConstants.FIELD_AIR_DATE ) ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_DESCRIPTION ) != -1 ) { description = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_DESCRIPTION ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_INETREF ) != -1 ) { inetref = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_INETREF ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_SEASON ) != -1 ) { season = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_SEASON ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_EPISODE ) != -1 ) { episode = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_EPISODE ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_MASTER_HOSTNAME ) != -1 ) { masterHostname = cursor.getString( cursor.getColumnIndex( ProgramConstants.FIELD_MASTER_HOSTNAME ) ); } if( cursor.getColumnIndex( ProgramConstants.FIELD_CHANNEL_ID ) != -1 ) { channelInfo = ChannelDaoHelper.convertCursorToChannelInfo( cursor ); } if( cursor.getColumnIndex( RecordingConstants.ContentDetails.getValueFromParent( table ).getTableName() + "_" + RecordingConstants.FIELD_RECORD_ID ) != -1 ) { recording = RecordingDaoHelper.convertCursorToRecording( cursor, table ); } if( cursor.getColumnIndex( LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants.FIELD_ID ) != -1 ) { liveStreamInfo = LiveStreamDaoHelper.convertCursorToLiveStreamInfo( cursor ); } Program program = new Program(); program.setStartTime( startTime ); program.setEndTime( endTime ); program.setTitle( title ); program.setSubTitle( subTitle ); program.setCategory( category ); program.setCategoryType( categoryType ); program.setRepeat( repeat == 1 ? true : false ); program.setVideoProps( videoProps ); program.setAudioProps( audioProps ); program.setSubProps( subProps ); program.setSeriesId( seriesId ); program.setProgramId( programId ); program.setStars( stars ); program.setFileSize( fileSize ); program.setLastModified( lastModified ); program.setProgramFlags( programFlags ); program.setHostname( hostname ); program.setFilename( filename ); program.setAirDate( airDate ); program.setDescription( description ); program.setInetref( inetref ); program.setSeason( season ); program.setEpisode( episode ); program.setChannelInfo( channelInfo ); program.setRecording( recording ); // program.set; // program.set; // Log.v( TAG, "convertCursorToProgram : id=" + id + ", program=" + program.toString() ); // Log.v( TAG, "convertCursorToProgram : exit" ); return program; } protected static ContentValues[] convertProgramsToContentValuesArray( final LocationProfile locationProfile, final DateTime lastModified, final List<Program> programs ) { // Log.v( TAG, "convertProgramsToContentValuesArray : enter" ); if( null != programs && !programs.isEmpty() ) { ContentValues contentValues; List<ContentValues> contentValuesArray = new ArrayList<ContentValues>(); for( Program program : programs ) { contentValues = convertProgramToContentValues( locationProfile, lastModified, program ); contentValuesArray.add( contentValues ); } if( !contentValuesArray.isEmpty() ) { // Log.v( TAG, "convertProgramsToContentValuesArray : exit" ); return contentValuesArray.toArray( new ContentValues[ contentValuesArray.size() ] ); } } // Log.v( TAG, "convertProgramsToContentValuesArray : exit, no programs to convert" ); return null; } protected static ContentValues convertProgramToContentValues( final LocationProfile locationProfile, final DateTime lastModified, final Program program ) { boolean inError; DateTime startTime = DateUtils.convertUtc( new DateTime( System.currentTimeMillis() ) ); DateTime endTime = DateUtils.convertUtc( new DateTime( System.currentTimeMillis() ) ); // If one timestamp is bad, leave them both set to 0. if( null == program.getStartTime() || null == program.getEndTime() ) { // Log.w(TAG, "convertProgramToContentValues : null starttime and or endtime" ); inError = true; } else { startTime = program.getStartTime(); endTime = program.getEndTime(); inError = false; } ContentValues values = new ContentValues(); values.put( ProgramConstants.FIELD_START_TIME, startTime.getMillis() ); values.put( ProgramConstants.FIELD_END_TIME, endTime.getMillis() ); values.put( ProgramConstants.FIELD_TITLE, null != program.getTitle() ? program.getTitle() : "" ); values.put( ProgramConstants.FIELD_SUB_TITLE, null != program.getSubTitle() ? program.getSubTitle() : "" ); values.put( ProgramConstants.FIELD_CATEGORY, null != program.getCategory() ? program.getCategory() : "" ); values.put( ProgramConstants.FIELD_CATEGORY_TYPE, null != program.getCategoryType() ? program.getCategoryType() : "" ); values.put( ProgramConstants.FIELD_REPEAT, program.isRepeat() ? 1 : 0 ); values.put( ProgramConstants.FIELD_VIDEO_PROPS, program.getVideoProps() ); values.put( ProgramConstants.FIELD_AUDIO_PROPS, program.getAudioProps() ); values.put( ProgramConstants.FIELD_SUB_PROPS, program.getSubProps() ); values.put( ProgramConstants.FIELD_SERIES_ID, null != program.getSeriesId() ? program.getSeriesId() : "" ); values.put( ProgramConstants.FIELD_PROGRAM_ID, null != program.getProgramId() ? program.getProgramId() : "" ); values.put( ProgramConstants.FIELD_STARS, program.getStars() ); values.put( ProgramConstants.FIELD_FILE_SIZE, null != program.getFileSize() ? program.getFileSize() : "" ); values.put( ProgramConstants.FIELD_LAST_MODIFIED, null != program.getLastModified() ? DateUtils.dateTimeFormatter.print( program.getLastModified() ) : "" ); values.put( ProgramConstants.FIELD_PROGRAM_FLAGS, null != program.getProgramFlags() ? program.getProgramFlags() : "" ); values.put( ProgramConstants.FIELD_HOSTNAME, null != program.getHostname() ? program.getHostname() : "" ); values.put( ProgramConstants.FIELD_FILENAME, null != program.getFilename() ? program.getFilename() : "" ); values.put( ProgramConstants.FIELD_AIR_DATE, null != program.getAirDate() ? DateUtils.dateTimeFormatter.print( program.getAirDate() ) : "" ); values.put( ProgramConstants.FIELD_DESCRIPTION, null != program.getDescription() ? program.getDescription() : "" ); values.put( ProgramConstants.FIELD_INETREF, null != program.getInetref() ? program.getInetref() : "" ); values.put( ProgramConstants.FIELD_SEASON, null != program.getSeason() ? program.getSeason() : "" ); values.put( ProgramConstants.FIELD_EPISODE, null != program.getEpisode() ? program.getEpisode() : "" ); values.put( ProgramConstants.FIELD_CHANNEL_ID, null != program.getChannelInfo() ? program.getChannelInfo().getChannelId() : -1 ); values.put( ProgramConstants.FIELD_RECORD_ID, null != program.getRecording() ? program.getRecording().getRecordId() : -1 ); values.put( ProgramConstants.FIELD_IN_ERROR, inError ? 1 : 0 ); values.put( ProgramConstants.FIELD_MASTER_HOSTNAME, locationProfile.getHostname() ); values.put( ProgramConstants.FIELD_LAST_MODIFIED_DATE, lastModified.getMillis() ); return values; } private class RemoveStreamTask extends AsyncTask<LiveStreamInfo, Void, ResponseEntity<Bool>> { private Context mContext; private LocationProfile mLocationProfile; private Exception e = null; @Override protected ResponseEntity<Bool> doInBackground( LiveStreamInfo... params ) { // Log.v( TAG, "RemoveStreamTask : enter" ); if( null == mContext ) throw new RuntimeException( "RemoveStreamTask not initalized!" ); try { // Log.v( TAG, "RemoveStreamTask : api" ); LiveStreamInfo liveStreamInfo = params[ 0 ]; if( null != liveStreamInfo ) { return mMythtvServiceHelper.getMythServicesApi( mLocationProfile ).contentOperations().removeLiveStream( liveStreamInfo.getId() ); } } catch( Exception e ) { // Log.v( TAG, "RemoveStreamTask : error" ); this.e = e; } // Log.v( TAG, "RemoveStreamTask : exit" ); return null; } @Override protected void onPostExecute( ResponseEntity<Bool> result ) { // Log.v( TAG, "RemoveStreamTask onPostExecute : enter" ); if( null == e ) { // Log.v( TAG, "RemoveStreamTask onPostExecute : no error occurred" ); if( null != result ) { // if( result.getBody().getBool().booleanValue() ) { // Log.v( TAG, "RemoveStreamTask onPostExecute : live stream removed" ); // } } // } else { // Log.e( TAG, "error removing live stream", e ); } // Log.v( TAG, "RemoveStreamTask onPostExecute : exit" ); } public void setContext( Context context ) { this.mContext = context; } public void setLocationProfile( LocationProfile locationProfile ) { this.mLocationProfile = locationProfile; } } }
true
true
protected int load( final Context context, final Uri uri, final LocationProfile locationProfile, List<Program> programs, String table ) throws RemoteException, OperationApplicationException { // Log.v( TAG, "load : enter" ); if( null == context ) throw new RuntimeException( "ProgramDaoHelper is not initialized" ); DateTime today = new DateTime( DateTimeZone.UTC ).withTimeAtStartOfDay(); DateTime lastModified = new DateTime( DateTimeZone.UTC ); // Log.v( TAG, "load : find all existing recordings, table=" + table ); String recordedSelection = ""; recordedSelection = appendLocationHostname( context, locationProfile, recordedSelection, table ); // Log.v( TAG, "load : recordedSelection=" + recordedSelection ); int loaded = -1; int count = 0; ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); String[] programProjection = new String[] { ProgramConstants._ID }; String programSelection = table + "." + ProgramConstants.FIELD_CHANNEL_ID + " = ? AND " + table + "." + ProgramConstants.FIELD_START_TIME + " = ?"; programSelection = appendLocationHostname( context, locationProfile, programSelection, table ); boolean inError; RecordingConstants.ContentDetails details = RecordingConstants.ContentDetails.getValueFromParent( table ); Log.w(TAG, "load : details - parent=" + details.getParent() + ", tableName=" + details.getTableName() + ", contentUri=" + details.getContentUri().toString() ); for( Program program : programs ) { if( null == program.getStartTime() || null == program.getEndTime() ) { // Log.w(TAG, "load : null starttime and or endtime" ); inError = true; } else { inError = false; } DateTime startTime = new DateTime( program.getStartTime() ); ContentValues programValues = convertProgramToContentValues( locationProfile, lastModified, program ); Cursor programCursor = context.getContentResolver().query( uri, programProjection, programSelection, new String[] { String.valueOf( program.getChannelInfo().getChannelId() ), String.valueOf( startTime.getMillis() ) }, null ); if( programCursor.moveToFirst() ) { // Log.v( TAG, "load : UPDATE PROGRAM " + count + ":" + program.getChannelInfo().getChannelId() + ":" + program.getStartTime() + ":" + program.getHostname() ); Long id = programCursor.getLong( programCursor.getColumnIndexOrThrow( ProgramConstants._ID ) ); ops.add( ContentProviderOperation.newUpdate( ContentUris.withAppendedId( uri, id ) ) .withValues( programValues ) .withYieldAllowed( true ) .build() ); } else { // Log.v( TAG, "load : INSERT PROGRAM " + count + ":" + program.getChannelInfo().getChannelId() + ":" + program.getStartTime() + ":" + program.getHostname() ); ops.add( ContentProviderOperation.newInsert( uri ) .withValues( programValues ) .withYieldAllowed( true ) .build() ); } programCursor.close(); count++; if( null != program.getChannelInfo() ) { String[] channelProjection = new String[] { ChannelConstants._ID }; String channelSelection = ChannelConstants.FIELD_CHAN_ID + " = ?"; channelSelection = appendLocationHostname( context, locationProfile, channelSelection, null ); ContentValues channelValues = ChannelDaoHelper.convertChannelInfoToContentValues( locationProfile, lastModified, program.getChannelInfo() ); Cursor channelCursor = context.getContentResolver().query( ChannelConstants.CONTENT_URI, channelProjection, channelSelection, new String[] { String.valueOf( program.getChannelInfo().getChannelId() ) }, null ); if( !channelCursor.moveToFirst() ) { // Log.v( TAG, "load : adding channel " + program.getChannelInfo().getChannelId() ); // catch all for channels not in regular linups (i.e. added as a result of integrating miro bridge) ops.add( ContentProviderOperation.newInsert( ChannelConstants.CONTENT_URI ) .withValues( channelValues ) .withYieldAllowed( true ) .build() ); count++; } channelCursor.close(); } if( !inError && null != program.getRecording() ) { if( program.getRecording().getRecordId() < 0 ) { String[] recordingProjection = new String[] { details.getTableName() + "_" + RecordingConstants._ID }; String recordingSelection = RecordingConstants.FIELD_RECORD_ID + " = ? AND " + RecordingConstants.FIELD_START_TIME + " = ? AND " + RecordingConstants.FIELD_MASTER_HOSTNAME + " = ?"; String[] recordingSelectionArgs = new String[] { String.valueOf( program.getRecording().getRecordId() ), String.valueOf( program.getStartTime().getMillis() ), locationProfile.getHostname() }; //Log.v( TAG, "load : recording=" + program.getRecording().toString() ); ContentValues recordingValues = RecordingDaoHelper.convertRecordingToContentValues( locationProfile, lastModified, program.getStartTime(), program.getRecording() ); Cursor recordingCursor = context.getContentResolver().query( details.getContentUri(), recordingProjection, recordingSelection, recordingSelectionArgs, null ); if( recordingCursor.moveToFirst() ) { //Log.v( TAG, "load : UPDATE RECORDING " + count + ":" + program.getTitle() + ", recording=" + program.getRecording().getRecordId() ); Long id = recordingCursor.getLong( recordingCursor.getColumnIndexOrThrow( details.getTableName() + "_" + RecordingConstants._ID ) ); ops.add( ContentProviderOperation.newUpdate( ContentUris.withAppendedId( details.getContentUri(), id ) ) .withValues( recordingValues ) .withYieldAllowed( true ) .build() ); } else { //Log.v( TAG, "load : INSERT RECORDING " + count + ":" + program.getTitle() + ", recording=" + program.getRecording().getRecordId() ); ops.add( ContentProviderOperation.newInsert( details.getContentUri() ) .withValues( recordingValues ) .withYieldAllowed( true ) .build() ); } recordingCursor.close(); count++; } } if( count > 100 ) { // Log.i( TAG, "load : applying batch for '" + count + "' transactions, processing programs" ); if( !ops.isEmpty() ) { // Log.v( TAG, "load : applying batch" ); ContentProviderResult[] results = context.getContentResolver().applyBatch( MythtvProvider.AUTHORITY, ops ); loaded += results.length; if( results.length > 0 ) { ops.clear(); // for( ContentProviderResult result : results ) { // Log.i( TAG, "load : batch result=" + result.toString() ); // } } } count = 0; } } if( !ops.isEmpty() ) { // Log.i( TAG, "load : applying final batch for '" + count + "' transactions, after processing programs" ); ContentProviderResult[] results = context.getContentResolver().applyBatch( MythtvProvider.AUTHORITY, ops ); loaded += results.length; if( results.length > 0 ) { ops.clear(); // for( ContentProviderResult result : results ) { // Log.i( TAG, "load : batch result=" + result.toString() ); // } } count = 0; } // Log.v( TAG, "load : remove deleted recordings" ); if( table.equals( ProgramConstants.TABLE_NAME_RECORDED ) ) { String deletedSelection = table + "." + ProgramConstants.FIELD_LAST_MODIFIED + " < ?"; String[] deletedSelectionArgs = new String[] { String.valueOf( today.getMillis() ) }; List<Program> deleted = findAll( context, uri, null, deletedSelection, deletedSelectionArgs, null, table ); for( Program program : deleted ) { // Log.v( TAG, "load : remove deleted recording - " + program.getTitle() + " [" + program.getSubTitle() + "]" ); // Delete any live stream details LiveStreamInfo liveStreamInfo = mLiveStreamDaoHelper.findByProgram( context, locationProfile, program ); if( null != liveStreamInfo ) { // Log.v( TAG, "load : remove live stream" ); RemoveStreamTask removeStreamTask = new RemoveStreamTask(); removeStreamTask.setContext( context ); removeStreamTask.setLocationProfile( locationProfile ); removeStreamTask.execute( liveStreamInfo ); } } } // Log.v( TAG, "load : DELETE PROGRAMS" ); ops.add( ContentProviderOperation.newDelete( uri ) .withSelection( table + "." + ProgramConstants.FIELD_LAST_MODIFIED_DATE + " < ?", new String[] { String.valueOf( today.getMillis() ) } ) .withYieldAllowed( true ) .build() ); // Log.v( TAG, "load : DELETE RECORDINGS" ); ops.add( ContentProviderOperation.newDelete( details.getContentUri() ) .withSelection( details.getTableName() + "." + RecordingConstants.FIELD_LAST_MODIFIED_DATE + " < ?", new String[] { String.valueOf( today.getMillis() ) } ) .withYieldAllowed( true ) .build() ); if( !ops.isEmpty() ) { // Log.i( TAG, "load : applying final batch for '" + count + "' transactions, final batch" ); ContentProviderResult[] results = context.getContentResolver().applyBatch( MythtvProvider.AUTHORITY, ops ); loaded += results.length; if( results.length > 0 ) { ops.clear(); // for( ContentProviderResult result : results ) { // Log.i( TAG, "load : batch result=" + result.toString() ); // } } } // Log.v( TAG, "load : exit" ); return loaded; }
protected int load( final Context context, final Uri uri, final LocationProfile locationProfile, List<Program> programs, String table ) throws RemoteException, OperationApplicationException { // Log.v( TAG, "load : enter" ); if( null == context ) throw new RuntimeException( "ProgramDaoHelper is not initialized" ); DateTime today = new DateTime( DateTimeZone.UTC ).withTimeAtStartOfDay(); DateTime lastModified = new DateTime( DateTimeZone.UTC ); // Log.v( TAG, "load : find all existing recordings, table=" + table ); String recordedSelection = ""; recordedSelection = appendLocationHostname( context, locationProfile, recordedSelection, table ); // Log.v( TAG, "load : recordedSelection=" + recordedSelection ); int loaded = -1; int count = 0; ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); String[] programProjection = new String[] { ProgramConstants._ID }; String programSelection = table + "." + ProgramConstants.FIELD_CHANNEL_ID + " = ? AND " + table + "." + ProgramConstants.FIELD_START_TIME + " = ?"; programSelection = appendLocationHostname( context, locationProfile, programSelection, table ); boolean inError; RecordingConstants.ContentDetails details = RecordingConstants.ContentDetails.getValueFromParent( table ); // Log.w(TAG, "load : details - parent=" + details.getParent() + ", tableName=" + details.getTableName() + ", contentUri=" + details.getContentUri().toString() ); for( Program program : programs ) { if( null == program.getStartTime() || null == program.getEndTime() ) { // Log.w(TAG, "load : null starttime and or endtime" ); inError = true; } else { inError = false; } DateTime startTime = new DateTime( program.getStartTime() ); ContentValues programValues = convertProgramToContentValues( locationProfile, lastModified, program ); Cursor programCursor = context.getContentResolver().query( uri, programProjection, programSelection, new String[] { String.valueOf( program.getChannelInfo().getChannelId() ), String.valueOf( startTime.getMillis() ) }, null ); if( programCursor.moveToFirst() ) { // Log.v( TAG, "load : UPDATE PROGRAM " + count + ":" + program.getChannelInfo().getChannelId() + ":" + program.getStartTime() + ":" + program.getHostname() ); Long id = programCursor.getLong( programCursor.getColumnIndexOrThrow( ProgramConstants._ID ) ); ops.add( ContentProviderOperation.newUpdate( ContentUris.withAppendedId( uri, id ) ) .withValues( programValues ) .withYieldAllowed( true ) .build() ); } else { // Log.v( TAG, "load : INSERT PROGRAM " + count + ":" + program.getChannelInfo().getChannelId() + ":" + program.getStartTime() + ":" + program.getHostname() ); ops.add( ContentProviderOperation.newInsert( uri ) .withValues( programValues ) .withYieldAllowed( true ) .build() ); } programCursor.close(); count++; if( null != program.getChannelInfo() ) { String[] channelProjection = new String[] { ChannelConstants._ID }; String channelSelection = ChannelConstants.FIELD_CHAN_ID + " = ?"; channelSelection = appendLocationHostname( context, locationProfile, channelSelection, null ); ContentValues channelValues = ChannelDaoHelper.convertChannelInfoToContentValues( locationProfile, lastModified, program.getChannelInfo() ); Cursor channelCursor = context.getContentResolver().query( ChannelConstants.CONTENT_URI, channelProjection, channelSelection, new String[] { String.valueOf( program.getChannelInfo().getChannelId() ) }, null ); if( !channelCursor.moveToFirst() ) { // Log.v( TAG, "load : adding channel " + program.getChannelInfo().getChannelId() ); // catch all for channels not in regular linups (i.e. added as a result of integrating miro bridge) ops.add( ContentProviderOperation.newInsert( ChannelConstants.CONTENT_URI ) .withValues( channelValues ) .withYieldAllowed( true ) .build() ); count++; } channelCursor.close(); } if( !inError && null != program.getRecording() ) { if( program.getRecording().getRecordId() < 0 ) { String[] recordingProjection = new String[] { details.getTableName() + "_" + RecordingConstants._ID }; String recordingSelection = RecordingConstants.FIELD_RECORD_ID + " = ? AND " + RecordingConstants.FIELD_START_TIME + " = ? AND " + RecordingConstants.FIELD_MASTER_HOSTNAME + " = ?"; String[] recordingSelectionArgs = new String[] { String.valueOf( program.getRecording().getRecordId() ), String.valueOf( program.getStartTime().getMillis() ), locationProfile.getHostname() }; //Log.v( TAG, "load : recording=" + program.getRecording().toString() ); ContentValues recordingValues = RecordingDaoHelper.convertRecordingToContentValues( locationProfile, lastModified, program.getStartTime(), program.getRecording() ); Cursor recordingCursor = context.getContentResolver().query( details.getContentUri(), recordingProjection, recordingSelection, recordingSelectionArgs, null ); if( recordingCursor.moveToFirst() ) { //Log.v( TAG, "load : UPDATE RECORDING " + count + ":" + program.getTitle() + ", recording=" + program.getRecording().getRecordId() ); Long id = recordingCursor.getLong( recordingCursor.getColumnIndexOrThrow( details.getTableName() + "_" + RecordingConstants._ID ) ); ops.add( ContentProviderOperation.newUpdate( ContentUris.withAppendedId( details.getContentUri(), id ) ) .withValues( recordingValues ) .withYieldAllowed( true ) .build() ); } else { //Log.v( TAG, "load : INSERT RECORDING " + count + ":" + program.getTitle() + ", recording=" + program.getRecording().getRecordId() ); ops.add( ContentProviderOperation.newInsert( details.getContentUri() ) .withValues( recordingValues ) .withYieldAllowed( true ) .build() ); } recordingCursor.close(); count++; } } if( count > 100 ) { // Log.i( TAG, "load : applying batch for '" + count + "' transactions, processing programs" ); if( !ops.isEmpty() ) { // Log.v( TAG, "load : applying batch" ); ContentProviderResult[] results = context.getContentResolver().applyBatch( MythtvProvider.AUTHORITY, ops ); loaded += results.length; if( results.length > 0 ) { ops.clear(); // for( ContentProviderResult result : results ) { // Log.i( TAG, "load : batch result=" + result.toString() ); // } } } count = 0; } } if( !ops.isEmpty() ) { // Log.i( TAG, "load : applying final batch for '" + count + "' transactions, after processing programs" ); ContentProviderResult[] results = context.getContentResolver().applyBatch( MythtvProvider.AUTHORITY, ops ); loaded += results.length; if( results.length > 0 ) { ops.clear(); // for( ContentProviderResult result : results ) { // Log.i( TAG, "load : batch result=" + result.toString() ); // } } count = 0; } // Log.v( TAG, "load : remove deleted recordings" ); if( table.equals( ProgramConstants.TABLE_NAME_RECORDED ) ) { String deletedSelection = table + "." + ProgramConstants.FIELD_LAST_MODIFIED + " < ?"; String[] deletedSelectionArgs = new String[] { String.valueOf( today.getMillis() ) }; List<Program> deleted = findAll( context, uri, null, deletedSelection, deletedSelectionArgs, null, table ); for( Program program : deleted ) { // Log.v( TAG, "load : remove deleted recording - " + program.getTitle() + " [" + program.getSubTitle() + "]" ); // Delete any live stream details LiveStreamInfo liveStreamInfo = mLiveStreamDaoHelper.findByProgram( context, locationProfile, program ); if( null != liveStreamInfo ) { // Log.v( TAG, "load : remove live stream" ); RemoveStreamTask removeStreamTask = new RemoveStreamTask(); removeStreamTask.setContext( context ); removeStreamTask.setLocationProfile( locationProfile ); removeStreamTask.execute( liveStreamInfo ); } } } // Log.v( TAG, "load : DELETE PROGRAMS" ); ops.add( ContentProviderOperation.newDelete( uri ) .withSelection( table + "." + ProgramConstants.FIELD_LAST_MODIFIED_DATE + " < ?", new String[] { String.valueOf( today.getMillis() ) } ) .withYieldAllowed( true ) .build() ); // Log.v( TAG, "load : DELETE RECORDINGS" ); ops.add( ContentProviderOperation.newDelete( details.getContentUri() ) .withSelection( details.getTableName() + "." + RecordingConstants.FIELD_LAST_MODIFIED_DATE + " < ?", new String[] { String.valueOf( today.getMillis() ) } ) .withYieldAllowed( true ) .build() ); if( !ops.isEmpty() ) { // Log.i( TAG, "load : applying final batch for '" + count + "' transactions, final batch" ); ContentProviderResult[] results = context.getContentResolver().applyBatch( MythtvProvider.AUTHORITY, ops ); loaded += results.length; if( results.length > 0 ) { ops.clear(); // for( ContentProviderResult result : results ) { // Log.i( TAG, "load : batch result=" + result.toString() ); // } } } // Log.v( TAG, "load : exit" ); return loaded; }
diff --git a/src/nl/sense_os/commonsense/client/auth/login/LoginForm.java b/src/nl/sense_os/commonsense/client/auth/login/LoginForm.java index 39c2e56b..7c9071ab 100644 --- a/src/nl/sense_os/commonsense/client/auth/login/LoginForm.java +++ b/src/nl/sense_os/commonsense/client/auth/login/LoginForm.java @@ -1,191 +1,192 @@ package nl.sense_os.commonsense.client.auth.login; import java.util.logging.Logger; import nl.sense_os.commonsense.client.common.utility.SenseIconProvider; import com.extjs.gxt.ui.client.Style.Orientation; import com.extjs.gxt.ui.client.Style.Scroll; import com.extjs.gxt.ui.client.event.ButtonEvent; import com.extjs.gxt.ui.client.event.ComponentEvent; import com.extjs.gxt.ui.client.event.KeyListener; import com.extjs.gxt.ui.client.event.SelectionListener; import com.extjs.gxt.ui.client.widget.LayoutContainer; import com.extjs.gxt.ui.client.widget.button.Button; import com.extjs.gxt.ui.client.widget.form.CheckBox; import com.extjs.gxt.ui.client.widget.form.FormButtonBinding; import com.extjs.gxt.ui.client.widget.form.FormPanel; import com.extjs.gxt.ui.client.widget.form.LabelField; import com.extjs.gxt.ui.client.widget.form.TextField; import com.extjs.gxt.ui.client.widget.layout.FormData; import com.extjs.gxt.ui.client.widget.layout.HBoxLayout; import com.extjs.gxt.ui.client.widget.layout.HBoxLayout.HBoxLayoutAlign; import com.extjs.gxt.ui.client.widget.layout.HBoxLayoutData; import com.extjs.gxt.ui.client.widget.layout.RowLayout; import com.google.gwt.event.dom.client.KeyCodes; public class LoginForm extends FormPanel { private static final Logger LOG = Logger.getLogger(LoginForm.class.getName()); private TextField<String> username; private TextField<String> password; private CheckBox chkRememberMe; private Button btnSubmit; private Button btnGoogle; private LabelField btnForgotPassword; public LoginForm() { super(); setHeading("Login"); setScrollMode(Scroll.AUTOY); setSize("", "auto"); setLabelAlign(LabelAlign.TOP); initFields(); initButtons(); } public LabelField getBtnForgotPassword() { return btnForgotPassword; } public Button getBtnGoogle() { return btnGoogle; } public Button getBtnSubmit() { return btnSubmit; } public String getPassword() { return password.getValue(); } public String getUsername() { return username.getValue(); } private void initButtons() { btnForgotPassword = new LabelField("Forgot your password?"); btnForgotPassword.setHideLabel(true); btnForgotPassword.setStyleAttribute("cursor", "pointer"); // btnSubmit button btnSubmit = new Button("Log in"); btnSubmit.setIconStyle("sense-btn-icon-go"); // btnSubmit.setType("submit"); // "submit" type makes the button always clickable! new FormButtonBinding(this).addButton(btnSubmit); btnSubmit.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { if (isValid()) { submit(); } } }); LayoutContainer submitWrapper = new LayoutContainer(new RowLayout(Orientation.HORIZONTAL)); submitWrapper.setSize("100%", "34px"); HBoxLayout wrapperLayout = new HBoxLayout(); wrapperLayout.setHBoxLayoutAlign(HBoxLayoutAlign.MIDDLE); submitWrapper.setLayout(wrapperLayout); - submitWrapper.add(btnSubmit, new HBoxLayoutData()); + submitWrapper.add(btnSubmit); + btnSubmit.setWidth("75px"); submitWrapper.add(btnForgotPassword, new HBoxLayoutData(0, 0, 0, 10)); // btnGoogle login button btnGoogle = new Button("Log in with Google", SenseIconProvider.ICON_GOOGLE); this.add(submitWrapper, new FormData("-10")); LabelField alternative = new LabelField( "Alternatively, you can use your Google Account to log in:"); // alternative.setHideLabel(true); this.add(alternative, new FormData("-10")); add(btnGoogle); setupSubmit(); } private void initFields() { // username field username = new TextField<String>(); username.setFieldLabel("Username"); username.setAllowBlank(false); // password field password = new TextField<String>(); password.setFieldLabel("Password"); password.setAllowBlank(false); password.setPassword(true); // remember me check box chkRememberMe = new CheckBox(); chkRememberMe.setHideLabel(true); chkRememberMe.setBoxLabel("Remember username"); chkRememberMe.setValue(true); this.add(username, new FormData("-20")); this.add(password, new FormData("-20")); this.add(chkRememberMe, new FormData("-20")); } public boolean isRememberMe() { return chkRememberMe.getValue(); } public void setBusy(boolean busy) { if (busy) { btnSubmit.setIconStyle("sense-btn-icon-loading"); } else { btnSubmit.setIconStyle("sense-btn-icon-go"); } } public void setPassword(String password) { if (null != password) { this.password.setValue(password); } else { this.password.clear(); } } public void setRememberMe(boolean rememberMe) { chkRememberMe.setValue(rememberMe); } /** * Defines how to btnSubmit the form, and the actions to take when the form is submitted. */ private void setupSubmit() { // ENTER-key listener to btnSubmit the form using the keyboard final KeyListener submitListener = new KeyListener() { @Override public void componentKeyDown(ComponentEvent event) { if (event.getKeyCode() == KeyCodes.KEY_ENTER) { LOG.finest("Pressed enter to submit form"); if (isValid()) { submit(); } } } }; username.addKeyListener(submitListener); password.addKeyListener(submitListener); // form action is not a regular URL, but we listen for the btnSubmit event instead setAction("javascript:;"); } public void setUsername(String username) { if (null != username && !username.equalsIgnoreCase("null")) { this.username.setValue(username); } else { this.username.clear(); } } }
true
true
private void initButtons() { btnForgotPassword = new LabelField("Forgot your password?"); btnForgotPassword.setHideLabel(true); btnForgotPassword.setStyleAttribute("cursor", "pointer"); // btnSubmit button btnSubmit = new Button("Log in"); btnSubmit.setIconStyle("sense-btn-icon-go"); // btnSubmit.setType("submit"); // "submit" type makes the button always clickable! new FormButtonBinding(this).addButton(btnSubmit); btnSubmit.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { if (isValid()) { submit(); } } }); LayoutContainer submitWrapper = new LayoutContainer(new RowLayout(Orientation.HORIZONTAL)); submitWrapper.setSize("100%", "34px"); HBoxLayout wrapperLayout = new HBoxLayout(); wrapperLayout.setHBoxLayoutAlign(HBoxLayoutAlign.MIDDLE); submitWrapper.setLayout(wrapperLayout); submitWrapper.add(btnSubmit, new HBoxLayoutData()); submitWrapper.add(btnForgotPassword, new HBoxLayoutData(0, 0, 0, 10)); // btnGoogle login button btnGoogle = new Button("Log in with Google", SenseIconProvider.ICON_GOOGLE); this.add(submitWrapper, new FormData("-10")); LabelField alternative = new LabelField( "Alternatively, you can use your Google Account to log in:"); // alternative.setHideLabel(true); this.add(alternative, new FormData("-10")); add(btnGoogle); setupSubmit(); }
private void initButtons() { btnForgotPassword = new LabelField("Forgot your password?"); btnForgotPassword.setHideLabel(true); btnForgotPassword.setStyleAttribute("cursor", "pointer"); // btnSubmit button btnSubmit = new Button("Log in"); btnSubmit.setIconStyle("sense-btn-icon-go"); // btnSubmit.setType("submit"); // "submit" type makes the button always clickable! new FormButtonBinding(this).addButton(btnSubmit); btnSubmit.addSelectionListener(new SelectionListener<ButtonEvent>() { @Override public void componentSelected(ButtonEvent ce) { if (isValid()) { submit(); } } }); LayoutContainer submitWrapper = new LayoutContainer(new RowLayout(Orientation.HORIZONTAL)); submitWrapper.setSize("100%", "34px"); HBoxLayout wrapperLayout = new HBoxLayout(); wrapperLayout.setHBoxLayoutAlign(HBoxLayoutAlign.MIDDLE); submitWrapper.setLayout(wrapperLayout); submitWrapper.add(btnSubmit); btnSubmit.setWidth("75px"); submitWrapper.add(btnForgotPassword, new HBoxLayoutData(0, 0, 0, 10)); // btnGoogle login button btnGoogle = new Button("Log in with Google", SenseIconProvider.ICON_GOOGLE); this.add(submitWrapper, new FormData("-10")); LabelField alternative = new LabelField( "Alternatively, you can use your Google Account to log in:"); // alternative.setHideLabel(true); this.add(alternative, new FormData("-10")); add(btnGoogle); setupSubmit(); }
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dNPC.java b/src/main/java/net/aufdemrand/denizen/objects/dNPC.java index 3b2dfa7f1..e8c19f520 100644 --- a/src/main/java/net/aufdemrand/denizen/objects/dNPC.java +++ b/src/main/java/net/aufdemrand/denizen/objects/dNPC.java @@ -1,576 +1,576 @@ package net.aufdemrand.denizen.objects; import net.aufdemrand.denizen.flags.FlagManager; import net.aufdemrand.denizen.npc.dNPCRegistry; import net.aufdemrand.denizen.npc.traits.AssignmentTrait; import net.aufdemrand.denizen.npc.traits.HealthTrait; import net.aufdemrand.denizen.npc.traits.NicknameTrait; import net.aufdemrand.denizen.npc.traits.TriggerTrait; import net.aufdemrand.denizen.scripts.commands.npc.EngageCommand; import net.aufdemrand.denizen.scripts.containers.core.InteractScriptContainer; import net.aufdemrand.denizen.scripts.containers.core.InteractScriptHelper; import net.aufdemrand.denizen.scripts.triggers.AbstractTrigger; import net.aufdemrand.denizen.tags.Attribute; import net.aufdemrand.denizen.tags.core.NPCTags; import net.aufdemrand.denizen.utilities.DenizenAPI; import net.aufdemrand.denizen.utilities.debugging.dB; import net.citizensnpcs.api.CitizensAPI; import net.citizensnpcs.api.ai.Navigator; import net.citizensnpcs.api.npc.NPC; import net.citizensnpcs.api.trait.Trait; import net.citizensnpcs.api.trait.trait.Owner; import net.citizensnpcs.trait.Anchors; import net.citizensnpcs.util.Anchor; import net.minecraft.server.v1_6_R3.EntityLiving; import org.bukkit.ChatColor; import org.bukkit.World; import org.bukkit.craftbukkit.v1_6_R3.entity.CraftLivingEntity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import java.util.ArrayList; import java.util.List; import java.util.Map; public class dNPC implements dObject { public static dNPC mirrorCitizensNPC(NPC npc) { if (dNPCRegistry.denizenNPCs.containsKey(npc.getId())) return dNPCRegistry.denizenNPCs.get(npc.getId()); else return new dNPC(npc); } @ObjectFetcher("n") public static dNPC valueOf(String string) { if (string == null) return null; //////// // Match NPC id string = string.toUpperCase().replace("N@", ""); NPC npc; if (aH.matchesInteger(string)) { if (dNPCRegistry.denizenNPCs.containsKey(aH.getIntegerFrom(string))) return dNPCRegistry.denizenNPCs.get(aH.getIntegerFrom(string)); npc = CitizensAPI.getNPCRegistry().getById(aH.getIntegerFrom(string)); if (npc != null) return new dNPC(npc); } //////// // Match NPC name else { for (NPC test : CitizensAPI.getNPCRegistry()) { if (test.getName().equalsIgnoreCase(string)) { return new dNPC(test); } } } return null; } public static boolean matches(String string) { string = string.toUpperCase().replace("N@", ""); NPC npc; if (aH.matchesInteger(string)) { npc = CitizensAPI.getNPCRegistry().getById(aH.getIntegerFrom(string)); if (npc != null) return true; } else { for (NPC test : CitizensAPI.getNPCRegistry()) { if (test.getName().equalsIgnoreCase(string)) { return true; } } } return false; } public boolean isValid() { return getCitizen() != null; } private int npcid = -1; private final org.bukkit.Location locationCache = new org.bukkit.Location(null, 0, 0, 0); public dNPC(NPC citizensNPC) { if (citizensNPC != null) this.npcid = citizensNPC.getId(); if (npcid >= 0 && !dNPCRegistry.denizenNPCs.containsKey(npcid)) dNPCRegistry.denizenNPCs.put(npcid, this); } public EntityLiving getHandle() { return ((CraftLivingEntity) getEntity()).getHandle(); } public NPC getCitizen() { NPC npc = CitizensAPI.getNPCRegistry().getById(npcid); if (npc == null) dB.log("Uh oh! Denizen has encountered a NPE while trying to fetch a NPC. Has this NPC been removed?"); return npc; } public LivingEntity getEntity() { try { return getCitizen().getBukkitEntity(); } catch (NullPointerException e) { dB.log("Uh oh! Denizen has encountered a NPE while trying to fetch a NPC entity. Has this NPC been removed?"); return null; } } public dEntity getDenizenEntity() { try { return new dEntity(getCitizen().getBukkitEntity()); } catch (NullPointerException e) { dB.log("Uh oh! Denizen has encountered a NPE while trying to fetch a NPC entity. Has this NPC been removed?"); return null; } } public EntityType getEntityType() { return getCitizen().getBukkitEntity().getType(); } public Navigator getNavigator() { return getCitizen().getNavigator(); } public int getId() { return getCitizen().getId(); } public String getName() { return getCitizen().getName(); } public InteractScriptContainer getInteractScript(dPlayer player, Class<? extends AbstractTrigger> triggerType) { return InteractScriptHelper.getInteractScript(this, player, triggerType); } public InteractScriptContainer getInteractScriptQuietly(dPlayer player, Class<? extends AbstractTrigger> triggerType) { boolean db = dB.debugMode; dB.debugMode = false; InteractScriptContainer script = InteractScriptHelper.getInteractScript(this, player, triggerType); dB.debugMode = db; return script; } public void destroy() { getCitizen().destroy(); } public dLocation getLocation() { if (isSpawned()) return new dLocation(getCitizen().getBukkitEntity().getLocation(locationCache)); else return null; } public dLocation getEyeLocation() { if (isSpawned()) return new dLocation(getCitizen().getBukkitEntity().getEyeLocation()); else return null; } public World getWorld() { if (isSpawned()) return getEntity().getWorld(); else return null; } @Override public String toString() { return getCitizen().getName() + "/" + getCitizen().getId(); } public boolean isEngaged() { return EngageCommand.getEngaged(getCitizen()); } public boolean isSpawned() { return getCitizen().isSpawned(); } public boolean isVulnerable() { return true; } public String getOwner() { return getCitizen().getTrait(Owner.class).getOwner(); } public AssignmentTrait getAssignmentTrait() { if (!getCitizen().hasTrait(AssignmentTrait.class)) getCitizen().addTrait(AssignmentTrait.class); return getCitizen().getTrait(AssignmentTrait.class); } public NicknameTrait getNicknameTrait() { if (!getCitizen().hasTrait(NicknameTrait.class)) getCitizen().addTrait(NicknameTrait.class); return getCitizen().getTrait(NicknameTrait.class); } public HealthTrait getHealthTrait() { if (!getCitizen().hasTrait(HealthTrait.class)) getCitizen().addTrait(HealthTrait.class); return getCitizen().getTrait(HealthTrait.class); } public TriggerTrait getTriggerTrait() { if (!getCitizen().hasTrait(TriggerTrait.class)) getCitizen().addTrait(TriggerTrait.class); return getCitizen().getTrait(TriggerTrait.class); } public void action(String actionName, dPlayer player, Map<String, dObject> context) { if (getCitizen() != null) { if (getCitizen().hasTrait(AssignmentTrait.class)) DenizenAPI.getCurrentInstance().getNPCRegistry() .getActionHandler().doAction( actionName, this, player, getAssignmentTrait().getAssignment(), context); } } public void action(String actionName, dPlayer player) { action(actionName, player, null); } private String prefix = "npc"; @Override public String getPrefix() { return prefix; } @Override public String debug() { return (prefix + "='<A>" + identify() + "<G>' "); } @Override public boolean isUnique() { return true; } @Override public String getObjectType() { return "NPC"; } @Override public String identify() { return "n@" + npcid; } @Override public dNPC setPrefix(String prefix) { return this; } @Override public String getAttribute(Attribute attribute) { if (attribute == null) return "null"; // <--[tag] // @attribute <npc.name.nickname> // @returns Element // @description // returns the NPC's nickname provided by the nickname trait, or null if the NPC does not have the nickname trait. // --> if (attribute.startsWith("name.nickname")) return new Element(getCitizen().hasTrait(NicknameTrait.class) ? getCitizen().getTrait(NicknameTrait.class) .getNickname() : getName()).getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.name> // @returns Element // @description // returns the name of the NPC. // --> if (attribute.startsWith("name")) return new Element(ChatColor.stripColor(getName())) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.list_traits> // @returns dList // @description // Returns a dList of all of the NPC's trait names. // --> if (attribute.startsWith("list_traits")) { List<String> list = new ArrayList<String>(); for (Trait trait : getCitizen().getTraits()) list.add(trait.getName()); return new dList(list).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <npc.has_trait[<trait>]> // @returns Element(boolean) // @description // Returns whether or not the NPC has a specified trait. // --> if (attribute.startsWith("has_trait")) { if (attribute.hasContext(1)) { Class<? extends Trait> trait = CitizensAPI.getTraitFactory().getTraitClass(attribute.getContext(1)); if (trait != null) return new Element(getCitizen().hasTrait(trait)) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <npc.anchor.list> // @returns dList // @description // returns a dList of anchor names currently assigned to the NPC. // --> if (attribute.startsWith("anchor.list") || attribute.startsWith("anchors.list")) { List<String> list = new ArrayList<String>(); for (Anchor anchor : getCitizen().getTrait(Anchors.class).getAnchors()) list.add(anchor.getName()); return new dList(list).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <npc.has_anchors> // @returns Element(boolean) // @description // returns true if the NPC has anchors assigned, false otherwise. // --> if (attribute.startsWith("has_anchors")) { return (new Element(getCitizen().getTrait(Anchors.class).getAnchors().size() > 0)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <npc.anchor[name]> // @returns dLocation // @description // returns a dLocation associated with the specified anchor, or 'null' if it doesn't exist. // --> if (attribute.startsWith("anchor")) { if (attribute.hasContext(1) && getCitizen().getTrait(Anchors.class).getAnchor(attribute.getContext(1)) != null) return new dLocation(getCitizen().getTrait(Anchors.class) .getAnchor(attribute.getContext(1)).getLocation()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <npc.flag[flag_name]> // @returns Flag dList // @description // returns 'flag dList' of the NPC's flag_name specified. // --> if (attribute.startsWith("flag")) { String flag_name; if (attribute.hasContext(1)) flag_name = attribute.getContext(1); else return "null"; attribute.fulfill(1); if (attribute.startsWith("is_expired") || attribute.startsWith("isexpired")) return new Element(!FlagManager.npcHasFlag(this, flag_name)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("size") && !FlagManager.npcHasFlag(this, flag_name)) return new Element(0).getAttribute(attribute.fulfill(1)); if (FlagManager.npcHasFlag(this, flag_name)) return new dList(DenizenAPI.getCurrentInstance().flagManager() .getNPCFlag(getId(), flag_name)) .getAttribute(attribute); else return "null"; } // <--[tag] // @attribute <npc.id> // @returns Element(number) // @description // returns the NPC's 'npcid' provided by Citizens. // --> if (attribute.startsWith("id")) return new Element(getId()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.owner> // @returns Element // @description // returns the owner of the NPC. // --> if (attribute.startsWith("owner")) return new Element(getOwner()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.inventory> // @returns dInventory // @description // Returns the dInventory of the NPC. // NOTE: This currently only works with player-type NPCs. // --> if (attribute.startsWith("inventory")) return new dInventory(getEntity()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.is_spawned> // @returns Element(boolean) // @description // returns 'true' if the NPC is spawned, otherwise 'false'. // --> if (attribute.startsWith("is_spawned")) return new Element(isSpawned()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.location.previous_location> // @returns dLocation // @description // returns the NPC's previous navigated location. // --> if (attribute.startsWith("location.previous_location")) return (NPCTags.previousLocations.containsKey(getId()) ? NPCTags.previousLocations.get(getId()).getAttribute(attribute.fulfill(2)) : "null"); // <--[tag] // @attribute <npc.script> // @returns dScript // @description // returns the NPC's assigned script. // --> if (attribute.startsWith("script")) { NPC citizen = getCitizen(); if (!citizen.hasTrait(AssignmentTrait.class) || !citizen.getTrait(AssignmentTrait.class).hasAssignment()) { return "null"; } else { return new Element(citizen.getTrait(AssignmentTrait.class).getAssignment().getName()) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <npc.navigator.is_navigating> // @returns Element(boolean) // @description // returns true if the NPC is currently navigating, false otherwise. // --> if (attribute.startsWith("navigator.is_navigating")) return new Element(getNavigator().isNavigating()).getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.speed> // @returns Element(number) // @description // returns the current speed of the NPC. // --> if (attribute.startsWith("navigator.speed")) return new Element(getNavigator().getLocalParameters().speed()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.range> // @returns Element(number) // @description // returns the maximum pathfinding range // --> if (attribute.startsWith("navigator.range")) return new Element(getNavigator().getLocalParameters().range()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.attack_strategy> // @returns Element // @description // returns the NPC's attack strategy // --> if (attribute.startsWith("navigator.attack_strategy")) return new Element(getNavigator().getLocalParameters().attackStrategy().toString()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.speed_modifier> // @returns Element(number) // @description // returns the NPC movement speed modifier // --> if (attribute.startsWith("navigator.speed_modifier")) return new Element(getNavigator().getLocalParameters().speedModifier()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.base_speed> // @returns Element(number) // @description // returns the base navigation speed // --> if (attribute.startsWith("navigator.base_speed")) return new Element(getNavigator().getLocalParameters().baseSpeed()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.avoid_water> // @returns Element(boolean) // @description // returns whether the NPC will avoid water // --> if (attribute.startsWith("navigator.avoid_water")) return new Element(getNavigator().getLocalParameters().avoidWater()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.target_location> // @returns dLocation // @description // returns the location the NPC is curently navigating towards // --> if (attribute.startsWith("navigator.target_location")) return (getNavigator().getTargetAsLocation() != null ? new dLocation(getNavigator().getTargetAsLocation()).getAttribute(attribute.fulfill(2)) : "null"); // <--[tag] // @attribute <npc.navigator.is_fighting> // @returns Element(boolean) // @description // returns whether the NPC is in combat // --> if (attribute.startsWith("navigator.is_fighting")) return new Element(getNavigator().getEntityTarget().isAggressive()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.target_type> // @returns Element // @description // returns the entity type of the target // --> if (attribute.startsWith("navigator.target_type")) return new Element(getNavigator().getTargetType().toString()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.target_entity> // @returns dEntity // @description // returns the entity being targeted // --> if (attribute.startsWith("navigator.target_entity")) return (getNavigator().getEntityTarget().getTarget() != null ? new dEntity(getNavigator().getEntityTarget().getTarget()).getAttribute(attribute.fulfill(2)) : "null"); return (getEntity() != null - ? new dEntity(getEntity()).getAttribute(attribute) + ? new dEntity(getCitizen()).getAttribute(attribute) : new Element(identify()).getAttribute(attribute)); } }
true
true
public String getAttribute(Attribute attribute) { if (attribute == null) return "null"; // <--[tag] // @attribute <npc.name.nickname> // @returns Element // @description // returns the NPC's nickname provided by the nickname trait, or null if the NPC does not have the nickname trait. // --> if (attribute.startsWith("name.nickname")) return new Element(getCitizen().hasTrait(NicknameTrait.class) ? getCitizen().getTrait(NicknameTrait.class) .getNickname() : getName()).getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.name> // @returns Element // @description // returns the name of the NPC. // --> if (attribute.startsWith("name")) return new Element(ChatColor.stripColor(getName())) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.list_traits> // @returns dList // @description // Returns a dList of all of the NPC's trait names. // --> if (attribute.startsWith("list_traits")) { List<String> list = new ArrayList<String>(); for (Trait trait : getCitizen().getTraits()) list.add(trait.getName()); return new dList(list).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <npc.has_trait[<trait>]> // @returns Element(boolean) // @description // Returns whether or not the NPC has a specified trait. // --> if (attribute.startsWith("has_trait")) { if (attribute.hasContext(1)) { Class<? extends Trait> trait = CitizensAPI.getTraitFactory().getTraitClass(attribute.getContext(1)); if (trait != null) return new Element(getCitizen().hasTrait(trait)) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <npc.anchor.list> // @returns dList // @description // returns a dList of anchor names currently assigned to the NPC. // --> if (attribute.startsWith("anchor.list") || attribute.startsWith("anchors.list")) { List<String> list = new ArrayList<String>(); for (Anchor anchor : getCitizen().getTrait(Anchors.class).getAnchors()) list.add(anchor.getName()); return new dList(list).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <npc.has_anchors> // @returns Element(boolean) // @description // returns true if the NPC has anchors assigned, false otherwise. // --> if (attribute.startsWith("has_anchors")) { return (new Element(getCitizen().getTrait(Anchors.class).getAnchors().size() > 0)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <npc.anchor[name]> // @returns dLocation // @description // returns a dLocation associated with the specified anchor, or 'null' if it doesn't exist. // --> if (attribute.startsWith("anchor")) { if (attribute.hasContext(1) && getCitizen().getTrait(Anchors.class).getAnchor(attribute.getContext(1)) != null) return new dLocation(getCitizen().getTrait(Anchors.class) .getAnchor(attribute.getContext(1)).getLocation()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <npc.flag[flag_name]> // @returns Flag dList // @description // returns 'flag dList' of the NPC's flag_name specified. // --> if (attribute.startsWith("flag")) { String flag_name; if (attribute.hasContext(1)) flag_name = attribute.getContext(1); else return "null"; attribute.fulfill(1); if (attribute.startsWith("is_expired") || attribute.startsWith("isexpired")) return new Element(!FlagManager.npcHasFlag(this, flag_name)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("size") && !FlagManager.npcHasFlag(this, flag_name)) return new Element(0).getAttribute(attribute.fulfill(1)); if (FlagManager.npcHasFlag(this, flag_name)) return new dList(DenizenAPI.getCurrentInstance().flagManager() .getNPCFlag(getId(), flag_name)) .getAttribute(attribute); else return "null"; } // <--[tag] // @attribute <npc.id> // @returns Element(number) // @description // returns the NPC's 'npcid' provided by Citizens. // --> if (attribute.startsWith("id")) return new Element(getId()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.owner> // @returns Element // @description // returns the owner of the NPC. // --> if (attribute.startsWith("owner")) return new Element(getOwner()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.inventory> // @returns dInventory // @description // Returns the dInventory of the NPC. // NOTE: This currently only works with player-type NPCs. // --> if (attribute.startsWith("inventory")) return new dInventory(getEntity()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.is_spawned> // @returns Element(boolean) // @description // returns 'true' if the NPC is spawned, otherwise 'false'. // --> if (attribute.startsWith("is_spawned")) return new Element(isSpawned()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.location.previous_location> // @returns dLocation // @description // returns the NPC's previous navigated location. // --> if (attribute.startsWith("location.previous_location")) return (NPCTags.previousLocations.containsKey(getId()) ? NPCTags.previousLocations.get(getId()).getAttribute(attribute.fulfill(2)) : "null"); // <--[tag] // @attribute <npc.script> // @returns dScript // @description // returns the NPC's assigned script. // --> if (attribute.startsWith("script")) { NPC citizen = getCitizen(); if (!citizen.hasTrait(AssignmentTrait.class) || !citizen.getTrait(AssignmentTrait.class).hasAssignment()) { return "null"; } else { return new Element(citizen.getTrait(AssignmentTrait.class).getAssignment().getName()) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <npc.navigator.is_navigating> // @returns Element(boolean) // @description // returns true if the NPC is currently navigating, false otherwise. // --> if (attribute.startsWith("navigator.is_navigating")) return new Element(getNavigator().isNavigating()).getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.speed> // @returns Element(number) // @description // returns the current speed of the NPC. // --> if (attribute.startsWith("navigator.speed")) return new Element(getNavigator().getLocalParameters().speed()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.range> // @returns Element(number) // @description // returns the maximum pathfinding range // --> if (attribute.startsWith("navigator.range")) return new Element(getNavigator().getLocalParameters().range()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.attack_strategy> // @returns Element // @description // returns the NPC's attack strategy // --> if (attribute.startsWith("navigator.attack_strategy")) return new Element(getNavigator().getLocalParameters().attackStrategy().toString()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.speed_modifier> // @returns Element(number) // @description // returns the NPC movement speed modifier // --> if (attribute.startsWith("navigator.speed_modifier")) return new Element(getNavigator().getLocalParameters().speedModifier()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.base_speed> // @returns Element(number) // @description // returns the base navigation speed // --> if (attribute.startsWith("navigator.base_speed")) return new Element(getNavigator().getLocalParameters().baseSpeed()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.avoid_water> // @returns Element(boolean) // @description // returns whether the NPC will avoid water // --> if (attribute.startsWith("navigator.avoid_water")) return new Element(getNavigator().getLocalParameters().avoidWater()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.target_location> // @returns dLocation // @description // returns the location the NPC is curently navigating towards // --> if (attribute.startsWith("navigator.target_location")) return (getNavigator().getTargetAsLocation() != null ? new dLocation(getNavigator().getTargetAsLocation()).getAttribute(attribute.fulfill(2)) : "null"); // <--[tag] // @attribute <npc.navigator.is_fighting> // @returns Element(boolean) // @description // returns whether the NPC is in combat // --> if (attribute.startsWith("navigator.is_fighting")) return new Element(getNavigator().getEntityTarget().isAggressive()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.target_type> // @returns Element // @description // returns the entity type of the target // --> if (attribute.startsWith("navigator.target_type")) return new Element(getNavigator().getTargetType().toString()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.target_entity> // @returns dEntity // @description // returns the entity being targeted // --> if (attribute.startsWith("navigator.target_entity")) return (getNavigator().getEntityTarget().getTarget() != null ? new dEntity(getNavigator().getEntityTarget().getTarget()).getAttribute(attribute.fulfill(2)) : "null"); return (getEntity() != null ? new dEntity(getEntity()).getAttribute(attribute) : new Element(identify()).getAttribute(attribute)); }
public String getAttribute(Attribute attribute) { if (attribute == null) return "null"; // <--[tag] // @attribute <npc.name.nickname> // @returns Element // @description // returns the NPC's nickname provided by the nickname trait, or null if the NPC does not have the nickname trait. // --> if (attribute.startsWith("name.nickname")) return new Element(getCitizen().hasTrait(NicknameTrait.class) ? getCitizen().getTrait(NicknameTrait.class) .getNickname() : getName()).getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.name> // @returns Element // @description // returns the name of the NPC. // --> if (attribute.startsWith("name")) return new Element(ChatColor.stripColor(getName())) .getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.list_traits> // @returns dList // @description // Returns a dList of all of the NPC's trait names. // --> if (attribute.startsWith("list_traits")) { List<String> list = new ArrayList<String>(); for (Trait trait : getCitizen().getTraits()) list.add(trait.getName()); return new dList(list).getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <npc.has_trait[<trait>]> // @returns Element(boolean) // @description // Returns whether or not the NPC has a specified trait. // --> if (attribute.startsWith("has_trait")) { if (attribute.hasContext(1)) { Class<? extends Trait> trait = CitizensAPI.getTraitFactory().getTraitClass(attribute.getContext(1)); if (trait != null) return new Element(getCitizen().hasTrait(trait)) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <npc.anchor.list> // @returns dList // @description // returns a dList of anchor names currently assigned to the NPC. // --> if (attribute.startsWith("anchor.list") || attribute.startsWith("anchors.list")) { List<String> list = new ArrayList<String>(); for (Anchor anchor : getCitizen().getTrait(Anchors.class).getAnchors()) list.add(anchor.getName()); return new dList(list).getAttribute(attribute.fulfill(2)); } // <--[tag] // @attribute <npc.has_anchors> // @returns Element(boolean) // @description // returns true if the NPC has anchors assigned, false otherwise. // --> if (attribute.startsWith("has_anchors")) { return (new Element(getCitizen().getTrait(Anchors.class).getAnchors().size() > 0)) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <npc.anchor[name]> // @returns dLocation // @description // returns a dLocation associated with the specified anchor, or 'null' if it doesn't exist. // --> if (attribute.startsWith("anchor")) { if (attribute.hasContext(1) && getCitizen().getTrait(Anchors.class).getAnchor(attribute.getContext(1)) != null) return new dLocation(getCitizen().getTrait(Anchors.class) .getAnchor(attribute.getContext(1)).getLocation()) .getAttribute(attribute.fulfill(1)); } // <--[tag] // @attribute <npc.flag[flag_name]> // @returns Flag dList // @description // returns 'flag dList' of the NPC's flag_name specified. // --> if (attribute.startsWith("flag")) { String flag_name; if (attribute.hasContext(1)) flag_name = attribute.getContext(1); else return "null"; attribute.fulfill(1); if (attribute.startsWith("is_expired") || attribute.startsWith("isexpired")) return new Element(!FlagManager.npcHasFlag(this, flag_name)) .getAttribute(attribute.fulfill(1)); if (attribute.startsWith("size") && !FlagManager.npcHasFlag(this, flag_name)) return new Element(0).getAttribute(attribute.fulfill(1)); if (FlagManager.npcHasFlag(this, flag_name)) return new dList(DenizenAPI.getCurrentInstance().flagManager() .getNPCFlag(getId(), flag_name)) .getAttribute(attribute); else return "null"; } // <--[tag] // @attribute <npc.id> // @returns Element(number) // @description // returns the NPC's 'npcid' provided by Citizens. // --> if (attribute.startsWith("id")) return new Element(getId()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.owner> // @returns Element // @description // returns the owner of the NPC. // --> if (attribute.startsWith("owner")) return new Element(getOwner()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.inventory> // @returns dInventory // @description // Returns the dInventory of the NPC. // NOTE: This currently only works with player-type NPCs. // --> if (attribute.startsWith("inventory")) return new dInventory(getEntity()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.is_spawned> // @returns Element(boolean) // @description // returns 'true' if the NPC is spawned, otherwise 'false'. // --> if (attribute.startsWith("is_spawned")) return new Element(isSpawned()).getAttribute(attribute.fulfill(1)); // <--[tag] // @attribute <npc.location.previous_location> // @returns dLocation // @description // returns the NPC's previous navigated location. // --> if (attribute.startsWith("location.previous_location")) return (NPCTags.previousLocations.containsKey(getId()) ? NPCTags.previousLocations.get(getId()).getAttribute(attribute.fulfill(2)) : "null"); // <--[tag] // @attribute <npc.script> // @returns dScript // @description // returns the NPC's assigned script. // --> if (attribute.startsWith("script")) { NPC citizen = getCitizen(); if (!citizen.hasTrait(AssignmentTrait.class) || !citizen.getTrait(AssignmentTrait.class).hasAssignment()) { return "null"; } else { return new Element(citizen.getTrait(AssignmentTrait.class).getAssignment().getName()) .getAttribute(attribute.fulfill(1)); } } // <--[tag] // @attribute <npc.navigator.is_navigating> // @returns Element(boolean) // @description // returns true if the NPC is currently navigating, false otherwise. // --> if (attribute.startsWith("navigator.is_navigating")) return new Element(getNavigator().isNavigating()).getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.speed> // @returns Element(number) // @description // returns the current speed of the NPC. // --> if (attribute.startsWith("navigator.speed")) return new Element(getNavigator().getLocalParameters().speed()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.range> // @returns Element(number) // @description // returns the maximum pathfinding range // --> if (attribute.startsWith("navigator.range")) return new Element(getNavigator().getLocalParameters().range()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.attack_strategy> // @returns Element // @description // returns the NPC's attack strategy // --> if (attribute.startsWith("navigator.attack_strategy")) return new Element(getNavigator().getLocalParameters().attackStrategy().toString()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.speed_modifier> // @returns Element(number) // @description // returns the NPC movement speed modifier // --> if (attribute.startsWith("navigator.speed_modifier")) return new Element(getNavigator().getLocalParameters().speedModifier()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.base_speed> // @returns Element(number) // @description // returns the base navigation speed // --> if (attribute.startsWith("navigator.base_speed")) return new Element(getNavigator().getLocalParameters().baseSpeed()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.avoid_water> // @returns Element(boolean) // @description // returns whether the NPC will avoid water // --> if (attribute.startsWith("navigator.avoid_water")) return new Element(getNavigator().getLocalParameters().avoidWater()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.target_location> // @returns dLocation // @description // returns the location the NPC is curently navigating towards // --> if (attribute.startsWith("navigator.target_location")) return (getNavigator().getTargetAsLocation() != null ? new dLocation(getNavigator().getTargetAsLocation()).getAttribute(attribute.fulfill(2)) : "null"); // <--[tag] // @attribute <npc.navigator.is_fighting> // @returns Element(boolean) // @description // returns whether the NPC is in combat // --> if (attribute.startsWith("navigator.is_fighting")) return new Element(getNavigator().getEntityTarget().isAggressive()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.target_type> // @returns Element // @description // returns the entity type of the target // --> if (attribute.startsWith("navigator.target_type")) return new Element(getNavigator().getTargetType().toString()) .getAttribute(attribute.fulfill(2)); // <--[tag] // @attribute <npc.navigator.target_entity> // @returns dEntity // @description // returns the entity being targeted // --> if (attribute.startsWith("navigator.target_entity")) return (getNavigator().getEntityTarget().getTarget() != null ? new dEntity(getNavigator().getEntityTarget().getTarget()).getAttribute(attribute.fulfill(2)) : "null"); return (getEntity() != null ? new dEntity(getCitizen()).getAttribute(attribute) : new Element(identify()).getAttribute(attribute)); }
diff --git a/src/main/java/hudson/maven/MavenModuleSetBuild.java b/src/main/java/hudson/maven/MavenModuleSetBuild.java index 92164bd..a315b46 100644 --- a/src/main/java/hudson/maven/MavenModuleSetBuild.java +++ b/src/main/java/hudson/maven/MavenModuleSetBuild.java @@ -1,1577 +1,1577 @@ /* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Red Hat, Inc., Victor Glushenkov, Alan Harder, Olivier Lamy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.maven; import static hudson.model.Result.FAILURE; import hudson.AbortException; import hudson.EnvVars; import hudson.ExtensionList; import hudson.FilePath; import hudson.FilePath.FileCallable; import hudson.Launcher; import hudson.Util; import hudson.maven.MavenBuild.ProxyImpl2; import hudson.maven.reporters.MavenAggregatedArtifactRecord; import hudson.maven.reporters.MavenFingerprinter; import hudson.maven.reporters.MavenMailer; import hudson.maven.settings.GlobalMavenSettingsProvider; import hudson.maven.settings.MavenSettingsProvider; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.Build; import hudson.model.BuildListener; import hudson.model.Cause.UpstreamCause; import hudson.model.Computer; import hudson.model.Environment; import hudson.model.Executor; import hudson.model.Fingerprint; import jenkins.model.Jenkins; import hudson.model.ParameterDefinition; import hudson.model.ParametersAction; import hudson.model.ParametersDefinitionProperty; import hudson.model.Result; import hudson.model.Run; import hudson.model.StringParameterDefinition; import hudson.model.TaskListener; import hudson.remoting.Channel; import hudson.remoting.VirtualChannel; import hudson.scm.ChangeLogSet; import hudson.tasks.BuildWrapper; import hudson.tasks.MailSender; import hudson.tasks.Maven.MavenInstallation; import hudson.util.ArgumentListBuilder; import hudson.util.IOUtils; import hudson.util.MaskingClassLoader; import hudson.util.StreamTaskListener; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InterruptedIOException; import java.io.PrintStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang.StringUtils; import org.apache.maven.BuildFailureException; import org.apache.maven.artifact.versioning.ComparableVersion; import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.ReactorManager; import org.apache.maven.lifecycle.LifecycleExecutionException; import org.apache.maven.model.building.ModelBuildingRequest; import org.apache.maven.monitor.event.EventDispatcher; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuildingException; import org.codehaus.plexus.util.PathTool; import org.jenkinsci.lib.configprovider.ConfigProvider; import org.jenkinsci.lib.configprovider.model.Config; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; import org.sonatype.aether.transfer.TransferCancelledException; import org.sonatype.aether.transfer.TransferEvent; import org.sonatype.aether.transfer.TransferListener; /** * {@link Build} for {@link MavenModuleSet}. * * <p> * A "build" of {@link MavenModuleSet} consists of: * * <ol> * <li>Update the workspace. * <li>Parse POMs * <li>Trigger module builds. * </ol> * * This object remembers the changelog and what {@link MavenBuild}s are done * on this. * * @author Kohsuke Kawaguchi */ public class MavenModuleSetBuild extends AbstractMavenBuild<MavenModuleSet,MavenModuleSetBuild> { /** * {@link MavenReporter}s that will contribute project actions. * Can be null if there's none. */ /*package*/ List<MavenReporter> projectActionReporters; private String mavenVersionUsed; private transient Object notifyModuleBuildLock = new Object(); public MavenModuleSetBuild(MavenModuleSet job) throws IOException { super(job); } public MavenModuleSetBuild(MavenModuleSet project, File buildDir) throws IOException { super(project, buildDir); } @Override protected void onLoad() { super.onLoad(); notifyModuleBuildLock = new Object(); } /** * Exposes {@code MAVEN_OPTS} to forked processes. * * When we fork Maven, we do so directly by executing Java, thus this environment variable * is pointless (we have to tweak JVM launch option correctly instead, which can be seen in * {@link MavenProcessFactory}), but setting the environment variable explicitly is still * useful in case this Maven forks other Maven processes via normal way. See HUDSON-3644. */ @Override public EnvVars getEnvironment(TaskListener log) throws IOException, InterruptedException { EnvVars envs = super.getEnvironment(log); // We need to add M2_HOME and the mvn binary to the PATH so if Maven // needs to run Maven it will pick the correct one. // This can happen if maven calls ANT which itself calls Maven // or if Maven calls itself e.g. maven-release-plugin MavenInstallation mvn = project.getMaven(); if (mvn == null) throw new AbortException(Messages.MavenModuleSetBuild_NoMavenConfigured()); mvn = mvn.forEnvironment(envs).forNode( Computer.currentComputer().getNode(), log); envs.put("M2_HOME", mvn.getHome()); envs.put("PATH+MAVEN", mvn.getHome() + "/bin"); return envs; } /** * Displays the combined status of all modules. * <p> * More precisely, this picks up the status of this build itself, * plus all the latest builds of the modules that belongs to this build. */ @Override public Result getResult() { Result r = super.getResult(); for (MavenBuild b : getModuleLastBuilds().values()) { Result br = b.getResult(); if(r==null) r = br; else if(br==Result.NOT_BUILT) continue; // UGLY: when computing combined status, ignore the modules that were not built else if(br!=null) r = r.combine(br); } return r; } /** * Returns the filtered changeset entries that match the given module. */ /*package*/ List<ChangeLogSet.Entry> getChangeSetFor(final MavenModule mod) { return new ArrayList<ChangeLogSet.Entry>() { { // modules that are under 'mod'. lazily computed List<MavenModule> subsidiaries = null; for (ChangeLogSet.Entry e : getChangeSet()) { if(isDescendantOf(e, mod)) { if(subsidiaries==null) subsidiaries = mod.getSubsidiaries(); // make sure at least one change belongs to this module proper, // and not its subsidiary module if (notInSubsidiary(subsidiaries, e)) add(e); } } } private boolean notInSubsidiary(List<MavenModule> subsidiaries, ChangeLogSet.Entry e) { for (String path : e.getAffectedPaths()) if(!belongsToSubsidiary(subsidiaries, path)) return true; return false; } private boolean belongsToSubsidiary(List<MavenModule> subsidiaries, String path) { for (MavenModule sub : subsidiaries) if (FilenameUtils.separatorsToUnix(path).startsWith(normalizePath(sub.getRelativePath()))) return true; return false; } /** * Does this change happen somewhere in the given module or its descendants? */ private boolean isDescendantOf(ChangeLogSet.Entry e, MavenModule mod) { for (String path : e.getAffectedPaths()) { if (FilenameUtils.separatorsToUnix(path).startsWith(normalizePath(mod.getRelativePath()))) return true; } return false; } }; } /** * Computes the module builds that correspond to this build. * <p> * A module may be built multiple times (by the user action), * so the value is a list. */ public Map<MavenModule,List<MavenBuild>> getModuleBuilds() { Collection<MavenModule> mods = getParent().getModules(); // identify the build number range. [start,end) MavenModuleSetBuild nb = getNextBuild(); int end = nb!=null ? nb.getNumber() : Integer.MAX_VALUE; // preserve the order by using LinkedHashMap Map<MavenModule,List<MavenBuild>> r = new LinkedHashMap<MavenModule,List<MavenBuild>>(mods.size()); for (MavenModule m : mods) { List<MavenBuild> builds = new ArrayList<MavenBuild>(); MavenBuild b = m.getNearestBuild(number); while(b!=null && b.getNumber()<end) { builds.add(b); b = b.getNextBuild(); } r.put(m,builds); } return r; } /** * Returns the estimated duration for this builds. * Takes only the modules into account which are actually being build in * case of incremental builds. * * @return the estimated duration in milliseconds * @since 1.383 */ @Override public long getEstimatedDuration() { if (!project.isIncrementalBuild()) { return super.getEstimatedDuration(); } long result = 0; Map<MavenModule, List<MavenBuild>> moduleBuilds = getModuleBuilds(); boolean noModuleBuildsYet = true; for (List<MavenBuild> builds : moduleBuilds.values()) { if (!builds.isEmpty()) { noModuleBuildsYet = false; MavenBuild build = builds.get(0); if (build.getResult() != Result.NOT_BUILT && build.getEstimatedDuration() != -1) { result += build.getEstimatedDuration(); } } } if (noModuleBuildsYet) { // modules not determined, yet, i.e. POM not parsed. // Use best estimation we have: return super.getEstimatedDuration(); } result += estimateModuleSetBuildDurationOverhead(3); return result != 0 ? result : -1; } /** * Estimates the duration overhead the {@link MavenModuleSetBuild} itself adds * to the sum of durations of the module builds. */ private long estimateModuleSetBuildDurationOverhead(int numberOfBuilds) { List<MavenModuleSetBuild> moduleSetBuilds = getPreviousBuildsOverThreshold(numberOfBuilds, Result.UNSTABLE); if (moduleSetBuilds.isEmpty()) { return 0; } long overhead = 0; for(MavenModuleSetBuild moduleSetBuild : moduleSetBuilds) { long sumOfModuleBuilds = 0; for (List<MavenBuild> builds : moduleSetBuild.getModuleBuilds().values()) { if (!builds.isEmpty()) { MavenBuild moduleBuild = builds.get(0); sumOfModuleBuilds += moduleBuild.getDuration(); } } overhead += Math.max(0, moduleSetBuild.getDuration() - sumOfModuleBuilds); } return Math.round((double)overhead / moduleSetBuilds.size()); } private static String normalizePath(String relPath) { relPath = StringUtils.trimToEmpty( relPath ); if (StringUtils.isEmpty( relPath )) { LOGGER.config("No need to normalize an empty path."); } else { if(FilenameUtils.indexOfLastSeparator( relPath ) == -1) { LOGGER.config("No need to normalize "+relPath); } else { String tmp = FilenameUtils.normalize( relPath ); if(tmp == null) { LOGGER.config("Path " + relPath + " can not be normalized (parent dir is unknown). Keeping as is."); } else { LOGGER.config("Normalized path " + relPath + " to "+tmp); relPath = tmp; } relPath = FilenameUtils.separatorsToUnix( relPath ); } } LOGGER.fine("Returning path " + relPath); return relPath; } /** * Gets the version of Maven used for build. * * @return * null if this build is done by earlier version of Jenkins that didn't record this information * (this means the build was done by Maven2.x) */ @Exported public String getMavenVersionUsed() { return mavenVersionUsed; } public void setMavenVersionUsed( String mavenVersionUsed ) throws IOException { this.mavenVersionUsed = mavenVersionUsed; save(); } @Override public synchronized void delete() throws IOException { super.delete(); // Delete all contained module builds too for (List<MavenBuild> list : getModuleBuilds().values()) for (MavenBuild build : list) build.delete(); } @Override public Object getDynamic(String token, StaplerRequest req, StaplerResponse rsp) { // map corresponding module build under this object if(token.indexOf('$')>0) { MavenModule m = getProject().getModule(token); if(m!=null) return m.getBuildByNumber(getNumber()); } return super.getDynamic(token,req,rsp); } /** * Information about artifacts produced by Maven. */ @Exported public MavenAggregatedArtifactRecord getMavenArtifacts() { return getAction(MavenAggregatedArtifactRecord.class); } /** * Computes the latest module builds that correspond to this build. * (when individual modules are built, a new ModuleSetBuild is not created, * but rather the new module build falls under the previous ModuleSetBuild) */ public Map<MavenModule,MavenBuild> getModuleLastBuilds() { Collection<MavenModule> mods = getParent().getModules(); // identify the build number range. [start,end) MavenModuleSetBuild nb = getNextBuild(); int end = nb!=null ? nb.getNumber() : Integer.MAX_VALUE; // preserve the order by using LinkedHashMap Map<MavenModule,MavenBuild> r = new LinkedHashMap<MavenModule,MavenBuild>(mods.size()); for (MavenModule m : mods) { MavenBuild b = m.getNearestOldBuild(end - 1); if(b!=null && b.getNumber()>=getNumber()) r.put(m,b); } return r; } public void registerAsProjectAction(MavenReporter reporter) { if(projectActionReporters==null) projectActionReporters = new ArrayList<MavenReporter>(); projectActionReporters.add(reporter); } /** * Finds {@link Action}s from all the module builds that belong to this * {@link MavenModuleSetBuild}. One action per one {@link MavenModule}, * and newer ones take precedence over older ones. */ public <T extends Action> List<T> findModuleBuildActions(Class<T> action) { Collection<MavenModule> mods = getParent().getModules(); List<T> r = new ArrayList<T>(mods.size()); // identify the build number range. [start,end) MavenModuleSetBuild nb = getNextBuild(); int end = nb!=null ? nb.getNumber()-1 : Integer.MAX_VALUE; for (MavenModule m : mods) { MavenBuild b = m.getNearestOldBuild(end); while(b!=null && b.getNumber()>=number) { T a = b.getAction(action); if(a!=null) { r.add(a); break; } b = b.getPreviousBuild(); } } return r; } public void run() { run(new RunnerImpl()); getProject().updateTransientActions(); } @Override public Fingerprint.RangeSet getDownstreamRelationship(AbstractProject that) { Fingerprint.RangeSet rs = super.getDownstreamRelationship(that); for(List<MavenBuild> builds : getModuleBuilds().values()) for (MavenBuild b : builds) rs.add(b.getDownstreamRelationship(that)); return rs; } /** * Called when a module build that corresponds to this module set build * has completed. */ /*package*/ void notifyModuleBuild(MavenBuild newBuild) { try { // update module set build number getParent().updateNextBuildNumber(); // update actions Map<MavenModule, List<MavenBuild>> moduleBuilds = getModuleBuilds(); // actions need to be replaced atomically especially // given that two builds might complete simultaneously. // use a separate lock object since this synchronized block calls into plugins, // which in turn can access other MavenModuleSetBuild instances, which will result in a dead lock. synchronized(notifyModuleBuildLock) { boolean modified = false; List<Action> actions = getActions(); Set<Class<? extends AggregatableAction>> individuals = new HashSet<Class<? extends AggregatableAction>>(); for (Action a : actions) { if(a instanceof MavenAggregatedReport) { MavenAggregatedReport mar = (MavenAggregatedReport) a; mar.update(moduleBuilds,newBuild); individuals.add(mar.getIndividualActionType()); modified = true; } } // see if the new build has any new aggregatable action that we haven't seen. for (AggregatableAction aa : newBuild.getActions(AggregatableAction.class)) { if(individuals.add(aa.getClass())) { // new AggregatableAction MavenAggregatedReport mar = aa.createAggregatedAction(this, moduleBuilds); mar.update(moduleBuilds,newBuild); addAction(mar); modified = true; } } if(modified) { save(); getProject().updateTransientActions(); } } // symlink to this module build String moduleFsName = newBuild.getProject().getModuleName().toFileSystemName(); Util.createSymlink(getRootDir(), "../../modules/"+ moduleFsName +"/builds/"+newBuild.getId() /*ugly!*/, moduleFsName, StreamTaskListener.NULL); } catch (IOException e) { LOGGER.log(Level.WARNING,"Failed to update "+this,e); } catch (InterruptedException e) { LOGGER.log(Level.WARNING,"Failed to update "+this,e); } } public String getMavenOpts(TaskListener listener, EnvVars envVars) { return envVars.expand(expandTokens(listener, project.getMavenOpts())); } /** * The sole job of the {@link MavenModuleSet} build is to update SCM * and triggers module builds. */ private class RunnerImpl extends AbstractRunner { private Map<ModuleName,MavenBuild.ProxyImpl2> proxies; protected Result doRun(final BuildListener listener) throws Exception { PrintStream logger = listener.getLogger(); Result r = null; File tmpSettingsFile = null, tmpGlobalSettingsFile = null; FilePath remoteSettings = null, remoteGlobalSettings = null; try { EnvVars envVars = getEnvironment(listener); MavenInstallation mvn = project.getMaven(); if(mvn==null) throw new AbortException(Messages.MavenModuleSetBuild_NoMavenConfigured()); mvn = mvn.forEnvironment(envVars).forNode(Computer.currentComputer().getNode(), listener); MavenInformation mavenInformation = getModuleRoot().act( new MavenVersionCallable( mvn.getHome() )); String mavenVersion = mavenInformation.getVersion(); MavenBuildInformation mavenBuildInformation = new MavenBuildInformation( mavenVersion ); setMavenVersionUsed( mavenVersion ); LOGGER.fine(getFullDisplayName()+" is building with mavenVersion " + mavenVersion + " from file " + mavenInformation.getVersionResourcePath()); if(!project.isAggregatorStyleBuild()) { parsePoms(listener, logger, envVars, mvn, mavenVersion); // start module builds logger.println("Triggering "+project.getRootModule().getModuleName()); project.getRootModule().scheduleBuild(new UpstreamCause((Run<?,?>)MavenModuleSetBuild.this)); } else { // do builds here try { List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>(); for (BuildWrapper w : project.getBuildWrappersList()) wrappers.add(w); ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) parameters.createBuildWrappers(MavenModuleSetBuild.this,wrappers); for( BuildWrapper w : wrappers) { Environment e = w.setUp(MavenModuleSetBuild.this, launcher, listener); if(e==null) return (r = Result.FAILURE); buildEnvironments.add(e); e.buildEnvVars(envVars); // #3502: too late for getEnvironment to do this } if(!preBuild(listener, project.getPublishers())) return Result.FAILURE; String settingsConfigId = project.getSettingConfigId(); if (settingsConfigId != null) { Config config = null; ExtensionList<ConfigProvider> configProviders = ConfigProvider.all(); if (configProviders != null && configProviders.size() > 0) { for (ConfigProvider configProvider : configProviders) { if (configProvider instanceof MavenSettingsProvider ) { if ( configProvider.isResponsibleFor( settingsConfigId ) ) { config = configProvider.getConfigById( settingsConfigId ); } } } } if (config == null) { logger.println(" your Apache Maven build is setup to use a config with id " + settingsConfigId + " but cannot find the config"); } else { logger.println("using settings config with name " + config.name); String settingsContent = config.content; if (settingsContent != null ) { tmpSettingsFile = File.createTempFile( "maven-settings", "xml" ); remoteSettings = new FilePath(getWorkspace(), tmpSettingsFile.getName()); ByteArrayInputStream bs = new ByteArrayInputStream(settingsContent.getBytes()); remoteSettings.copyFrom(bs); project.setAlternateSettings( remoteSettings.getRemote() ); } } } String globalSettingsConfigId = project.getGlobalSettingConfigId(); if (globalSettingsConfigId != null) { Config config = null; ExtensionList<ConfigProvider> configProviders = ConfigProvider.all(); if (configProviders != null && configProviders.size() > 0) { for (ConfigProvider configProvider : configProviders) { if (configProvider instanceof GlobalMavenSettingsProvider ) { if ( configProvider.isResponsibleFor( globalSettingsConfigId ) ) { config = configProvider.getConfigById( globalSettingsConfigId ); } } } } if (config == null) { logger.println(" your Apache Maven build is setup to use a global settings config with id " + globalSettingsConfigId + " but cannot find the config"); } else { - logger.println("using settings config with name " + config.name); + logger.println("using global settings config with name " + config.name); String globalSettingsContent = config.content; if (globalSettingsContent != null ) { tmpGlobalSettingsFile = File.createTempFile( "global-maven-settings", "xml" ); remoteGlobalSettings = new FilePath(getWorkspace(), tmpGlobalSettingsFile.getName()); ByteArrayInputStream bs = new ByteArrayInputStream(globalSettingsContent.getBytes()); remoteGlobalSettings.copyFrom(bs); project.globalSettingConfigPath = remoteGlobalSettings.getRemote(); } } } parsePoms(listener, logger, envVars, mvn, mavenVersion); // #5428 : do pre-build *before* parsing pom SplittableBuildListener slistener = new SplittableBuildListener(listener); proxies = new HashMap<ModuleName, ProxyImpl2>(); List<ModuleName> changedModules = new ArrayList<ModuleName>(); if (project.isIncrementalBuild() && !getChangeSet().isEmptySet()) { changedModules.addAll(getUnbuildModulesSinceLastSuccessfulBuild()); } for (MavenModule m : project.sortedActiveModules) { MavenBuild mb = m.newBuild(); // JENKINS-8418 mb.setBuiltOnStr( getBuiltOnStr() ); // Check if incrementalBuild is selected and that there are changes - // we act as if incrementalBuild is not set if there are no changes. if (!MavenModuleSetBuild.this.getChangeSet().isEmptySet() && project.isIncrementalBuild()) { //If there are changes for this module, add it. // Also add it if we've never seen this module before, // or if the previous build of this module failed or was unstable. if ((mb.getPreviousBuiltBuild() == null) || (!getChangeSetFor(m).isEmpty()) || (mb.getPreviousBuiltBuild().getResult().isWorseThan(Result.SUCCESS))) { changedModules.add(m.getModuleName()); } } mb.setWorkspace(getModuleRoot().child(m.getRelativePath())); proxies.put(m.getModuleName(), mb.new ProxyImpl2(MavenModuleSetBuild.this,slistener)); } // run the complete build here // figure out the root POM location. // choice of module root ('ws' in this method) is somewhat arbitrary // when multiple CVS/SVN modules are checked out, so also check // the path against the workspace root if that seems like what the user meant (see issue #1293) String rootPOM = project.getRootPOM(); FilePath pom = getModuleRoot().child(rootPOM); FilePath parentLoc = getWorkspace().child(rootPOM); if(!pom.exists() && parentLoc.exists()) pom = parentLoc; ProcessCache.MavenProcess process = null; boolean maven3orLater = MavenUtil.maven3orLater( mavenVersion ); if ( maven3orLater ) { LOGGER.fine( "using maven 3 " + mavenVersion ); process = MavenBuild.mavenProcessCache.get( launcher.getChannel(), slistener, new Maven3ProcessFactory( project, launcher, envVars, getMavenOpts(listener, envVars), pom.getParent() ) ); } else { LOGGER.fine( "using maven 2 " + mavenVersion ); process = MavenBuild.mavenProcessCache.get( launcher.getChannel(), slistener, new MavenProcessFactory( project, launcher, envVars,getMavenOpts(listener, envVars), pom.getParent() ) ); } ArgumentListBuilder margs = new ArgumentListBuilder().add("-B").add("-f", pom.getRemote()); if(project.usesPrivateRepository()) margs.add("-Dmaven.repo.local="+getWorkspace().child(".repository")); if (project.globalSettingConfigPath != null) margs.add("-gs" , project.globalSettingConfigPath); // If incrementalBuild is set // and the previous build didn't specify that we need a full build // and we're on Maven 2.1 or later // and there's at least one module listed in changedModules, // then do the Maven incremental build commands. // If there are no changed modules, we're building everything anyway. boolean maven2_1orLater = new ComparableVersion (mavenVersion).compareTo( new ComparableVersion ("2.1") ) >= 0; boolean needsFullBuild = getPreviousCompletedBuild() != null && getPreviousCompletedBuild().getAction(NeedsFullBuildAction.class) != null; if (project.isIncrementalBuild() && !needsFullBuild && maven2_1orLater && !changedModules.isEmpty()) { margs.add("-amd"); margs.add("-pl", Util.join(changedModules, ",")); } if (project.getAlternateSettings() != null) { if (IOUtils.isAbsolute(project.getAlternateSettings())) { margs.add("-s").add(project.getAlternateSettings()); } else { FilePath mrSettings = getModuleRoot().child(project.getAlternateSettings()); FilePath wsSettings = getWorkspace().child(project.getAlternateSettings()); if (!wsSettings.exists() && mrSettings.exists()) wsSettings = mrSettings; margs.add("-s").add(wsSettings.getRemote()); } } margs.addTokenized(envVars.expand(project.getGoals())); if (maven3orLater) { Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName, List<MavenReporter>>(project.sortedActiveModules.size()); for (MavenModule mavenModule : project.sortedActiveModules) { reporters.put( mavenModule.getModuleName(), mavenModule.createReporters() ); } Maven3Builder maven3Builder = new Maven3Builder( slistener, proxies, reporters, margs.toList(), envVars, mavenBuildInformation ); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(maven3Builder); return r; } finally { maven3Builder.end(launcher); getActions().remove(mpa); process.discard(); } } else { Builder builder = new Builder(slistener, proxies, project.sortedActiveModules, margs.toList(), envVars, mavenBuildInformation); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(builder); return r; } finally { builder.end(launcher); getActions().remove(mpa); process.discard(); } } } catch (InterruptedException e) { r = Executor.currentExecutor().abortResult(); throw e; } finally { if (r != null) { setResult(r); } // tear down in reverse order boolean failed=false; for( int i=buildEnvironments.size()-1; i>=0; i-- ) { if (!buildEnvironments.get(i).tearDown(MavenModuleSetBuild.this,listener)) { failed=true; } } // WARNING The return in the finally clause will trump any return before if (failed) return Result.FAILURE; } } return r; } catch (AbortException e) { if(e.getMessage()!=null) listener.error(e.getMessage()); return Result.FAILURE; } catch (InterruptedIOException e) { e.printStackTrace(listener.error("Aborted Maven execution for InterruptedIOException")); return Executor.currentExecutor().abortResult(); } catch (IOException e) { e.printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom())); return Result.FAILURE; } catch (RunnerAbortedException e) { return Result.FAILURE; } catch (RuntimeException e) { // bug in the code. e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report this to [email protected]")); logger.println("project="+project); logger.println("project.getModules()="+project.getModules()); logger.println("project.getRootModule()="+project.getRootModule()); throw e; } finally { if (project.getSettingConfigId() != null) { // restore to null if as was modified project.setAlternateSettings( null ); project.save(); } // delete tmp files used for MavenSettingsProvider FileUtils.deleteQuietly( tmpSettingsFile ); if (remoteSettings != null) { remoteSettings.delete(); } FileUtils.deleteQuietly( tmpGlobalSettingsFile ); if (project.getGlobalSettingConfigId() != null ) { remoteGlobalSettings.delete(); } } } /** * Returns the modules which have not been build since the last successful aggregator build * though they should be because they had SCM changes. * This can happen when the aggregator build fails before it reaches the module. * * See JENKINS-5764 */ private Collection<ModuleName> getUnbuildModulesSinceLastSuccessfulBuild() { Collection<ModuleName> unbuiltModules = new ArrayList<ModuleName>(); MavenModuleSetBuild previousSuccessfulBuild = getPreviousSuccessfulBuild(); if (previousSuccessfulBuild == null) { // no successful build, yet. Just take the 1st build previousSuccessfulBuild = getParent().getFirstBuild(); } if (previousSuccessfulBuild != null) { MavenModuleSetBuild previousBuild = previousSuccessfulBuild; do { UnbuiltModuleAction unbuiltModuleAction = previousBuild.getAction(UnbuiltModuleAction.class); if (unbuiltModuleAction != null) { for (ModuleName name : unbuiltModuleAction.getUnbuildModules()) { unbuiltModules.add(name); } } previousBuild = previousBuild.getNextBuild(); } while (previousBuild != null && previousBuild != MavenModuleSetBuild.this); } return unbuiltModules; } private void parsePoms(BuildListener listener, PrintStream logger, EnvVars envVars, MavenInstallation mvn, String mavenVersion) throws IOException, InterruptedException { logger.println("Parsing POMs"); List<PomInfo> poms; try { poms = getModuleRoot().act(new PomParser(listener, mvn, project, mavenVersion, envVars)); } catch (IOException e) { if (project.isIncrementalBuild()) { // If POM parsing failed we should do a full build next time. // Otherwise only the modules which have a SCM change for the next build might // be build next time. getActions().add(new NeedsFullBuildAction()); } if (e.getCause() instanceof AbortException) throw (AbortException) e.getCause(); throw e; } catch (MavenExecutionException e) { // Maven failed to parse POM e.getCause().printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom())); if (project.isIncrementalBuild()) { getActions().add(new NeedsFullBuildAction()); } throw new AbortException(); } boolean needsDependencyGraphRecalculation = false; // update the module list Map<ModuleName,MavenModule> modules = project.modules; synchronized(modules) { Map<ModuleName,MavenModule> old = new HashMap<ModuleName, MavenModule>(modules); List<MavenModule> sortedModules = new ArrayList<MavenModule>(); modules.clear(); if(debug) logger.println("Root POM is "+poms.get(0).name); project.reconfigure(poms.get(0)); for (PomInfo pom : poms) { MavenModule mm = old.get(pom.name); if(mm!=null) {// found an existing matching module if(debug) logger.println("Reconfiguring "+mm); if (!mm.isSameModule(pom)) { needsDependencyGraphRecalculation = true; } mm.reconfigure(pom); modules.put(pom.name,mm); } else {// this looks like a new module logger.println(Messages.MavenModuleSetBuild_DiscoveredModule(pom.name,pom.displayName)); mm = new MavenModule(project,pom,getNumber()); modules.put(mm.getModuleName(),mm); needsDependencyGraphRecalculation = true; } sortedModules.add(mm); mm.save(); } // at this point the list contains all the live modules project.sortedActiveModules = sortedModules; // remaining modules are no longer active. old.keySet().removeAll(modules.keySet()); for (MavenModule om : old.values()) { if(debug) logger.println("Disabling "+om); om.makeDisabled(true); needsDependencyGraphRecalculation = true; } modules.putAll(old); } // we might have added new modules if (needsDependencyGraphRecalculation) { logger.println("Modules changed, recalculating dependency graph"); Jenkins.getInstance().rebuildDependencyGraph(); } // module builds must start with this build's number for (MavenModule m : modules.values()) m.updateNextBuildNumber(getNumber()); } protected void post2(BuildListener listener) throws Exception { // asynchronous executions from the build might have left some unsaved state, // so just to be safe, save them all. for (MavenBuild b : getModuleLastBuilds().values()) b.save(); // at this point the result is all set, so ignore the return value if (!performAllBuildSteps(listener, project.getPublishers(), true)) setResult(FAILURE); if (!performAllBuildSteps(listener, project.getProperties(), true)) setResult(FAILURE); // aggregate all module fingerprints to us, // so that dependencies between module builds can be understood as // dependencies between module set builds. // TODO: we really want to implement this as a publisher, // but we don't want to ask for a user configuration, nor should it // show up in the persisted record. MavenFingerprinter.aggregate(MavenModuleSetBuild.this); } @Override public void cleanUp(BuildListener listener) throws Exception { MavenMailer mailer = project.getReporters().get(MavenMailer.class); if (mailer != null) { new MailSender(mailer.recipients, mailer.dontNotifyEveryUnstableBuild, mailer.sendToIndividuals).execute(MavenModuleSetBuild.this, listener); } // too late to set the build result at this point. so ignore failures. performAllBuildSteps(listener, project.getPublishers(), false); performAllBuildSteps(listener, project.getProperties(), false); super.cleanUp(listener); } } /** * Runs Maven and builds the project. * * This is only used for * {@link MavenModuleSet#isAggregatorStyleBuild() the aggregator style build}. */ private static final class Builder extends MavenBuilder { private final Map<ModuleName,MavenBuildProxy2> proxies; private final Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName,List<MavenReporter>>(); private final Map<ModuleName,List<ExecutedMojo>> executedMojos = new HashMap<ModuleName,List<ExecutedMojo>>(); private long mojoStartTime; private MavenBuildProxy2 lastProxy; /** * Kept so that we can finalize them in the end method. */ private final transient Map<ModuleName,ProxyImpl2> sourceProxies; public Builder(BuildListener listener,Map<ModuleName,ProxyImpl2> proxies, Collection<MavenModule> modules, List<String> goals, Map<String,String> systemProps, MavenBuildInformation mavenBuildInformation) { super(listener,goals,systemProps); this.sourceProxies = proxies; this.proxies = new HashMap<ModuleName, MavenBuildProxy2>(proxies); for (Entry<ModuleName,MavenBuildProxy2> e : this.proxies.entrySet()) e.setValue(new FilterImpl(e.getValue(), mavenBuildInformation)); for (MavenModule m : modules) reporters.put(m.getModuleName(),m.createReporters()); } private class FilterImpl extends MavenBuildProxy2.Filter<MavenBuildProxy2> implements Serializable { private MavenBuildInformation mavenBuildInformation; public FilterImpl(MavenBuildProxy2 core, MavenBuildInformation mavenBuildInformation) { super(core); this.mavenBuildInformation = mavenBuildInformation; } @Override public void executeAsync(final BuildCallable<?,?> program) throws IOException { futures.add(Channel.current().callAsync(new AsyncInvoker(core,program))); } public MavenBuildInformation getMavenBuildInformation() { return mavenBuildInformation; } private static final long serialVersionUID = 1L; } /** * Invoked after the maven has finished running, and in the master, not in the maven process. */ void end(Launcher launcher) throws IOException, InterruptedException { for (Map.Entry<ModuleName,ProxyImpl2> e : sourceProxies.entrySet()) { ProxyImpl2 p = e.getValue(); for (MavenReporter r : reporters.get(e.getKey())) { // we'd love to do this when the module build ends, but doing so requires // we know how many task segments are in the current build. r.end(p.owner(),launcher,listener); p.appendLastLog(); } p.close(); } } @Override public Result call() throws IOException { try { if (debug) { listener.getLogger().println("Builder extends MavenBuilder in call " + Thread.currentThread().getContextClassLoader()); } return super.call(); } finally { if(lastProxy!=null) lastProxy.appendLastLog(); } } @Override void preBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException { // set all modules which are not actually being build (in incremental builds) to NOT_BUILD List<MavenProject> projects = rm.getSortedProjects(); Set<ModuleName> buildingProjects = new HashSet<ModuleName>(); for (MavenProject p : projects) { buildingProjects.add(new ModuleName(p)); } for (Entry<ModuleName,MavenBuildProxy2> e : this.proxies.entrySet()) { if (! buildingProjects.contains(e.getKey())) { MavenBuildProxy2 proxy = e.getValue(); proxy.start(); proxy.setResult(Result.NOT_BUILT); proxy.end(); } } } void postBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException { // TODO } void preModule(MavenProject project) throws InterruptedException, IOException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy2 proxy = proxies.get(name); listener.getLogger().flush(); // make sure the data until here are all written proxy.start(); for (MavenReporter r : reporters.get(name)) if(!r.preBuild(proxy,project,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); } void postModule(MavenProject project) throws InterruptedException, IOException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy2 proxy = proxies.get(name); List<MavenReporter> rs = reporters.get(name); if(rs==null) { // probe for issue #906 throw new AssertionError("reporters.get("+name+")==null. reporters="+reporters+" proxies="+proxies); } for (MavenReporter r : rs) if(!r.postBuild(proxy,project,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); proxy.setExecutedMojos(executedMojos.get(name)); listener.getLogger().flush(); // make sure the data until here are all written proxy.end(); lastProxy = proxy; } void preExecute(MavenProject project, MojoInfo mojoInfo) throws IOException, InterruptedException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy proxy = proxies.get(name); for (MavenReporter r : reporters.get(name)) if(!r.preExecute(proxy,project,mojoInfo,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); mojoStartTime = System.currentTimeMillis(); } void postExecute(MavenProject project, MojoInfo mojoInfo, Exception exception) throws IOException, InterruptedException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); List<ExecutedMojo> mojoList = executedMojos.get(name); if(mojoList==null) executedMojos.put(name,mojoList=new ArrayList<ExecutedMojo>()); mojoList.add(new ExecutedMojo(mojoInfo,System.currentTimeMillis()-mojoStartTime)); MavenBuildProxy2 proxy = proxies.get(name); for (MavenReporter r : reporters.get(name)) if(!r.postExecute(proxy,project,mojoInfo,listener,exception)) throw new hudson.maven.agent.AbortException(r+" failed"); if(exception!=null) proxy.setResult(Result.FAILURE); } void onReportGenerated(MavenProject project, MavenReportInfo report) throws IOException, InterruptedException, hudson.maven.agent.AbortException { ModuleName name = new ModuleName(project); MavenBuildProxy proxy = proxies.get(name); for (MavenReporter r : reporters.get(name)) if(!r.reportGenerated(proxy,project,report,listener)) throw new hudson.maven.agent.AbortException(r+" failed"); } private static final long serialVersionUID = 1L; @Override public ClassLoader getClassLoader() { return new MaskingClassLoader( super.getClassLoader() ); } } /** * Used to tunnel exception from Maven through remoting. */ private static final class MavenExecutionException extends RuntimeException { private MavenExecutionException(Exception cause) { super(cause); } @Override public Exception getCause() { return (Exception)super.getCause(); } private static final long serialVersionUID = 1L; } /** * Executed on the slave to parse POM and extract information into {@link PomInfo}, * which will be then brought back to the master. */ private static final class PomParser implements FileCallable<List<PomInfo>> { private final BuildListener listener; private final String rootPOM; /** * Capture the value of the static field so that the debug flag * takes an effect even when {@link PomParser} runs in a slave. */ private final boolean verbose = debug; private final MavenInstallation mavenHome; private final String profiles; private final Properties properties; private final String privateRepository; private final String alternateSettings; private final String globalSetings; private final boolean nonRecursive; // We're called against the module root, not the workspace, which can cause a lot of confusion. private final String workspaceProper; private final String mavenVersion; private final String moduleRootPath; private boolean resolveDependencies = false; private boolean processPlugins = false; private int mavenValidationLevel = -1; String rootPOMRelPrefix; public PomParser(BuildListener listener, MavenInstallation mavenHome, MavenModuleSet project,String mavenVersion,EnvVars envVars) { // project cannot be shipped to the remote JVM, so all the relevant properties need to be captured now. this.listener = listener; this.mavenHome = mavenHome; this.rootPOM = project.getRootPOM(); this.profiles = project.getProfiles(); this.properties = project.getMavenProperties(); ParametersDefinitionProperty parametersDefinitionProperty = project.getProperty( ParametersDefinitionProperty.class ); if (parametersDefinitionProperty != null && parametersDefinitionProperty.getParameterDefinitions() != null) { for (ParameterDefinition parameterDefinition : parametersDefinitionProperty.getParameterDefinitions()) { // those must used as env var if (parameterDefinition instanceof StringParameterDefinition) { this.properties.put( "env." + parameterDefinition.getName(), ((StringParameterDefinition)parameterDefinition).getDefaultValue() ); } } } if (envVars != null && !envVars.isEmpty()) { for (Entry<String,String> entry : envVars.entrySet()) { if (entry.getKey() != null && entry.getValue() != null) { this.properties.put( "env." + entry.getKey(), entry.getValue() ); } } } this.nonRecursive = project.isNonRecursive(); this.workspaceProper = project.getLastBuild().getWorkspace().getRemote(); if (project.usesPrivateRepository()) { this.privateRepository = project.getLastBuild().getWorkspace().child(".repository").getRemote(); } else { this.privateRepository = null; } // TODO maybe in goals with -s,--settings // or -Dmaven.repo.local this.alternateSettings = project.getAlternateSettings(); this.mavenVersion = mavenVersion; this.resolveDependencies = project.isResolveDependencies(); this.processPlugins = project.isProcessPlugins(); this.moduleRootPath = project.getScm().getModuleRoot( project.getLastBuild().getWorkspace(), project.getLastBuild() ).getRemote(); this.mavenValidationLevel = project.getMavenValidationLevel(); this.globalSetings = project.globalSettingConfigPath; } public List<PomInfo> invoke(File ws, VirtualChannel channel) throws IOException { File pom; PrintStream logger = listener.getLogger(); if (IOUtils.isAbsolute(rootPOM)) { pom = new File(rootPOM); } else { // choice of module root ('ws' in this method) is somewhat arbitrary // when multiple CVS/SVN modules are checked out, so also check // the path against the workspace root if that seems like what the user meant (see issue #1293) pom = new File(ws, rootPOM); File parentLoc = new File(ws.getParentFile(),rootPOM); if(!pom.exists() && parentLoc.exists()) pom = parentLoc; } if(!pom.exists()) throw new AbortException(Messages.MavenModuleSetBuild_NoSuchPOMFile(pom)); if (rootPOM.startsWith("../") || rootPOM.startsWith("..\\")) { File wsp = new File(workspaceProper); if (!ws.equals(wsp)) { rootPOMRelPrefix = ws.getCanonicalPath().substring(wsp.getCanonicalPath().length()+1)+"/"; } else { rootPOMRelPrefix = wsp.getName() + "/"; } } else { rootPOMRelPrefix = ""; } if(verbose) logger.println("Parsing " + (nonRecursive ? "non-recursively " : "recursively ") + pom); File settingsLoc; if (alternateSettings == null) { settingsLoc = null; } else if (IOUtils.isAbsolute(alternateSettings)) { settingsLoc = new File(alternateSettings); } else { // Check for settings.xml first in the workspace proper, and then in the current directory, // which is getModuleRoot(). // This is backwards from the order the root POM logic uses, but it's to be consistent with the Maven execution logic. settingsLoc = new File(workspaceProper, alternateSettings); File mrSettingsLoc = new File(workspaceProper, alternateSettings); if (!settingsLoc.exists() && mrSettingsLoc.exists()) settingsLoc = mrSettingsLoc; } if (debug) { logger.println(Messages.MavenModuleSetBuild_SettinsgXmlAndPrivateRepository(settingsLoc,privateRepository)); } if ((settingsLoc != null) && (!settingsLoc.exists())) { throw new AbortException(Messages.MavenModuleSetBuild_NoSuchAlternateSettings(settingsLoc.getAbsolutePath())); } try { MavenEmbedderRequest mavenEmbedderRequest = new MavenEmbedderRequest( listener, mavenHome.getHomeDir(), profiles, properties, privateRepository, settingsLoc ); mavenEmbedderRequest.setTransferListener( new SimpleTransferListener(listener) ); mavenEmbedderRequest.setProcessPlugins( this.processPlugins ); mavenEmbedderRequest.setResolveDependencies( this.resolveDependencies ); if (globalSetings != null) { mavenEmbedderRequest.setGlobalSettings( new File(globalSetings) ); } // FIXME handle 3.1 level when version will be here : no rush :-) // or made something configurable tru the ui ? ReactorReader reactorReader = null; boolean maven3OrLater = new ComparableVersion (mavenVersion).compareTo( new ComparableVersion ("3.0") ) >= 0; if (maven3OrLater) { mavenEmbedderRequest.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0 ); } else { reactorReader = new ReactorReader( new HashMap<String, MavenProject>(), new File(workspaceProper) ); mavenEmbedderRequest.setWorkspaceReader( reactorReader ); } if (this.mavenValidationLevel >= 0) { mavenEmbedderRequest.setValidationLevel( this.mavenValidationLevel ); } //mavenEmbedderRequest.setClassLoader( MavenEmbedderUtils.buildClassRealm( mavenHome.getHomeDir(), null, null ) ); MavenEmbedder embedder = MavenUtil.createEmbedder( mavenEmbedderRequest ); MavenProject rootProject = null; List<MavenProject> mps = new ArrayList<MavenProject>(0); if (maven3OrLater) { mps = embedder.readProjects( pom,!this.nonRecursive ); } else { // http://issues.jenkins-ci.org/browse/HUDSON-8390 // we cannot read maven projects in one time for backward compatibility // but we have to use a ReactorReader to get some pom with bad inheritence configured MavenProject mavenProject = embedder.readProject( pom ); rootProject = mavenProject; mps.add( mavenProject ); reactorReader.addProject( mavenProject ); if (!this.nonRecursive) { readChilds( mavenProject, embedder, mps, reactorReader ); } } Map<String,MavenProject> canonicalPaths = new HashMap<String, MavenProject>( mps.size() ); for(MavenProject mp : mps) { // Projects are indexed by POM path and not module path because // Maven allows to have several POMs with different names in the same directory canonicalPaths.put( mp.getFile().getCanonicalPath(), mp ); } //MavenUtil.resolveModules(embedder,mp,getRootPath(rootPOMRelPrefix),relPath,listener,nonRecursive); if(verbose) { for (Entry<String,MavenProject> e : canonicalPaths.entrySet()) logger.printf("Discovered %s at %s\n",e.getValue().getId(),e.getKey()); } Set<PomInfo> infos = new LinkedHashSet<PomInfo>(); if (maven3OrLater) { for (MavenProject mp : mps) { if (mp.isExecutionRoot()) { rootProject = mp; continue; } } } // if rootProject is null but no reason :-) use the first one if (rootProject == null) { rootProject = mps.get( 0 ); } toPomInfo(rootProject,null,canonicalPaths,infos); for (PomInfo pi : infos) pi.cutCycle(); return new ArrayList<PomInfo>(infos); } catch (MavenEmbedderException e) { throw new MavenExecutionException(e); } catch (ProjectBuildingException e) { throw new MavenExecutionException(e); } } /** * @see PomInfo#relativePath to understand relPath calculation */ private void toPomInfo(MavenProject mp, PomInfo parent, Map<String,MavenProject> abslPath, Set<PomInfo> infos) throws IOException { String relPath = PathTool.getRelativeFilePath( this.moduleRootPath, mp.getBasedir().getPath() ); relPath = normalizePath(relPath); if (parent == null ) { relPath = getRootPath(rootPOMRelPrefix); } relPath = StringUtils.removeStart( relPath, "/" ); PomInfo pi = new PomInfo(mp, parent, relPath); infos.add(pi); if(!this.nonRecursive) { for (String modulePath : mp.getModules()) { if (StringUtils.isBlank( modulePath )) { continue; } File path = new File(mp.getBasedir(), modulePath); // HUDSON-8391 : Modules are indexed by POM path thus // by default we have to add the default pom.xml file if(path.isDirectory()) path = new File(mp.getBasedir(), modulePath+"/pom.xml"); MavenProject child = abslPath.get( path.getCanonicalPath()); if (child == null) { listener.getLogger().printf(Messages.MavenModuleSetBuild_FoundModuleWithoutProject(modulePath)); continue; } toPomInfo(child,pi,abslPath,infos); } } } private void readChilds(MavenProject mp, MavenEmbedder mavenEmbedder, List<MavenProject> mavenProjects, ReactorReader reactorReader) throws ProjectBuildingException, MavenEmbedderException { if (mp.getModules() == null || mp.getModules().isEmpty()) { return; } for (String module : mp.getModules()) { if ( Util.fixEmptyAndTrim( module ) != null ) { File pomFile = new File(mp.getFile().getParent(), module); MavenProject mavenProject2 = null; // take care of HUDSON-8445 if (pomFile.isFile()) mavenProject2 = mavenEmbedder.readProject( pomFile ); else mavenProject2 = mavenEmbedder.readProject( new File(mp.getFile().getParent(), module + "/pom.xml") ); mavenProjects.add( mavenProject2 ); reactorReader.addProject( mavenProject2 ); readChilds( mavenProject2, mavenEmbedder, mavenProjects, reactorReader ); } } } /** * Computes the path of {@link #rootPOM}. * * Returns "abc" if rootPOM="abc/pom.xml" * If rootPOM="pom.xml", this method returns "". */ private String getRootPath(String prefix) { int idx = Math.max(rootPOM.lastIndexOf('/'), rootPOM.lastIndexOf('\\')); if(idx==-1) return ""; return prefix + rootPOM.substring(0,idx); } private static final long serialVersionUID = 1L; } private static final Logger LOGGER = Logger.getLogger(MavenModuleSetBuild.class.getName()); /** * Extra verbose debug switch. */ public static boolean debug = Boolean.getBoolean( "hudson.maven.debug" ); @Override public MavenModuleSet getParent() {// don't know why, but javac wants this return super.getParent(); } /** * will log in the {@link TaskListener} when transferFailed and transferSucceeded * @author Olivier Lamy * @since */ public static class SimpleTransferListener implements TransferListener { private TaskListener taskListener; public SimpleTransferListener(TaskListener taskListener) { this.taskListener = taskListener; } public void transferCorrupted( TransferEvent arg0 ) throws TransferCancelledException { // no op } public void transferFailed( TransferEvent transferEvent ) { taskListener.getLogger().println(Messages.MavenModuleSetBuild_FailedToTransfer(transferEvent.getException().getMessage())); } public void transferInitiated( TransferEvent arg0 ) throws TransferCancelledException { // no op } public void transferProgressed( TransferEvent arg0 ) throws TransferCancelledException { // no op } public void transferStarted( TransferEvent arg0 ) throws TransferCancelledException { // no op } public void transferSucceeded( TransferEvent transferEvent ) { taskListener.getLogger().println( Messages.MavenModuleSetBuild_DownloadedArtifact( transferEvent.getResource().getRepositoryUrl(), transferEvent.getResource().getResourceName()) ); } } }
true
true
protected Result doRun(final BuildListener listener) throws Exception { PrintStream logger = listener.getLogger(); Result r = null; File tmpSettingsFile = null, tmpGlobalSettingsFile = null; FilePath remoteSettings = null, remoteGlobalSettings = null; try { EnvVars envVars = getEnvironment(listener); MavenInstallation mvn = project.getMaven(); if(mvn==null) throw new AbortException(Messages.MavenModuleSetBuild_NoMavenConfigured()); mvn = mvn.forEnvironment(envVars).forNode(Computer.currentComputer().getNode(), listener); MavenInformation mavenInformation = getModuleRoot().act( new MavenVersionCallable( mvn.getHome() )); String mavenVersion = mavenInformation.getVersion(); MavenBuildInformation mavenBuildInformation = new MavenBuildInformation( mavenVersion ); setMavenVersionUsed( mavenVersion ); LOGGER.fine(getFullDisplayName()+" is building with mavenVersion " + mavenVersion + " from file " + mavenInformation.getVersionResourcePath()); if(!project.isAggregatorStyleBuild()) { parsePoms(listener, logger, envVars, mvn, mavenVersion); // start module builds logger.println("Triggering "+project.getRootModule().getModuleName()); project.getRootModule().scheduleBuild(new UpstreamCause((Run<?,?>)MavenModuleSetBuild.this)); } else { // do builds here try { List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>(); for (BuildWrapper w : project.getBuildWrappersList()) wrappers.add(w); ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) parameters.createBuildWrappers(MavenModuleSetBuild.this,wrappers); for( BuildWrapper w : wrappers) { Environment e = w.setUp(MavenModuleSetBuild.this, launcher, listener); if(e==null) return (r = Result.FAILURE); buildEnvironments.add(e); e.buildEnvVars(envVars); // #3502: too late for getEnvironment to do this } if(!preBuild(listener, project.getPublishers())) return Result.FAILURE; String settingsConfigId = project.getSettingConfigId(); if (settingsConfigId != null) { Config config = null; ExtensionList<ConfigProvider> configProviders = ConfigProvider.all(); if (configProviders != null && configProviders.size() > 0) { for (ConfigProvider configProvider : configProviders) { if (configProvider instanceof MavenSettingsProvider ) { if ( configProvider.isResponsibleFor( settingsConfigId ) ) { config = configProvider.getConfigById( settingsConfigId ); } } } } if (config == null) { logger.println(" your Apache Maven build is setup to use a config with id " + settingsConfigId + " but cannot find the config"); } else { logger.println("using settings config with name " + config.name); String settingsContent = config.content; if (settingsContent != null ) { tmpSettingsFile = File.createTempFile( "maven-settings", "xml" ); remoteSettings = new FilePath(getWorkspace(), tmpSettingsFile.getName()); ByteArrayInputStream bs = new ByteArrayInputStream(settingsContent.getBytes()); remoteSettings.copyFrom(bs); project.setAlternateSettings( remoteSettings.getRemote() ); } } } String globalSettingsConfigId = project.getGlobalSettingConfigId(); if (globalSettingsConfigId != null) { Config config = null; ExtensionList<ConfigProvider> configProviders = ConfigProvider.all(); if (configProviders != null && configProviders.size() > 0) { for (ConfigProvider configProvider : configProviders) { if (configProvider instanceof GlobalMavenSettingsProvider ) { if ( configProvider.isResponsibleFor( globalSettingsConfigId ) ) { config = configProvider.getConfigById( globalSettingsConfigId ); } } } } if (config == null) { logger.println(" your Apache Maven build is setup to use a global settings config with id " + globalSettingsConfigId + " but cannot find the config"); } else { logger.println("using settings config with name " + config.name); String globalSettingsContent = config.content; if (globalSettingsContent != null ) { tmpGlobalSettingsFile = File.createTempFile( "global-maven-settings", "xml" ); remoteGlobalSettings = new FilePath(getWorkspace(), tmpGlobalSettingsFile.getName()); ByteArrayInputStream bs = new ByteArrayInputStream(globalSettingsContent.getBytes()); remoteGlobalSettings.copyFrom(bs); project.globalSettingConfigPath = remoteGlobalSettings.getRemote(); } } } parsePoms(listener, logger, envVars, mvn, mavenVersion); // #5428 : do pre-build *before* parsing pom SplittableBuildListener slistener = new SplittableBuildListener(listener); proxies = new HashMap<ModuleName, ProxyImpl2>(); List<ModuleName> changedModules = new ArrayList<ModuleName>(); if (project.isIncrementalBuild() && !getChangeSet().isEmptySet()) { changedModules.addAll(getUnbuildModulesSinceLastSuccessfulBuild()); } for (MavenModule m : project.sortedActiveModules) { MavenBuild mb = m.newBuild(); // JENKINS-8418 mb.setBuiltOnStr( getBuiltOnStr() ); // Check if incrementalBuild is selected and that there are changes - // we act as if incrementalBuild is not set if there are no changes. if (!MavenModuleSetBuild.this.getChangeSet().isEmptySet() && project.isIncrementalBuild()) { //If there are changes for this module, add it. // Also add it if we've never seen this module before, // or if the previous build of this module failed or was unstable. if ((mb.getPreviousBuiltBuild() == null) || (!getChangeSetFor(m).isEmpty()) || (mb.getPreviousBuiltBuild().getResult().isWorseThan(Result.SUCCESS))) { changedModules.add(m.getModuleName()); } } mb.setWorkspace(getModuleRoot().child(m.getRelativePath())); proxies.put(m.getModuleName(), mb.new ProxyImpl2(MavenModuleSetBuild.this,slistener)); } // run the complete build here // figure out the root POM location. // choice of module root ('ws' in this method) is somewhat arbitrary // when multiple CVS/SVN modules are checked out, so also check // the path against the workspace root if that seems like what the user meant (see issue #1293) String rootPOM = project.getRootPOM(); FilePath pom = getModuleRoot().child(rootPOM); FilePath parentLoc = getWorkspace().child(rootPOM); if(!pom.exists() && parentLoc.exists()) pom = parentLoc; ProcessCache.MavenProcess process = null; boolean maven3orLater = MavenUtil.maven3orLater( mavenVersion ); if ( maven3orLater ) { LOGGER.fine( "using maven 3 " + mavenVersion ); process = MavenBuild.mavenProcessCache.get( launcher.getChannel(), slistener, new Maven3ProcessFactory( project, launcher, envVars, getMavenOpts(listener, envVars), pom.getParent() ) ); } else { LOGGER.fine( "using maven 2 " + mavenVersion ); process = MavenBuild.mavenProcessCache.get( launcher.getChannel(), slistener, new MavenProcessFactory( project, launcher, envVars,getMavenOpts(listener, envVars), pom.getParent() ) ); } ArgumentListBuilder margs = new ArgumentListBuilder().add("-B").add("-f", pom.getRemote()); if(project.usesPrivateRepository()) margs.add("-Dmaven.repo.local="+getWorkspace().child(".repository")); if (project.globalSettingConfigPath != null) margs.add("-gs" , project.globalSettingConfigPath); // If incrementalBuild is set // and the previous build didn't specify that we need a full build // and we're on Maven 2.1 or later // and there's at least one module listed in changedModules, // then do the Maven incremental build commands. // If there are no changed modules, we're building everything anyway. boolean maven2_1orLater = new ComparableVersion (mavenVersion).compareTo( new ComparableVersion ("2.1") ) >= 0; boolean needsFullBuild = getPreviousCompletedBuild() != null && getPreviousCompletedBuild().getAction(NeedsFullBuildAction.class) != null; if (project.isIncrementalBuild() && !needsFullBuild && maven2_1orLater && !changedModules.isEmpty()) { margs.add("-amd"); margs.add("-pl", Util.join(changedModules, ",")); } if (project.getAlternateSettings() != null) { if (IOUtils.isAbsolute(project.getAlternateSettings())) { margs.add("-s").add(project.getAlternateSettings()); } else { FilePath mrSettings = getModuleRoot().child(project.getAlternateSettings()); FilePath wsSettings = getWorkspace().child(project.getAlternateSettings()); if (!wsSettings.exists() && mrSettings.exists()) wsSettings = mrSettings; margs.add("-s").add(wsSettings.getRemote()); } } margs.addTokenized(envVars.expand(project.getGoals())); if (maven3orLater) { Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName, List<MavenReporter>>(project.sortedActiveModules.size()); for (MavenModule mavenModule : project.sortedActiveModules) { reporters.put( mavenModule.getModuleName(), mavenModule.createReporters() ); } Maven3Builder maven3Builder = new Maven3Builder( slistener, proxies, reporters, margs.toList(), envVars, mavenBuildInformation ); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(maven3Builder); return r; } finally { maven3Builder.end(launcher); getActions().remove(mpa); process.discard(); } } else { Builder builder = new Builder(slistener, proxies, project.sortedActiveModules, margs.toList(), envVars, mavenBuildInformation); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(builder); return r; } finally { builder.end(launcher); getActions().remove(mpa); process.discard(); } } } catch (InterruptedException e) { r = Executor.currentExecutor().abortResult(); throw e; } finally { if (r != null) { setResult(r); } // tear down in reverse order boolean failed=false; for( int i=buildEnvironments.size()-1; i>=0; i-- ) { if (!buildEnvironments.get(i).tearDown(MavenModuleSetBuild.this,listener)) { failed=true; } } // WARNING The return in the finally clause will trump any return before if (failed) return Result.FAILURE; } } return r; } catch (AbortException e) { if(e.getMessage()!=null) listener.error(e.getMessage()); return Result.FAILURE; } catch (InterruptedIOException e) { e.printStackTrace(listener.error("Aborted Maven execution for InterruptedIOException")); return Executor.currentExecutor().abortResult(); } catch (IOException e) { e.printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom())); return Result.FAILURE; } catch (RunnerAbortedException e) { return Result.FAILURE; } catch (RuntimeException e) { // bug in the code. e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report this to [email protected]")); logger.println("project="+project); logger.println("project.getModules()="+project.getModules()); logger.println("project.getRootModule()="+project.getRootModule()); throw e; } finally { if (project.getSettingConfigId() != null) { // restore to null if as was modified project.setAlternateSettings( null ); project.save(); } // delete tmp files used for MavenSettingsProvider FileUtils.deleteQuietly( tmpSettingsFile ); if (remoteSettings != null) { remoteSettings.delete(); } FileUtils.deleteQuietly( tmpGlobalSettingsFile ); if (project.getGlobalSettingConfigId() != null ) { remoteGlobalSettings.delete(); } } }
protected Result doRun(final BuildListener listener) throws Exception { PrintStream logger = listener.getLogger(); Result r = null; File tmpSettingsFile = null, tmpGlobalSettingsFile = null; FilePath remoteSettings = null, remoteGlobalSettings = null; try { EnvVars envVars = getEnvironment(listener); MavenInstallation mvn = project.getMaven(); if(mvn==null) throw new AbortException(Messages.MavenModuleSetBuild_NoMavenConfigured()); mvn = mvn.forEnvironment(envVars).forNode(Computer.currentComputer().getNode(), listener); MavenInformation mavenInformation = getModuleRoot().act( new MavenVersionCallable( mvn.getHome() )); String mavenVersion = mavenInformation.getVersion(); MavenBuildInformation mavenBuildInformation = new MavenBuildInformation( mavenVersion ); setMavenVersionUsed( mavenVersion ); LOGGER.fine(getFullDisplayName()+" is building with mavenVersion " + mavenVersion + " from file " + mavenInformation.getVersionResourcePath()); if(!project.isAggregatorStyleBuild()) { parsePoms(listener, logger, envVars, mvn, mavenVersion); // start module builds logger.println("Triggering "+project.getRootModule().getModuleName()); project.getRootModule().scheduleBuild(new UpstreamCause((Run<?,?>)MavenModuleSetBuild.this)); } else { // do builds here try { List<BuildWrapper> wrappers = new ArrayList<BuildWrapper>(); for (BuildWrapper w : project.getBuildWrappersList()) wrappers.add(w); ParametersAction parameters = getAction(ParametersAction.class); if (parameters != null) parameters.createBuildWrappers(MavenModuleSetBuild.this,wrappers); for( BuildWrapper w : wrappers) { Environment e = w.setUp(MavenModuleSetBuild.this, launcher, listener); if(e==null) return (r = Result.FAILURE); buildEnvironments.add(e); e.buildEnvVars(envVars); // #3502: too late for getEnvironment to do this } if(!preBuild(listener, project.getPublishers())) return Result.FAILURE; String settingsConfigId = project.getSettingConfigId(); if (settingsConfigId != null) { Config config = null; ExtensionList<ConfigProvider> configProviders = ConfigProvider.all(); if (configProviders != null && configProviders.size() > 0) { for (ConfigProvider configProvider : configProviders) { if (configProvider instanceof MavenSettingsProvider ) { if ( configProvider.isResponsibleFor( settingsConfigId ) ) { config = configProvider.getConfigById( settingsConfigId ); } } } } if (config == null) { logger.println(" your Apache Maven build is setup to use a config with id " + settingsConfigId + " but cannot find the config"); } else { logger.println("using settings config with name " + config.name); String settingsContent = config.content; if (settingsContent != null ) { tmpSettingsFile = File.createTempFile( "maven-settings", "xml" ); remoteSettings = new FilePath(getWorkspace(), tmpSettingsFile.getName()); ByteArrayInputStream bs = new ByteArrayInputStream(settingsContent.getBytes()); remoteSettings.copyFrom(bs); project.setAlternateSettings( remoteSettings.getRemote() ); } } } String globalSettingsConfigId = project.getGlobalSettingConfigId(); if (globalSettingsConfigId != null) { Config config = null; ExtensionList<ConfigProvider> configProviders = ConfigProvider.all(); if (configProviders != null && configProviders.size() > 0) { for (ConfigProvider configProvider : configProviders) { if (configProvider instanceof GlobalMavenSettingsProvider ) { if ( configProvider.isResponsibleFor( globalSettingsConfigId ) ) { config = configProvider.getConfigById( globalSettingsConfigId ); } } } } if (config == null) { logger.println(" your Apache Maven build is setup to use a global settings config with id " + globalSettingsConfigId + " but cannot find the config"); } else { logger.println("using global settings config with name " + config.name); String globalSettingsContent = config.content; if (globalSettingsContent != null ) { tmpGlobalSettingsFile = File.createTempFile( "global-maven-settings", "xml" ); remoteGlobalSettings = new FilePath(getWorkspace(), tmpGlobalSettingsFile.getName()); ByteArrayInputStream bs = new ByteArrayInputStream(globalSettingsContent.getBytes()); remoteGlobalSettings.copyFrom(bs); project.globalSettingConfigPath = remoteGlobalSettings.getRemote(); } } } parsePoms(listener, logger, envVars, mvn, mavenVersion); // #5428 : do pre-build *before* parsing pom SplittableBuildListener slistener = new SplittableBuildListener(listener); proxies = new HashMap<ModuleName, ProxyImpl2>(); List<ModuleName> changedModules = new ArrayList<ModuleName>(); if (project.isIncrementalBuild() && !getChangeSet().isEmptySet()) { changedModules.addAll(getUnbuildModulesSinceLastSuccessfulBuild()); } for (MavenModule m : project.sortedActiveModules) { MavenBuild mb = m.newBuild(); // JENKINS-8418 mb.setBuiltOnStr( getBuiltOnStr() ); // Check if incrementalBuild is selected and that there are changes - // we act as if incrementalBuild is not set if there are no changes. if (!MavenModuleSetBuild.this.getChangeSet().isEmptySet() && project.isIncrementalBuild()) { //If there are changes for this module, add it. // Also add it if we've never seen this module before, // or if the previous build of this module failed or was unstable. if ((mb.getPreviousBuiltBuild() == null) || (!getChangeSetFor(m).isEmpty()) || (mb.getPreviousBuiltBuild().getResult().isWorseThan(Result.SUCCESS))) { changedModules.add(m.getModuleName()); } } mb.setWorkspace(getModuleRoot().child(m.getRelativePath())); proxies.put(m.getModuleName(), mb.new ProxyImpl2(MavenModuleSetBuild.this,slistener)); } // run the complete build here // figure out the root POM location. // choice of module root ('ws' in this method) is somewhat arbitrary // when multiple CVS/SVN modules are checked out, so also check // the path against the workspace root if that seems like what the user meant (see issue #1293) String rootPOM = project.getRootPOM(); FilePath pom = getModuleRoot().child(rootPOM); FilePath parentLoc = getWorkspace().child(rootPOM); if(!pom.exists() && parentLoc.exists()) pom = parentLoc; ProcessCache.MavenProcess process = null; boolean maven3orLater = MavenUtil.maven3orLater( mavenVersion ); if ( maven3orLater ) { LOGGER.fine( "using maven 3 " + mavenVersion ); process = MavenBuild.mavenProcessCache.get( launcher.getChannel(), slistener, new Maven3ProcessFactory( project, launcher, envVars, getMavenOpts(listener, envVars), pom.getParent() ) ); } else { LOGGER.fine( "using maven 2 " + mavenVersion ); process = MavenBuild.mavenProcessCache.get( launcher.getChannel(), slistener, new MavenProcessFactory( project, launcher, envVars,getMavenOpts(listener, envVars), pom.getParent() ) ); } ArgumentListBuilder margs = new ArgumentListBuilder().add("-B").add("-f", pom.getRemote()); if(project.usesPrivateRepository()) margs.add("-Dmaven.repo.local="+getWorkspace().child(".repository")); if (project.globalSettingConfigPath != null) margs.add("-gs" , project.globalSettingConfigPath); // If incrementalBuild is set // and the previous build didn't specify that we need a full build // and we're on Maven 2.1 or later // and there's at least one module listed in changedModules, // then do the Maven incremental build commands. // If there are no changed modules, we're building everything anyway. boolean maven2_1orLater = new ComparableVersion (mavenVersion).compareTo( new ComparableVersion ("2.1") ) >= 0; boolean needsFullBuild = getPreviousCompletedBuild() != null && getPreviousCompletedBuild().getAction(NeedsFullBuildAction.class) != null; if (project.isIncrementalBuild() && !needsFullBuild && maven2_1orLater && !changedModules.isEmpty()) { margs.add("-amd"); margs.add("-pl", Util.join(changedModules, ",")); } if (project.getAlternateSettings() != null) { if (IOUtils.isAbsolute(project.getAlternateSettings())) { margs.add("-s").add(project.getAlternateSettings()); } else { FilePath mrSettings = getModuleRoot().child(project.getAlternateSettings()); FilePath wsSettings = getWorkspace().child(project.getAlternateSettings()); if (!wsSettings.exists() && mrSettings.exists()) wsSettings = mrSettings; margs.add("-s").add(wsSettings.getRemote()); } } margs.addTokenized(envVars.expand(project.getGoals())); if (maven3orLater) { Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName, List<MavenReporter>>(project.sortedActiveModules.size()); for (MavenModule mavenModule : project.sortedActiveModules) { reporters.put( mavenModule.getModuleName(), mavenModule.createReporters() ); } Maven3Builder maven3Builder = new Maven3Builder( slistener, proxies, reporters, margs.toList(), envVars, mavenBuildInformation ); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(maven3Builder); return r; } finally { maven3Builder.end(launcher); getActions().remove(mpa); process.discard(); } } else { Builder builder = new Builder(slistener, proxies, project.sortedActiveModules, margs.toList(), envVars, mavenBuildInformation); MavenProbeAction mpa=null; try { mpa = new MavenProbeAction(project,process.channel); addAction(mpa); r = process.call(builder); return r; } finally { builder.end(launcher); getActions().remove(mpa); process.discard(); } } } catch (InterruptedException e) { r = Executor.currentExecutor().abortResult(); throw e; } finally { if (r != null) { setResult(r); } // tear down in reverse order boolean failed=false; for( int i=buildEnvironments.size()-1; i>=0; i-- ) { if (!buildEnvironments.get(i).tearDown(MavenModuleSetBuild.this,listener)) { failed=true; } } // WARNING The return in the finally clause will trump any return before if (failed) return Result.FAILURE; } } return r; } catch (AbortException e) { if(e.getMessage()!=null) listener.error(e.getMessage()); return Result.FAILURE; } catch (InterruptedIOException e) { e.printStackTrace(listener.error("Aborted Maven execution for InterruptedIOException")); return Executor.currentExecutor().abortResult(); } catch (IOException e) { e.printStackTrace(listener.error(Messages.MavenModuleSetBuild_FailedToParsePom())); return Result.FAILURE; } catch (RunnerAbortedException e) { return Result.FAILURE; } catch (RuntimeException e) { // bug in the code. e.printStackTrace(listener.error("Processing failed due to a bug in the code. Please report this to [email protected]")); logger.println("project="+project); logger.println("project.getModules()="+project.getModules()); logger.println("project.getRootModule()="+project.getRootModule()); throw e; } finally { if (project.getSettingConfigId() != null) { // restore to null if as was modified project.setAlternateSettings( null ); project.save(); } // delete tmp files used for MavenSettingsProvider FileUtils.deleteQuietly( tmpSettingsFile ); if (remoteSettings != null) { remoteSettings.delete(); } FileUtils.deleteQuietly( tmpGlobalSettingsFile ); if (project.getGlobalSettingConfigId() != null ) { remoteGlobalSettings.delete(); } } }
diff --git a/ttools/src/testcases/uk/ac/starlink/ttools/task/TableMatch2Test.java b/ttools/src/testcases/uk/ac/starlink/ttools/task/TableMatch2Test.java index 7733744f9..16099cb8e 100644 --- a/ttools/src/testcases/uk/ac/starlink/ttools/task/TableMatch2Test.java +++ b/ttools/src/testcases/uk/ac/starlink/ttools/task/TableMatch2Test.java @@ -1,157 +1,157 @@ package uk.ac.starlink.ttools.task; import java.util.logging.Level; import java.util.logging.Logger; import uk.ac.starlink.table.ColumnData; import uk.ac.starlink.table.StarTable; import uk.ac.starlink.table.Tables; import uk.ac.starlink.task.UsageException; import uk.ac.starlink.ttools.QuickTable; import uk.ac.starlink.ttools.TableTestCase; import uk.ac.starlink.ttools.join.MatchEngineParameter; public class TableMatch2Test extends TableTestCase { private final StarTable t1_; private final StarTable t2_; public TableMatch2Test( String name ) { super( name ); t1_ = new QuickTable( 3, new ColumnData[] { col( "X", new double[] { 1134.822, 659.68, 909.613 } ), col( "Y", new double[] { 599.247, 1046.874, 543.293 } ), col( "Vmag", new double[] { 13.8, 17.2, 9.3 } ), } ); t2_ = new QuickTable( 4, new ColumnData[] { col( "X", new double[] { 909.523, 1832.114, 1135.201, 702.622 } ), col( "Y", new double[] { 543.800, 409.567, 600.100, 1004.972 } ), col( "Bmag", new double[] { 10.1, 12.3, 14.6, 19.0 } ), } ); Logger.getLogger( "uk.ac.starlink.ttools.task" ) .setLevel( Level.WARNING ); } public void testCols() throws Exception { String[] cols12sep = new String[] { "X_1", "Y_1", "Vmag", "X_2", "Y_2", "Bmag", "Separation" }; assertArrayEquals( cols12sep, getColNames( join12( "1and2", "best", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "1or2", "all", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "all1", "all", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "all2", "all", 1.0 ) ) ); assertArrayEquals( new String[] { "X_1", "Y_1", "Vmag", "X_2", "Y_2", "Bmag" }, getColNames( join12( "1xor2", "all", 1.0 ) ) ); assertArrayEquals( - new String[] { "X_1", "Y_1", "Vmag", "X_2", "Y_2", "Bmag" }, + cols12sep, getColNames( join12( "1and2", "all", 0.5 ) ) ); assertArrayEquals( new String[] { "X", "Y", "Vmag" }, getColNames( join12( "1not2", "best", 1.0 ) ) ); assertArrayEquals( new String[] { "X", "Y", "Bmag" }, getColNames( join12( "2not1", "all", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "1and2", "best", 1.0, null, null ) ) ); assertArrayEquals( new String[] { "X", "Y", "Vmag", "X", "Y", "Bmag", "Separation" }, getColNames( join12( "1and2", "best", 1.0, "", "" ) ) ); assertArrayEquals( new String[] { "X_1", "Y_1", "Vmag", "X", "Y", "Bmag", "Separation" }, getColNames( join12( "1and2", "best", 1.0, null, "" ) ) ); assertArrayEquals( new String[] { "X-a", "Y-a", "Vmag", "X-b", "Y-b", "Bmag", "Separation" }, getColNames( join12( "1or2", "best", 1.0, "-a", "-b" ) ) ); } public void testRows() throws Exception { assertEquals( 2L, join12( "1and2", "best", 1.0 ).getRowCount() ); assertEquals( 5L, join12( "1or2", "best", 1.0 ).getRowCount() ); assertEquals( 3L, join12( "all1", "best", 1.0 ).getRowCount() ); assertEquals( 4L, join12( "all2", "best", 1.0 ).getRowCount() ); assertEquals( 1L, join12( "1not2", "best", 1.0 ).getRowCount() ); assertEquals( 2L, join12( "2not1", "best", 1.0 ).getRowCount() ); assertEquals( 3L, join12( "1xor2", "best", 1.0 ).getRowCount() ); } public void testAnd() throws Exception { StarTable tAnd = join12( "1and2", "best", 1.0 ); assertArrayEquals( box( new double[] { 1134.822, 909.613 } ), getColData( tAnd, 0 ) ); assertArrayEquals( box( new double[] { 600.100, 543.800 } ), getColData( tAnd, 4 ) ); assertArrayEquals( new double[] { 0.933, 0.515 }, unbox( getColData( tAnd, 6 ) ), 0.0005 ); assertEquals( 2, join12( "1and2", "best", 0.934 ).getRowCount() ); assertEquals( 1, join12( "1and2", "best", 0.932 ).getRowCount() ); assertEquals( 1, join12( "1and2", "best", 0.516 ).getRowCount() ); assertEquals( 0, join12( "1and2", "best", 0.514 ).getRowCount() ); } public void testNot() throws Exception { StarTable tNot = join12( "1not2", "best", 1.0 ); assertArrayEquals( new double[] { 659.68, 1046.874, 17.2 }, unbox( tNot.getRow( 0 ) ) ); assertEquals( 1L, tNot.getRowCount() ); } public void testExamples() throws UsageException { String[] examps = MatchEngineParameter.getExampleValues(); MatchEngineParameter matcherParam = new MatchEngineParameter( "matcher" ); for ( int i = 0; i < examps.length; i++ ) { assertTrue( matcherParam.createEngine( examps[ i ] ) != null ); } } private StarTable join12( String join, String find, double err ) throws Exception { return join12( join, find, err, null, null ); } private StarTable join12( String join, String find, double err, String duptag1, String duptag2 ) throws Exception { MapEnvironment env = new MapEnvironment() .setValue( "in1", t1_ ) .setValue( "in2", t2_ ) .setValue( "matcher", "2d" ) .setValue( "values1", "X Y" ) .setValue( "values2", "X Y" ) .setValue( "params", Double.toString( err ) ) .setValue( "join", join ) .setValue( "find", find ) .setValue( "fixcols", "dups" ); if ( duptag1 != null ) { env.setValue( "suffix1", duptag1 ); } if ( duptag2 != null ) { env.setValue( "suffix2", duptag2 ); } new TableMatch2().createExecutable( env ).execute(); StarTable result = env.getOutputTable( "omode" ); if ( result != null ) { Tables.checkTable( result ); } return result; } }
true
true
public void testCols() throws Exception { String[] cols12sep = new String[] { "X_1", "Y_1", "Vmag", "X_2", "Y_2", "Bmag", "Separation" }; assertArrayEquals( cols12sep, getColNames( join12( "1and2", "best", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "1or2", "all", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "all1", "all", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "all2", "all", 1.0 ) ) ); assertArrayEquals( new String[] { "X_1", "Y_1", "Vmag", "X_2", "Y_2", "Bmag" }, getColNames( join12( "1xor2", "all", 1.0 ) ) ); assertArrayEquals( new String[] { "X_1", "Y_1", "Vmag", "X_2", "Y_2", "Bmag" }, getColNames( join12( "1and2", "all", 0.5 ) ) ); assertArrayEquals( new String[] { "X", "Y", "Vmag" }, getColNames( join12( "1not2", "best", 1.0 ) ) ); assertArrayEquals( new String[] { "X", "Y", "Bmag" }, getColNames( join12( "2not1", "all", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "1and2", "best", 1.0, null, null ) ) ); assertArrayEquals( new String[] { "X", "Y", "Vmag", "X", "Y", "Bmag", "Separation" }, getColNames( join12( "1and2", "best", 1.0, "", "" ) ) ); assertArrayEquals( new String[] { "X_1", "Y_1", "Vmag", "X", "Y", "Bmag", "Separation" }, getColNames( join12( "1and2", "best", 1.0, null, "" ) ) ); assertArrayEquals( new String[] { "X-a", "Y-a", "Vmag", "X-b", "Y-b", "Bmag", "Separation" }, getColNames( join12( "1or2", "best", 1.0, "-a", "-b" ) ) ); }
public void testCols() throws Exception { String[] cols12sep = new String[] { "X_1", "Y_1", "Vmag", "X_2", "Y_2", "Bmag", "Separation" }; assertArrayEquals( cols12sep, getColNames( join12( "1and2", "best", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "1or2", "all", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "all1", "all", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "all2", "all", 1.0 ) ) ); assertArrayEquals( new String[] { "X_1", "Y_1", "Vmag", "X_2", "Y_2", "Bmag" }, getColNames( join12( "1xor2", "all", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "1and2", "all", 0.5 ) ) ); assertArrayEquals( new String[] { "X", "Y", "Vmag" }, getColNames( join12( "1not2", "best", 1.0 ) ) ); assertArrayEquals( new String[] { "X", "Y", "Bmag" }, getColNames( join12( "2not1", "all", 1.0 ) ) ); assertArrayEquals( cols12sep, getColNames( join12( "1and2", "best", 1.0, null, null ) ) ); assertArrayEquals( new String[] { "X", "Y", "Vmag", "X", "Y", "Bmag", "Separation" }, getColNames( join12( "1and2", "best", 1.0, "", "" ) ) ); assertArrayEquals( new String[] { "X_1", "Y_1", "Vmag", "X", "Y", "Bmag", "Separation" }, getColNames( join12( "1and2", "best", 1.0, null, "" ) ) ); assertArrayEquals( new String[] { "X-a", "Y-a", "Vmag", "X-b", "Y-b", "Bmag", "Separation" }, getColNames( join12( "1or2", "best", 1.0, "-a", "-b" ) ) ); }
diff --git a/RequirementManager/src/edu/wpi/cs/wpisuitetng/modules/requirementmanager/view/overview/OverviewTreePanel.java b/RequirementManager/src/edu/wpi/cs/wpisuitetng/modules/requirementmanager/view/overview/OverviewTreePanel.java index 594ec336..bbccbd34 100644 --- a/RequirementManager/src/edu/wpi/cs/wpisuitetng/modules/requirementmanager/view/overview/OverviewTreePanel.java +++ b/RequirementManager/src/edu/wpi/cs/wpisuitetng/modules/requirementmanager/view/overview/OverviewTreePanel.java @@ -1,235 +1,235 @@ /******************************************************************************* * Copyright (c) 2013 WPI-Suite * 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: Team Rolling Thunder ******************************************************************************/ package edu.wpi.cs.wpisuitetng.modules.requirementmanager.view.overview; import java.awt.Dimension; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Enumeration; import java.util.List; import javax.swing.DropMode; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import edu.wpi.cs.wpisuitetng.modules.requirementmanager.models.Requirement; import edu.wpi.cs.wpisuitetng.modules.requirementmanager.models.iterations.Iteration; import edu.wpi.cs.wpisuitetng.modules.requirementmanager.models.iterations.IterationModel; import edu.wpi.cs.wpisuitetng.modules.requirementmanager.view.ViewEventController; /** * @author justinhess * @version $Revision: 1.0 $ */ public class OverviewTreePanel extends JScrollPane implements MouseListener, TreeSelectionListener{ private JTree tree; /** * Sets up the left hand panel of the overview */ public OverviewTreePanel() { this.setViewportView(tree); ViewEventController.getInstance().setOverviewTree(this); this.refresh(); } /** * Method valueChanged. * @see javax.swing.event.TreeSelectionListener#valueChanged(TreeSelectionEvent) *//* @Override public void valueChanged(TreeSelectionEvent e) { }*/ /** * This will wipe out the current tree and rebuild it */ public void refresh(){ - DefaultMutableTreeNode top = new DefaultMutableTreeNode(/*ConfigManager.getConfig().getProjectName()*/ "BEHOLD THE TREE"); //makes a starting node + DefaultMutableTreeNode top = new DefaultMutableTreeNode(/*ConfigManager.getConfig().getProjectName()*/ "Iteration Tree"); //makes a starting node List<Iteration> iterations = IterationModel.getInstance().getIterations(); //retreive the list of all iterations System.out.println("Num Iterations: " + iterations.size()); for(int i=0; i<iterations.size(); i++){ DefaultMutableTreeNode newIterNode = new DefaultMutableTreeNode(iterations.get(i)); //make a new iteration node to add List<Requirement> requirements = iterations.get(i).getRequirements(); //gets the list of requirements that is associated with the iteration //check to see if there are any requirements for the iteration if(requirements.size() > 0){ addRequirementsToTree(requirements, newIterNode); } top.add(newIterNode); //add the iteration's node to the top node } tree = new JTree(top); //create the tree with the top node as the top tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); //tell it that it can only select one thing at a time tree.setToggleClickCount(0); tree.setCellRenderer(new CustomTreeCellRenderer()); //set to custom cell renderer so that icons make sense tree.addMouseListener(this); //add a listener to check for clicking tree.addTreeSelectionListener(this); tree.setTransferHandler(new IterationTransferHandler()); tree.setDragEnabled(true); tree.setDropMode(DropMode.ON); this.setViewportView(tree); //make panel display the tree ViewEventController.getInstance().setOverviewTree(this); //update the ViewEventControler so it contains the right tree System.out.println("finished refreshing the tree"); } private void addRequirementsToTree(List<Requirement> requirements, DefaultMutableTreeNode parentNode) { for (int j = 0; j < requirements.size(); j++) { DefaultMutableTreeNode newReqNode = new DefaultMutableTreeNode(requirements.get(j)); List<Requirement> children = requirements.get(j).getChildren(); if(children.size() > 0) { addRequirementsToTree(children, newReqNode); } parentNode.add(newReqNode); } } /** * Method mouseClicked. * @param e MouseEvent * @see java.awt.event.MouseListener#mouseClicked(MouseEvent) */ @Override public void mouseClicked(MouseEvent e) { int x = e.getX(); int y = e.getY(); if (e.getClickCount() == 2) { TreePath treePath = tree.getPathForLocation(e.getX(), e.getY()); if(treePath != null) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent(); if(node != null) { if(node.getUserObject() instanceof Iteration) { ViewEventController.getInstance().editIteration((Iteration)node.getUserObject()); } if(node.getUserObject() instanceof Requirement) { ViewEventController.getInstance().editRequirement((Requirement)node.getUserObject()); } } } } /* if (SwingUtilities.isRightMouseButton(e)) { int row = tree.getClosestRowForLocation(e.getX(), e.getY()); tree.setSelectionRow(row); String label = "popup: "; JPopupMenu popup = new JPopupMenu(); popup.add(new JMenuItem(label)); popup.show(tree, x, y); } */ } /** * Method mousePressed. * @param e MouseEvent * @see java.awt.event.MouseListener#mousePressed(MouseEvent) */ @Override public void mousePressed(MouseEvent e) { } /** * Method mouseReleased. * @param e MouseEvent * @see java.awt.event.MouseListener#mouseReleased(MouseEvent) */ @Override public void mouseReleased(MouseEvent e) { } /** * Method mouseEntered. * @param e MouseEvent * @see java.awt.event.MouseListener#mouseEntered(MouseEvent) */ @Override public void mouseEntered(MouseEvent e) { } /** * Method mouseExited. * @param e MouseEvent * @see java.awt.event.MouseListener#mouseExited(MouseEvent) */ @Override public void mouseExited(MouseEvent e) { } /** * @return the tree */ public JTree getTree() { return tree; } @Override public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent(); if(node != null) { if(node.getUserObject() instanceof Iteration) { ViewEventController.getInstance().getIterationOverview().highlight((Iteration)node.getUserObject()); } else { ViewEventController.getInstance().getIterationOverview().highlight(IterationModel.getInstance().getBacklog()); } } } public void selectIteration(Iteration iteration) { DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot(); Enumeration<DefaultMutableTreeNode> e = root.breadthFirstEnumeration(); DefaultMutableTreeNode foundNode = null; while(e.hasMoreElements()) { DefaultMutableTreeNode node = e.nextElement(); if(node.getUserObject() == iteration) { foundNode = node; break; } } if(foundNode != null) { TreePath path = new TreePath(foundNode.getPath()); tree.setSelectionPath(path); tree.scrollPathToVisible(path); } } }
true
true
public void refresh(){ DefaultMutableTreeNode top = new DefaultMutableTreeNode(/*ConfigManager.getConfig().getProjectName()*/ "BEHOLD THE TREE"); //makes a starting node List<Iteration> iterations = IterationModel.getInstance().getIterations(); //retreive the list of all iterations System.out.println("Num Iterations: " + iterations.size()); for(int i=0; i<iterations.size(); i++){ DefaultMutableTreeNode newIterNode = new DefaultMutableTreeNode(iterations.get(i)); //make a new iteration node to add List<Requirement> requirements = iterations.get(i).getRequirements(); //gets the list of requirements that is associated with the iteration //check to see if there are any requirements for the iteration if(requirements.size() > 0){ addRequirementsToTree(requirements, newIterNode); } top.add(newIterNode); //add the iteration's node to the top node } tree = new JTree(top); //create the tree with the top node as the top tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); //tell it that it can only select one thing at a time tree.setToggleClickCount(0); tree.setCellRenderer(new CustomTreeCellRenderer()); //set to custom cell renderer so that icons make sense tree.addMouseListener(this); //add a listener to check for clicking tree.addTreeSelectionListener(this); tree.setTransferHandler(new IterationTransferHandler()); tree.setDragEnabled(true); tree.setDropMode(DropMode.ON); this.setViewportView(tree); //make panel display the tree ViewEventController.getInstance().setOverviewTree(this); //update the ViewEventControler so it contains the right tree System.out.println("finished refreshing the tree"); }
public void refresh(){ DefaultMutableTreeNode top = new DefaultMutableTreeNode(/*ConfigManager.getConfig().getProjectName()*/ "Iteration Tree"); //makes a starting node List<Iteration> iterations = IterationModel.getInstance().getIterations(); //retreive the list of all iterations System.out.println("Num Iterations: " + iterations.size()); for(int i=0; i<iterations.size(); i++){ DefaultMutableTreeNode newIterNode = new DefaultMutableTreeNode(iterations.get(i)); //make a new iteration node to add List<Requirement> requirements = iterations.get(i).getRequirements(); //gets the list of requirements that is associated with the iteration //check to see if there are any requirements for the iteration if(requirements.size() > 0){ addRequirementsToTree(requirements, newIterNode); } top.add(newIterNode); //add the iteration's node to the top node } tree = new JTree(top); //create the tree with the top node as the top tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); //tell it that it can only select one thing at a time tree.setToggleClickCount(0); tree.setCellRenderer(new CustomTreeCellRenderer()); //set to custom cell renderer so that icons make sense tree.addMouseListener(this); //add a listener to check for clicking tree.addTreeSelectionListener(this); tree.setTransferHandler(new IterationTransferHandler()); tree.setDragEnabled(true); tree.setDropMode(DropMode.ON); this.setViewportView(tree); //make panel display the tree ViewEventController.getInstance().setOverviewTree(this); //update the ViewEventControler so it contains the right tree System.out.println("finished refreshing the tree"); }
diff --git a/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/support/ManagedTestSuite.java b/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/support/ManagedTestSuite.java index 3313aac1..10ea9c02 100644 --- a/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/support/ManagedTestSuite.java +++ b/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/support/ManagedTestSuite.java @@ -1,194 +1,197 @@ /******************************************************************************* * Copyright (c) 2010 Tasktop Technologies and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tasktop Technologies - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.commons.tests.support; import java.net.ProxySelector; import java.net.URI; import java.net.URISyntaxException; import java.text.MessageFormat; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.Map.Entry; import java.util.regex.Pattern; import junit.framework.AssertionFailedError; import junit.framework.Test; import junit.framework.TestFailure; import junit.framework.TestListener; import junit.framework.TestResult; import junit.framework.TestSuite; import org.eclipse.core.runtime.Platform; import org.eclipse.mylyn.commons.net.WebUtil; import org.eclipse.mylyn.internal.commons.net.CommonsNetPlugin; /** * Prints the name of each test to System.err when it started and dumps a stack trace of all thread to System.err if a * test takes longer than 10 minutes. * * @author Steffen Pingel */ public class ManagedTestSuite extends TestSuite { private class DumpThreadTask extends TimerTask { private final Test test; private final Thread testThread; public DumpThreadTask(Test test) { this.test = test; this.testThread = Thread.currentThread(); } @Override public void run() { StringBuffer sb = new StringBuffer(); sb.append(MessageFormat.format("Test {0} is taking too long:\n", test.toString())); Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces(); for (Map.Entry<Thread, StackTraceElement[]> entry : traces.entrySet()) { sb.append(entry.getKey().toString()); sb.append("\n"); for (StackTraceElement element : entry.getValue()) { sb.append(" "); sb.append(element.toString()); sb.append("\n"); } sb.append("\n"); } System.err.println(sb.toString()); System.err.println("Sending interrupt to thread: " + testThread.toString()); testThread.interrupt(); } } private class Listener implements TestListener { private DumpThreadTask task; private final Timer timer = new Timer(true); public void addError(Test test, Throwable t) { System.err.println("[ERROR]"); } public void addFailure(Test test, AssertionFailedError t) { System.err.println("[FAILURE]"); } private void dumpList(String header, Enumeration<TestFailure> failures) { System.err.println(header); while (failures.hasMoreElements()) { TestFailure failure = failures.nextElement(); System.err.print(" "); System.err.println(failure.toString()); } } public void dumpResults(TestResult result) { System.err.println(); dumpList("Failures: ", result.failures()); System.err.println(); dumpList("Errors: ", result.errors()); int failedCount = result.errorCount() + result.failureCount(); System.err.println(); System.err.println(MessageFormat.format("{0} out of {1} tests failed", failedCount, result.runCount())); } public void endTest(Test test) { if (task != null) { task.cancel(); task = null; } } public void startTest(Test test) { System.err.println("Running " + test.toString()); task = new DumpThreadTask(test); timer.schedule(task, DELAY); } } public final static long DELAY = 10 * 60 * 1000; private final Listener listener = new Listener(); public ManagedTestSuite() { } public ManagedTestSuite(String name) { super(name); } @Override public void run(TestResult result) { result.addListener(listener); dumpSystemInfo(); super.run(result); listener.dumpResults(result); // add dummy test to dump threads in case shutdown hangs listener.startTest(new Test() { public int countTestCases() { return 1; } public void run(TestResult result) { // do nothing } @Override public String toString() { return "ShutdownWatchdog"; } }); } private static void dumpSystemInfo() { if (Platform.isRunning() && CommonsNetPlugin.getProxyService() != null - && !CommonsNetPlugin.getProxyService().isSystemProxiesEnabled()) { + && CommonsNetPlugin.getProxyService().isSystemProxiesEnabled() + && !CommonsNetPlugin.getProxyService().hasSystemProxies()) { // XXX e3.5/gtk.x86_64 activate manual proxy configuration which // defaults to Java system properties if system proxy support is // not available + System.err.println("Forcing manual proxy configuration"); + CommonsNetPlugin.getProxyService().setSystemProxiesEnabled(false); CommonsNetPlugin.getProxyService().setProxiesEnabled(true); } Properties p = System.getProperties(); if (Platform.isRunning()) { p.put("build.system", Platform.getOS() + "-" + Platform.getOSArch() + "-" + Platform.getWS()); } else { p.put("build.system", "standalone"); } String info = "System: ${os.name} ${os.version} (${os.arch}) / ${build.system} / ${java.vendor} ${java.vm.name} ${java.version}"; for (Entry<Object, Object> entry : p.entrySet()) { info = info.replaceFirst(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().toString()); } System.err.println(info); System.err.print("Proxy : " + WebUtil.getProxyForUrl("http://mylyn.eclipse.org") + " (Platform)"); try { System.err.print(" / " + ProxySelector.getDefault().select(new URI("http://mylyn.eclipse.org")) + " (Java)"); } catch (URISyntaxException e) { // ignore } System.err.println(); System.err.println(); } }
false
true
private static void dumpSystemInfo() { if (Platform.isRunning() && CommonsNetPlugin.getProxyService() != null && !CommonsNetPlugin.getProxyService().isSystemProxiesEnabled()) { // XXX e3.5/gtk.x86_64 activate manual proxy configuration which // defaults to Java system properties if system proxy support is // not available CommonsNetPlugin.getProxyService().setProxiesEnabled(true); } Properties p = System.getProperties(); if (Platform.isRunning()) { p.put("build.system", Platform.getOS() + "-" + Platform.getOSArch() + "-" + Platform.getWS()); } else { p.put("build.system", "standalone"); } String info = "System: ${os.name} ${os.version} (${os.arch}) / ${build.system} / ${java.vendor} ${java.vm.name} ${java.version}"; for (Entry<Object, Object> entry : p.entrySet()) { info = info.replaceFirst(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().toString()); } System.err.println(info); System.err.print("Proxy : " + WebUtil.getProxyForUrl("http://mylyn.eclipse.org") + " (Platform)"); try { System.err.print(" / " + ProxySelector.getDefault().select(new URI("http://mylyn.eclipse.org")) + " (Java)"); } catch (URISyntaxException e) { // ignore } System.err.println(); System.err.println(); }
private static void dumpSystemInfo() { if (Platform.isRunning() && CommonsNetPlugin.getProxyService() != null && CommonsNetPlugin.getProxyService().isSystemProxiesEnabled() && !CommonsNetPlugin.getProxyService().hasSystemProxies()) { // XXX e3.5/gtk.x86_64 activate manual proxy configuration which // defaults to Java system properties if system proxy support is // not available System.err.println("Forcing manual proxy configuration"); CommonsNetPlugin.getProxyService().setSystemProxiesEnabled(false); CommonsNetPlugin.getProxyService().setProxiesEnabled(true); } Properties p = System.getProperties(); if (Platform.isRunning()) { p.put("build.system", Platform.getOS() + "-" + Platform.getOSArch() + "-" + Platform.getWS()); } else { p.put("build.system", "standalone"); } String info = "System: ${os.name} ${os.version} (${os.arch}) / ${build.system} / ${java.vendor} ${java.vm.name} ${java.version}"; for (Entry<Object, Object> entry : p.entrySet()) { info = info.replaceFirst(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().toString()); } System.err.println(info); System.err.print("Proxy : " + WebUtil.getProxyForUrl("http://mylyn.eclipse.org") + " (Platform)"); try { System.err.print(" / " + ProxySelector.getDefault().select(new URI("http://mylyn.eclipse.org")) + " (Java)"); } catch (URISyntaxException e) { // ignore } System.err.println(); System.err.println(); }
diff --git a/src/cards/CardSicarius.java b/src/cards/CardSicarius.java index fd10472..c3358de 100644 --- a/src/cards/CardSicarius.java +++ b/src/cards/CardSicarius.java @@ -1,70 +1,71 @@ package cards; import java.util.ArrayList; import java.util.List; import cards.activators.CardParams; import cards.activators.SicariusParams; import roma.Game; import roma.GameVisor; import enums.*; public class CardSicarius extends Card { public CardNames getID() { return CardNames.Sicarius; } public String getName() { return "Sicarius"; } public int getCostToPlay() { return 9; } public int getDiceToActivate() { return 1; } public boolean isBuilding() { return false; } public String getDescription() { return "Eliminates an opposing, face-up character card. " + "The opposing card and the Sicarius are both discarded"; } public int getDefense() { return 2; } @Override public CardParams getParams() { return new SicariusParams(); } @Override public boolean performEffect(GameVisor g, int pos, CardParams a) { boolean performed = false; SicariusParams myParams = (SicariusParams) a; int enemyPos = (g.whoseTurn() + 1) % Game.MAX_PLAYERS; Card targetCard = g.getField().getCard(enemyPos, myParams.getTargetPos()); // Sicarius attacks the enemy for 9999 (ties in the Kat) - if (targetCard != null && !targetCard.isBuilding() && targetCard.onAttacked(g, this, myParams.getTargetPos(), 9999)) { + if (targetCard != null && !targetCard.isBuilding()) { + targetCard.onAttacked(g, this, myParams.getTargetPos(), 9999); performed = true; g.getField().setCard(g.whoseTurn(), pos-1, null); g.discard(this); } else { } return performed; } }
true
true
public boolean performEffect(GameVisor g, int pos, CardParams a) { boolean performed = false; SicariusParams myParams = (SicariusParams) a; int enemyPos = (g.whoseTurn() + 1) % Game.MAX_PLAYERS; Card targetCard = g.getField().getCard(enemyPos, myParams.getTargetPos()); // Sicarius attacks the enemy for 9999 (ties in the Kat) if (targetCard != null && !targetCard.isBuilding() && targetCard.onAttacked(g, this, myParams.getTargetPos(), 9999)) { performed = true; g.getField().setCard(g.whoseTurn(), pos-1, null); g.discard(this); } else { } return performed; }
public boolean performEffect(GameVisor g, int pos, CardParams a) { boolean performed = false; SicariusParams myParams = (SicariusParams) a; int enemyPos = (g.whoseTurn() + 1) % Game.MAX_PLAYERS; Card targetCard = g.getField().getCard(enemyPos, myParams.getTargetPos()); // Sicarius attacks the enemy for 9999 (ties in the Kat) if (targetCard != null && !targetCard.isBuilding()) { targetCard.onAttacked(g, this, myParams.getTargetPos(), 9999); performed = true; g.getField().setCard(g.whoseTurn(), pos-1, null); g.discard(this); } else { } return performed; }
diff --git a/easyb/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java b/easyb/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java index 794c91d..728aa7e 100644 --- a/easyb/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java +++ b/easyb/src/java/org/disco/easyb/core/delegates/EnsuringDelegate.java @@ -1,93 +1,94 @@ package org.disco.easyb.core.delegates; import groovy.lang.Closure; import org.disco.easyb.core.exception.VerificationException; /** * * @author aglover * */ public class EnsuringDelegate { /** * * @param clzz * the class of the exception type expected * @param closure * closure containing code to be run that should throw an * exception * @throws Exception */ public void ensureThrows(final Class<?> clzz, final Closure closure) throws Exception { try { closure.call(); } catch (Throwable e) { - if (!clzz.isAssignableFrom(e.getClass()) && !(e.getCause().getClass() == clzz)) { + if (!clzz.isAssignableFrom(e.getClass()) && (e.getCause() != null) + && !(e.getCause().getClass() == clzz)) { throw new VerificationException( "exception caught (" + e.getClass().getName()+ ") is not of type " + clzz + " or the cause isn't " + clzz); } } } /** * * @param expression * to be evaluated and should resolve to a boolean result * @throws Exception */ public void ensure(final boolean expression) throws Exception { if (!expression) { throw new VerificationException("the expression evaluated to false"); } } /** * * @param value * @param closure * @throws Exception */ public void ensure(final Object value, final Closure closure) throws Exception { RichlyEnsurable delegate = this.getDelegate(value); closure.setDelegate(delegate); closure.call(); } /** * * @param value * @return FlexibleDelegate instance * @throws Exception */ private RichlyEnsurable getDelegate(final Object value) throws Exception { RichlyEnsurable delegate = EnsurableFactory.manufacture(); delegate.setVerified(value); return delegate; } /** * * @param message */ public void fail(String message) { throw new VerificationException(message); } /** * * @param message * @param e */ public void fail(String message, Exception e) { throw new VerificationException(message, e); } /** * * @param message * @param expected * @param actual */ public void fail(String message, Object expected, Object actual) { throw new VerificationException(message, expected, actual); } }
true
true
public void ensureThrows(final Class<?> clzz, final Closure closure) throws Exception { try { closure.call(); } catch (Throwable e) { if (!clzz.isAssignableFrom(e.getClass()) && !(e.getCause().getClass() == clzz)) { throw new VerificationException( "exception caught (" + e.getClass().getName()+ ") is not of type " + clzz + " or the cause isn't " + clzz); } } }
public void ensureThrows(final Class<?> clzz, final Closure closure) throws Exception { try { closure.call(); } catch (Throwable e) { if (!clzz.isAssignableFrom(e.getClass()) && (e.getCause() != null) && !(e.getCause().getClass() == clzz)) { throw new VerificationException( "exception caught (" + e.getClass().getName()+ ") is not of type " + clzz + " or the cause isn't " + clzz); } } }
diff --git a/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuJsonReader.java b/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuJsonReader.java index b13b8427..d7e47657 100644 --- a/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuJsonReader.java +++ b/apvs-ptu/src/main/java/ch/cern/atlas/apvs/ptu/server/PtuJsonReader.java @@ -1,131 +1,136 @@ package ch.cern.atlas.apvs.ptu.server; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.cern.atlas.apvs.domain.Event; import ch.cern.atlas.apvs.domain.Measurement; import ch.cern.atlas.apvs.domain.Message; import com.cedarsoftware.util.io.JsonReader; public class PtuJsonReader extends JsonReader { private Logger log = LoggerFactory.getLogger(getClass().getName()); public PtuJsonReader(InputStream in) { super(in); } public PtuJsonReader(InputStream in, boolean noObjects) { super(in, noObjects); } @Override public Object readObject() throws IOException { List<Message> result = new ArrayList<Message>(); @SuppressWarnings("rawtypes") JsonObject jsonObj = (JsonObject) readIntoJsonMaps(); String sender = (String) jsonObj.get("Sender"); // String receiver = (String) jsonObj.get("Receiver"); // String frameID = (String) jsonObj.get("FrameID"); // String acknowledge = (String) jsonObj.get("Acknowledge"); @SuppressWarnings({ "rawtypes", "unchecked" }) List<JsonObject> msgs = (List<JsonObject>) jsonObj.get("Messages"); + // fix for #497 + if (msgs == null) { + log.warn("No messages in JSON from "+sender); + return result; + } JsonMessage[] messages = new JsonMessage[msgs.size()]; for (int i = 0; i < messages.length; i++) { @SuppressWarnings("rawtypes") JsonObject msg = msgs.get(i); String type = (String) msg.get("Type"); if (type.equals("Measurement")) { String sensor = (String) msg.get("Sensor"); String unit = (String) msg.get("Unit"); Number value = convertToDouble(msg.get("Value")); String time = (String)msg.get("Time"); String samplingRate = (String) msg.get("SamplingRate"); // fix for #486 and #490 if ((sensor == null) || (value == null) || (unit == null) || (time == null)) { log.warn("PTU "+sender+": Measurement contains <null> sensor, value, samplingrate, unit or time ("+sensor+", "+value+", "+unit+", "+samplingRate+", "+time+")"); continue; } Number low = convertToDouble(msg.get("DownThreshold")); Number high = convertToDouble(msg.get("UpThreshold")); // Scale down to microSievert value = Scale.getValue(value, unit); low = Scale.getLowLimit(low, unit); high = Scale.getHighLimit(high, unit); unit = Scale.getUnit(unit); result.add(new Measurement(sender, sensor, value, low, high, unit, Integer.parseInt(samplingRate), convertToDate(time))); } else if (type.equals("Event")) { result.add(new Event(sender, (String) msg.get("Sensor"), (String) msg.get("EventType"), convertToDouble(msg .get("Value")), convertToDouble(msg .get("Threshold")), (String) msg.get("Unit"), convertToDate(msg.get("Time")))); } else { log.warn("Message type not implemented: " + type); } // FIXME add other types of messages, #115 #112 #114 } // returns a list of messages return result; } private Double convertToDouble(Object number) { if ((number == null) || !(number instanceof String)) { return null; } try { return Double.parseDouble((String) number); } catch (NumberFormatException e) { return null; } } @Override protected Date convertToDate(Object rhs) { try { return PtuServerConstants.dateFormat.parse((String) rhs); } catch (ParseException e) { return null; } } public static List<Message> jsonToJava(String json) throws IOException { ByteArrayInputStream ba = new ByteArrayInputStream( json.getBytes("UTF-8")); PtuJsonReader jr = new PtuJsonReader(ba, false); @SuppressWarnings("unchecked") List<Message> result = (List<Message>) jr.readObject(); jr.close(); return result; } public static List<Message> toJava(String json) { try { return jsonToJava(json); } catch (Exception ignored) { return null; } } }
true
true
public Object readObject() throws IOException { List<Message> result = new ArrayList<Message>(); @SuppressWarnings("rawtypes") JsonObject jsonObj = (JsonObject) readIntoJsonMaps(); String sender = (String) jsonObj.get("Sender"); // String receiver = (String) jsonObj.get("Receiver"); // String frameID = (String) jsonObj.get("FrameID"); // String acknowledge = (String) jsonObj.get("Acknowledge"); @SuppressWarnings({ "rawtypes", "unchecked" }) List<JsonObject> msgs = (List<JsonObject>) jsonObj.get("Messages"); JsonMessage[] messages = new JsonMessage[msgs.size()]; for (int i = 0; i < messages.length; i++) { @SuppressWarnings("rawtypes") JsonObject msg = msgs.get(i); String type = (String) msg.get("Type"); if (type.equals("Measurement")) { String sensor = (String) msg.get("Sensor"); String unit = (String) msg.get("Unit"); Number value = convertToDouble(msg.get("Value")); String time = (String)msg.get("Time"); String samplingRate = (String) msg.get("SamplingRate"); // fix for #486 and #490 if ((sensor == null) || (value == null) || (unit == null) || (time == null)) { log.warn("PTU "+sender+": Measurement contains <null> sensor, value, samplingrate, unit or time ("+sensor+", "+value+", "+unit+", "+samplingRate+", "+time+")"); continue; } Number low = convertToDouble(msg.get("DownThreshold")); Number high = convertToDouble(msg.get("UpThreshold")); // Scale down to microSievert value = Scale.getValue(value, unit); low = Scale.getLowLimit(low, unit); high = Scale.getHighLimit(high, unit); unit = Scale.getUnit(unit); result.add(new Measurement(sender, sensor, value, low, high, unit, Integer.parseInt(samplingRate), convertToDate(time))); } else if (type.equals("Event")) { result.add(new Event(sender, (String) msg.get("Sensor"), (String) msg.get("EventType"), convertToDouble(msg .get("Value")), convertToDouble(msg .get("Threshold")), (String) msg.get("Unit"), convertToDate(msg.get("Time")))); } else { log.warn("Message type not implemented: " + type); } // FIXME add other types of messages, #115 #112 #114 } // returns a list of messages return result; }
public Object readObject() throws IOException { List<Message> result = new ArrayList<Message>(); @SuppressWarnings("rawtypes") JsonObject jsonObj = (JsonObject) readIntoJsonMaps(); String sender = (String) jsonObj.get("Sender"); // String receiver = (String) jsonObj.get("Receiver"); // String frameID = (String) jsonObj.get("FrameID"); // String acknowledge = (String) jsonObj.get("Acknowledge"); @SuppressWarnings({ "rawtypes", "unchecked" }) List<JsonObject> msgs = (List<JsonObject>) jsonObj.get("Messages"); // fix for #497 if (msgs == null) { log.warn("No messages in JSON from "+sender); return result; } JsonMessage[] messages = new JsonMessage[msgs.size()]; for (int i = 0; i < messages.length; i++) { @SuppressWarnings("rawtypes") JsonObject msg = msgs.get(i); String type = (String) msg.get("Type"); if (type.equals("Measurement")) { String sensor = (String) msg.get("Sensor"); String unit = (String) msg.get("Unit"); Number value = convertToDouble(msg.get("Value")); String time = (String)msg.get("Time"); String samplingRate = (String) msg.get("SamplingRate"); // fix for #486 and #490 if ((sensor == null) || (value == null) || (unit == null) || (time == null)) { log.warn("PTU "+sender+": Measurement contains <null> sensor, value, samplingrate, unit or time ("+sensor+", "+value+", "+unit+", "+samplingRate+", "+time+")"); continue; } Number low = convertToDouble(msg.get("DownThreshold")); Number high = convertToDouble(msg.get("UpThreshold")); // Scale down to microSievert value = Scale.getValue(value, unit); low = Scale.getLowLimit(low, unit); high = Scale.getHighLimit(high, unit); unit = Scale.getUnit(unit); result.add(new Measurement(sender, sensor, value, low, high, unit, Integer.parseInt(samplingRate), convertToDate(time))); } else if (type.equals("Event")) { result.add(new Event(sender, (String) msg.get("Sensor"), (String) msg.get("EventType"), convertToDouble(msg .get("Value")), convertToDouble(msg .get("Threshold")), (String) msg.get("Unit"), convertToDate(msg.get("Time")))); } else { log.warn("Message type not implemented: " + type); } // FIXME add other types of messages, #115 #112 #114 } // returns a list of messages return result; }
diff --git a/src/main/java/by/vsu/emdsproject/report/jasper/PersonCardReportDSWrapper.java b/src/main/java/by/vsu/emdsproject/report/jasper/PersonCardReportDSWrapper.java index f1d2731..4d41b7f 100644 --- a/src/main/java/by/vsu/emdsproject/report/jasper/PersonCardReportDSWrapper.java +++ b/src/main/java/by/vsu/emdsproject/report/jasper/PersonCardReportDSWrapper.java @@ -1,64 +1,64 @@ package by.vsu.emdsproject.report.jasper; import by.vsu.emdsproject.model.Questionnaire; import by.vsu.emdsproject.model.Student; import java.util.HashMap; /** * вытягивает все необходимые данные для отчета персональной карточки студента */ public class PersonCardReportDSWrapper implements ReportDataSourceWrapper { private Student student; public static final String templateName = "/home/anton/PersonCardReport.jasper"; public static class Parameter { public static final String CARD_NUMBER = "cardNumber"; public static final String ADMISSION_YEAR = "admissionYear"; public static final String FIO = "fio"; public static final String BITH_YEAR = "bithYear"; public static final String BITH_PLACE = "bithPlace"; public static final String RECRUIT_OFFICE = "recruitOffice"; public static final String FACULTY = "faculty"; public static final String EDUCATION = "education"; public static final String DUTY = "duty"; public static final String EDUCATION_START = "educationStart"; public static final String EDUCATION_END = "educationEnd"; public static final String RANK = "rank"; public static final String PARENT_ADDRESS = "parentAddress"; public static final String ADDRESS = "address"; } public PersonCardReportDSWrapper(Student student) { this.student = student; } public String getTemplateName() { return templateName; } public HashMap getDataSource() { Questionnaire questionnaire = student.getQuestionnaire(); HashMap map = new HashMap(); - map.put(Parameter.CARD_NUMBER, student.getId()); + map.put(Parameter.CARD_NUMBER, student.getId().toString()); map.put(Parameter.FIO, student.getLastName() + " " + student.getFirstName() + " " + student.getMiddleName()); - map.put(Parameter.ADMISSION_YEAR, questionnaire.getAdmissionYear()); - map.put(Parameter.BITH_YEAR, student.getBirthDate().getYear()); + map.put(Parameter.ADMISSION_YEAR, questionnaire.getAdmissionYear().toString()); + map.put(Parameter.BITH_YEAR, student.getBirthDate().getYear()+""); map.put(Parameter.BITH_PLACE, questionnaire.getBirthPlace()); map.put(Parameter.RECRUIT_OFFICE, questionnaire.getRecruitmentOffice()); map.put(Parameter.FACULTY, questionnaire.getFaculty()); map.put(Parameter.EDUCATION, questionnaire.getEducation()); String duty = "не служил"; if (questionnaire.getDutyStart() != null && questionnaire.getDutyEnd() != null) { duty = "c " + questionnaire.getDutyStart() + " по " + questionnaire.getDutyEnd(); } map.put(Parameter.DUTY, duty); - map.put(Parameter.EDUCATION_START, questionnaire.getEducationStartDate()); - map.put(Parameter.EDUCATION_END, questionnaire.getEducationEndDate()); + map.put(Parameter.EDUCATION_START, questionnaire.getEducationStartDate()+""); + map.put(Parameter.EDUCATION_END, questionnaire.getEducationEndDate()+""); map.put(Parameter.RANK, student.getRank()); - map.put(Parameter.PARENT_ADDRESS, questionnaire.getParentAddress()); - map.put(Parameter.ADDRESS, questionnaire.getAddress()); + map.put(Parameter.PARENT_ADDRESS, questionnaire.getParentAddress()+""); + map.put(Parameter.ADDRESS, questionnaire.getAddress()+""); return map; } }
false
true
public HashMap getDataSource() { Questionnaire questionnaire = student.getQuestionnaire(); HashMap map = new HashMap(); map.put(Parameter.CARD_NUMBER, student.getId()); map.put(Parameter.FIO, student.getLastName() + " " + student.getFirstName() + " " + student.getMiddleName()); map.put(Parameter.ADMISSION_YEAR, questionnaire.getAdmissionYear()); map.put(Parameter.BITH_YEAR, student.getBirthDate().getYear()); map.put(Parameter.BITH_PLACE, questionnaire.getBirthPlace()); map.put(Parameter.RECRUIT_OFFICE, questionnaire.getRecruitmentOffice()); map.put(Parameter.FACULTY, questionnaire.getFaculty()); map.put(Parameter.EDUCATION, questionnaire.getEducation()); String duty = "не служил"; if (questionnaire.getDutyStart() != null && questionnaire.getDutyEnd() != null) { duty = "c " + questionnaire.getDutyStart() + " по " + questionnaire.getDutyEnd(); } map.put(Parameter.DUTY, duty); map.put(Parameter.EDUCATION_START, questionnaire.getEducationStartDate()); map.put(Parameter.EDUCATION_END, questionnaire.getEducationEndDate()); map.put(Parameter.RANK, student.getRank()); map.put(Parameter.PARENT_ADDRESS, questionnaire.getParentAddress()); map.put(Parameter.ADDRESS, questionnaire.getAddress()); return map; }
public HashMap getDataSource() { Questionnaire questionnaire = student.getQuestionnaire(); HashMap map = new HashMap(); map.put(Parameter.CARD_NUMBER, student.getId().toString()); map.put(Parameter.FIO, student.getLastName() + " " + student.getFirstName() + " " + student.getMiddleName()); map.put(Parameter.ADMISSION_YEAR, questionnaire.getAdmissionYear().toString()); map.put(Parameter.BITH_YEAR, student.getBirthDate().getYear()+""); map.put(Parameter.BITH_PLACE, questionnaire.getBirthPlace()); map.put(Parameter.RECRUIT_OFFICE, questionnaire.getRecruitmentOffice()); map.put(Parameter.FACULTY, questionnaire.getFaculty()); map.put(Parameter.EDUCATION, questionnaire.getEducation()); String duty = "не служил"; if (questionnaire.getDutyStart() != null && questionnaire.getDutyEnd() != null) { duty = "c " + questionnaire.getDutyStart() + " по " + questionnaire.getDutyEnd(); } map.put(Parameter.DUTY, duty); map.put(Parameter.EDUCATION_START, questionnaire.getEducationStartDate()+""); map.put(Parameter.EDUCATION_END, questionnaire.getEducationEndDate()+""); map.put(Parameter.RANK, student.getRank()); map.put(Parameter.PARENT_ADDRESS, questionnaire.getParentAddress()+""); map.put(Parameter.ADDRESS, questionnaire.getAddress()+""); return map; }
diff --git a/src/main/java/org/sonar/ant/SonarTask.java b/src/main/java/org/sonar/ant/SonarTask.java index 5a4605f..bda9dcb 100644 --- a/src/main/java/org/sonar/ant/SonarTask.java +++ b/src/main/java/org/sonar/ant/SonarTask.java @@ -1,284 +1,285 @@ /* * Sonar Ant Task * Copyright (C) 2011 SonarSource * [email protected] * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.ant; import com.google.common.annotations.VisibleForTesting; import org.apache.tools.ant.Main; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.Environment; import org.apache.tools.ant.types.Path; import org.sonar.ant.deprecated.OldSonarTaskExecutor; import org.sonar.ant.utils.SonarAntTaskUtils; import org.sonar.runner.Runner; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; public class SonarTask extends Task { private static final String HOST_PROPERTY = "sonar.host.url"; private static final String PROPERTY_WORK_DIRECTORY = "sonar.working.directory"; private static final String DEF_VALUE_WORK_DIRECTORY = ".sonar"; private File workDir; private File baseDir; // BEGIN of deprecated fields/properties list used only by the OldSonarTaskExecutor and the associated compatibility mode private static final String ENV_PROPERTY_COMPATIBILITY_MODE = "SONAR_ANT_TASK_COMPATIBILITY_MODE"; private static final String PROPERTY_COMPATIBILITY_MODE = "sonar.anttask.compatibilitymode"; private static final String COMPATIBILITY_MODE_ON = "on"; private boolean compatibilityMode = false; private Properties taskProperties = new Properties(); private String key; private String version; private Path sources; private Path tests; private Path binaries; private Path libraries; private String initTarget; // END of deprecated properties @SuppressWarnings("unchecked") @Override public void execute() { log(Main.getAntVersion()); log("Sonar Ant Task version: " + SonarAntTaskUtils.getTaskVersion()); log("Loaded from: " + SonarAntTaskUtils.getJarPath()); log("Sonar work directory: " + getWorkDir().getAbsolutePath()); log("Sonar server: " + getServerUrl()); Properties allProps = new Properties(); allProps.putAll(getProject().getProperties()); launchAnalysis(allProps); } private void launchAnalysis(Properties properties) { if (isCompatibilityModeActivated(properties)) { // Compatibility mode is activated to prevent issues with the standard way to execute analyses (= with the Sonar Runner) log("/!\\ Sonar Ant Task running in compatibility mode: please refer to the documentation to udpate your scripts to comply with the standards.", Project.MSG_WARN); OldSonarTaskExecutor oldSonarTaskExecutor = new OldSonarTaskExecutor(this); oldSonarTaskExecutor.execute(); } else { // Standard mode Runner runner = Runner.create(properties, baseDir); - // TODO : with the following line, the Sonar Runner crashed with a DefNotFoundError on AntProject - // runner.setEnvironmentInformation("Ant", SonarAntTaskUtils.getTaskVersion()); + runner.setUnmaskedPackages("org.apache.tools.ant", "org.sonar.ant"); + runner.setEnvironmentInformation("Ant", SonarAntTaskUtils.getTaskVersion()); + runner.addContainerExtension(getProject()); runner.execute(); } } /** * Compatibility mode is activated if: * - at least one of the old deprecated properties has been set * - "sonar.anttask.compatibilitymode=on" has been passed to the JVM * - SONAR_ANT_TASK_COMPATIBILITY_MODE env variable exists and is set to "on" * - "sonar.modules" exists and references XML files */ @VisibleForTesting protected boolean isCompatibilityModeActivated(Properties properties) { return compatibilityMode || COMPATIBILITY_MODE_ON.equalsIgnoreCase(properties.getProperty(PROPERTY_COMPATIBILITY_MODE, "")) || COMPATIBILITY_MODE_ON.equalsIgnoreCase(System.getenv(ENV_PROPERTY_COMPATIBILITY_MODE)) || modulesPropertyReferencesXmlFiles(properties); } private boolean modulesPropertyReferencesXmlFiles(Properties properties) { String[] modules = getListFromProperty(properties, "sonar.modules"); for (String module : modules) { if (module.endsWith(".xml")) { return true; } } return false; } @VisibleForTesting protected String[] getListFromProperty(Properties properties, String key) { String list = properties.getProperty(key); if (list == null) { return new String[0]; } List<String> values = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(list, ","); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); values.add(token.trim()); } return values.toArray(new String[values.size()]); } @VisibleForTesting protected void setCompatibilityMode(boolean compatibilityMode) { this.compatibilityMode = compatibilityMode; } /** * @return value of property "sonar.host.url", default is "http://localhost:9000" */ public String getServerUrl() { String serverUrl = getProperties().getProperty(HOST_PROPERTY); // from task: will be dropped some day... if (serverUrl == null) { serverUrl = getProject().getProperty(HOST_PROPERTY); // from ant } if (serverUrl == null) { serverUrl = "http://localhost:9000"; // default } return serverUrl; } /** * @return work directory, default is ".sonar" in project directory */ public File getWorkDir() { if (workDir == null) { String customPath = getProject().getProperty(PROPERTY_WORK_DIRECTORY); if (customPath == null || "".equals(customPath.trim())) { workDir = new File(getBaseDir(), DEF_VALUE_WORK_DIRECTORY); } else { workDir = new File(customPath); if (!workDir.isAbsolute()) { workDir = new File(getBaseDir(), customPath); } } } return workDir; } /** * @since 1.1 */ public void setBaseDir(File baseDir) { this.baseDir = baseDir; } /** * @return base directory, default is the current project base directory * @since 1.1 */ public File getBaseDir() { if (baseDir == null) { baseDir = getProject().getBaseDir(); } return baseDir; } /* * ============================================================================= * * Methods and related properties beyond this point are all deprecated. * * They should be removed at some point of time, when backward compatibility is * not necessary any longer (= when the "org.sonar.ant.deprecated" package is * is removed) * * ============================================================================= */ public void setKey(String key) { this.key = key; this.compatibilityMode = true; } public String getKey() { return key; } public void setVersion(String version) { this.version = version; this.compatibilityMode = true; } public String getVersion() { return version; } /** * @since 1.1 */ public void setInitTarget(String initTarget) { this.initTarget = initTarget; this.compatibilityMode = true; } /** * @since 1.1 */ public String getInitTarget() { return initTarget; } public Path getSources() { return sources; } /** * Note that name of this method is important - see http://ant.apache.org/manual/develop.html#nested-elements */ public void addConfiguredProperty(Environment.Variable property) { taskProperties.setProperty(property.getKey(), property.getValue()); this.compatibilityMode = true; } public Properties getProperties() { return taskProperties; } public Path createSources() { this.compatibilityMode = true; if (sources == null) { sources = new Path(getProject()); } return sources; } public Path createTests() { this.compatibilityMode = true; if (tests == null) { tests = new Path(getProject()); } return tests; } public Path createBinaries() { this.compatibilityMode = true; if (binaries == null) { binaries = new Path(getProject()); } return binaries; } public Path createLibraries() { this.compatibilityMode = true; if (libraries == null) { libraries = new Path(getProject()); } return libraries; } }
true
true
private void launchAnalysis(Properties properties) { if (isCompatibilityModeActivated(properties)) { // Compatibility mode is activated to prevent issues with the standard way to execute analyses (= with the Sonar Runner) log("/!\\ Sonar Ant Task running in compatibility mode: please refer to the documentation to udpate your scripts to comply with the standards.", Project.MSG_WARN); OldSonarTaskExecutor oldSonarTaskExecutor = new OldSonarTaskExecutor(this); oldSonarTaskExecutor.execute(); } else { // Standard mode Runner runner = Runner.create(properties, baseDir); // TODO : with the following line, the Sonar Runner crashed with a DefNotFoundError on AntProject // runner.setEnvironmentInformation("Ant", SonarAntTaskUtils.getTaskVersion()); runner.execute(); } }
private void launchAnalysis(Properties properties) { if (isCompatibilityModeActivated(properties)) { // Compatibility mode is activated to prevent issues with the standard way to execute analyses (= with the Sonar Runner) log("/!\\ Sonar Ant Task running in compatibility mode: please refer to the documentation to udpate your scripts to comply with the standards.", Project.MSG_WARN); OldSonarTaskExecutor oldSonarTaskExecutor = new OldSonarTaskExecutor(this); oldSonarTaskExecutor.execute(); } else { // Standard mode Runner runner = Runner.create(properties, baseDir); runner.setUnmaskedPackages("org.apache.tools.ant", "org.sonar.ant"); runner.setEnvironmentInformation("Ant", SonarAntTaskUtils.getTaskVersion()); runner.addContainerExtension(getProject()); runner.execute(); } }
diff --git a/app/controllers/IssueApp.java b/app/controllers/IssueApp.java index 2e224b98..413529b9 100644 --- a/app/controllers/IssueApp.java +++ b/app/controllers/IssueApp.java @@ -1,735 +1,735 @@ package controllers; import models.*; import models.enumeration.*; import play.mvc.Http; import views.html.issue.edit; import views.html.issue.view; import views.html.issue.list; import views.html.issue.create; import utils.AccessControl; import utils.JodaDateUtil; import utils.HttpUtil; import utils.ErrorViews; import play.data.Form; import play.mvc.Call; import play.mvc.Result; import jxl.write.WriteException; import org.apache.tika.Tika; import com.avaje.ebean.Page; import com.avaje.ebean.ExpressionList; import javax.persistence.Transient; import java.io.IOException; import java.util.*; import static com.avaje.ebean.Expr.icontains; import static play.data.Form.form; public class IssueApp extends AbstractPostingApp { private static final String EXCEL_EXT = "xls"; public static class SearchCondition extends AbstractPostingApp.SearchCondition { public String state; public Boolean commentedCheck; public Long milestoneId; public Set<Long> labelIds; public String authorLoginId; public Long assigneeId; @Transient public static SearchCondition emptySearchCondition = new SearchCondition(); public SearchCondition() { super(); milestoneId = null; state = State.OPEN.name(); commentedCheck = false; } private ExpressionList<Issue> asExpressionList(Project project) { ExpressionList<Issue> el = Issue.finder.where().eq("project.id", project.id); if (filter != null) { el.or(icontains("title", filter), icontains("body", filter)); } if (authorLoginId != null && !authorLoginId.isEmpty()) { User user = User.findByLoginId(authorLoginId); if (!user.isAnonymous()) { el.eq("authorId", user.id); } else { List<Long> ids = new ArrayList<>(); for (User u : User.find.where().icontains("loginId", authorLoginId).findList()) { ids.add(u.id); } el.in("authorId", ids); } } if (assigneeId != null) { if (assigneeId == User.anonymous.id) { el.isNull("assignee"); } else { el.eq("assignee.user.id", assigneeId); el.eq("assignee.project.id", project.id); } } if (milestoneId != null) { if (milestoneId == Milestone.NULL_MILESTONE_ID) { el.isNull("milestone"); } else { el.eq("milestone.id", milestoneId); } } if (commentedCheck) { el.ge("numOfComments", AbstractPosting.NUMBER_OF_ONE_MORE_COMMENTS); } State st = State.getValue(state); if (st.equals(State.OPEN) || st.equals(State.CLOSED)) { el.eq("state", st); } if (labelIds != null) { for (Long labelId : labelIds) { el.idIn(el.query().copy().where().eq("labels.id", labelId).findIds()); } } if (orderBy != null) { el.orderBy(orderBy + " " + orderDir); } return el; } } /** * 이슈 목록 조회 * * <p>when: 프로젝트의 이슈 목록 진입, 이슈 검색</p> * * 현재 사용자가 프로젝트에 권한이 없다면 Forbidden 으로 응답한다. * 입력된 검색 조건이 있다면 적용하고 페이징 처리된 목록을 보여준다. * 요청 형식({@code format})이 엑셀(xls)일 경우 목록을 엑셀로 다운로드한다. * * @param ownerName 프로젝트 소유자 이름 * @param projectName 프로젝트 이름 * @param state 이슈 상태 (해결 / 미해결) * @param format 요청 형식 * @param pageNum 페이지 번호 * @return * @throws WriteException * @throws IOException */ public static Result issues(String ownerName, String projectName, String state, String format, int pageNum) throws WriteException, IOException { Project project = ProjectApp.getProject(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (!AccessControl.isAllowed(UserApp.currentUser(), project.asResource(), Operation.READ)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } Form<SearchCondition> issueParamForm = new Form<>(SearchCondition.class); SearchCondition searchCondition = issueParamForm.bindFromRequest().get(); searchCondition.pageNum = pageNum - 1; searchCondition.state = state; if(searchCondition.orderBy.equals("id")) { searchCondition.orderBy = "createdDate"; } String[] labelIds = request().queryString().get("labelIds"); if (labelIds != null) { for (String labelId : labelIds) { searchCondition.labelIds.add(Long.valueOf(labelId)); } } ExpressionList<Issue> el = searchCondition.asExpressionList(project); if (EXCEL_EXT.equals(format)) { byte[] excelData = Issue.excelFrom(el.findList()); String filename = HttpUtil.encodeContentDisposition( project.name + "_issues_" + JodaDateUtil.today().getTime() + "." + EXCEL_EXT); response().setHeader("Content-Type", new Tika().detect(filename)); response().setHeader("Content-Disposition", "attachment; " + filename); return ok(excelData); } else { Page<Issue> issues = el .findPagingList(ITEMS_PER_PAGE).getPage(searchCondition.pageNum); return ok(list.render("title.issueList", issues, searchCondition, project)); } } /** * 이슈 조회 * * <p>when: 단일 이슈의 상세내용 조회</p> * * 접근 권한이 없을 경우, Forbidden 으로 응답한다. * 조회하려는 이슈가 존재하지 않을 경우엔 NotFound 로 응답한다. * * @param ownerName 프로젝트 소유자 이름 * @param projectName 프로젝트 이름 * @param number 이슈 번호 * @return */ public static Result issue(String ownerName, String projectName, Long number) { Project project = ProjectApp.getProject(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } Issue issueInfo = Issue.findByNumber(project, number); if (issueInfo == null) { return notFound(ErrorViews.NotFound.render("error.notfound", project, "issue")); } if (!AccessControl.isAllowed(UserApp.currentUser(), issueInfo.asResource(), Operation.READ)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } for (IssueLabel label: issueInfo.labels) { label.refresh(); } Form<Comment> commentForm = new Form<>(Comment.class); Form<Issue> editForm = new Form<>(Issue.class).fill(Issue.findByNumber(project, number)); return ok(view.render("title.issueDetail", issueInfo, editForm, commentForm, project)); } /** * 새 이슈 등록 폼 * * <p>when: 새로운 이슈 작성</p> * * @param ownerName 프로젝트 소유자 이름 * @param projectName 프로젝트 이름 * @return * @see {@link AbstractPostingApp#newPostingForm(Project, ResourceType, play.mvc.Content)} */ public static Result newIssueForm(String ownerName, String projectName) { Project project = ProjectApp.getProject(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } return newPostingForm(project, ResourceType.ISSUE_POST, create.render("title.newIssue", new Form<>(Issue.class), project)); } /** * 여러 이슈를 한번에 갱신하려는 요청에 응답한다. * * <p>when: 이슈 목록 페이지에서 이슈를 체크하고 상단의 갱신 드롭박스를 이용해 체크한 이슈들을 갱신할 때</p> * * 갱신을 시도한 이슈들 중 하나 이상 갱신에 성공했다면 이슈 목록 페이지로 리다이렉트한다. (303 See Other) * 어떤 이슈에 대한 갱신 요청이든 모두 실패했으며, 그 중 권한 문제로 실패한 것이 한 개 이상 있다면 403 * Forbidden 으로 응답한다. * 갱신 요청이 잘못된 경우엔 400 Bad Request 로 응답한다. * * @param ownerName 프로젝트 소유자 이름 * @param projectName 프로젝트 이름 * @return * @throws IOException */ public static Result massUpdate(String ownerName, String projectName) throws IOException { Form<IssueMassUpdate> issueMassUpdateForm = new Form<>(IssueMassUpdate.class).bindFromRequest(); if (issueMassUpdateForm.hasErrors()) { return badRequest(issueMassUpdateForm.errorsAsJson()); } IssueMassUpdate issueMassUpdate = issueMassUpdateForm.get(); Project project = Project.findByOwnerAndProjectName(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound", project, null)); } int updatedItems = 0; int rejectedByPermission = 0; for (Issue issue : issueMassUpdate.issues) { issue.refresh(); if (issueMassUpdate.delete == true) { if (AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.DELETE)) { issue.delete(); continue; } else { rejectedByPermission++; continue; } } if (!AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.UPDATE)) { rejectedByPermission++; continue; } boolean assigneeChanged = false; User oldAssignee = null; if (issueMassUpdate.assignee != null) { if(issue.assignee != null) { oldAssignee = issue.assignee.user; } Assignee newAssignee = null; if (issueMassUpdate.assignee.isAnonymous()) { newAssignee = null; } else { newAssignee = Assignee.add(issueMassUpdate.assignee.id, project.id); } assigneeChanged = !issue.assigneeEquals(newAssignee); issue.assignee = newAssignee; } boolean stateChanged = false; State oldState = null; if ((issueMassUpdate.state != null) && (issue.state != issueMassUpdate.state)) { stateChanged = true; oldState = issue.state; issue.state = issueMassUpdate.state; } if (issueMassUpdate.milestone != null) { if(issueMassUpdate.milestone.isNullMilestone()) { issue.milestone = null; } else { issue.milestone = issueMassUpdate.milestone; } } if (issueMassUpdate.attachingLabel != null) { issue.labels.add(issueMassUpdate.attachingLabel); } if (issueMassUpdate.detachingLabel != null) { issue.labels.remove(issueMassUpdate.detachingLabel); } issue.update(); updatedItems++; Issue updatedIssue = Issue.finder.byId(issue.id); String urlToView = routes.IssueApp.issue(issue.project.owner, issue.project.name, issue.getNumber()).absoluteURL(request()); if(assigneeChanged) { addAssigneeChangedNotification(oldAssignee, updatedIssue, urlToView); } if(stateChanged) { addStateChangedNotification(oldState, updatedIssue, urlToView); } } if (updatedItems == 0 && rejectedByPermission > 0) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } // Response as JSON on XHR - String contentType = HttpUtil.getPreferType(request(), "application/json"); + String contentType = HttpUtil.getPreferType(request(), "application/json", "text/html"); Boolean isXHR = contentType.equals("application/json"); return isXHR ? ok() : redirect(request().getHeader("Referer")); } /** * 새 이슈 등록 * * <p>when: 새 이슈 등록 폼에서 저장</p> * * 이슈 생성 권한이 없다면 Forbidden 으로 응답한다. * 입력 폼에 문제가 있다면 BadRequest 로 응답한다. * 이슈 저장전에 임시적으로 사용자에게 첨부되었던 첨부파일들을 이슈 하위로 옮긴다, * 저장 이후 목록 화면으로 돌아간다. * * @param ownerName 프로젝트 소유자 이름 * @param projectName 프로젝트 이름 * @return * @throws IOException */ public static Result newIssue(String ownerName, String projectName) throws IOException { Form<Issue> issueForm = new Form<>(Issue.class).bindFromRequest(); Project project = ProjectApp.getProject(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } if (!AccessControl.isProjectResourceCreatable(UserApp.currentUser(), project, ResourceType.ISSUE_POST)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } if (issueForm.hasErrors()) { return badRequest(create.render(issueForm.errors().toString(), issueForm, project)); } final Issue newIssue = issueForm.get(); newIssue.createdDate = JodaDateUtil.now(); newIssue.setAuthor(UserApp.currentUser()); newIssue.project = project; newIssue.state = State.OPEN; addLabels(newIssue.labels, request()); setMilestone(issueForm, newIssue); newIssue.save(); // Attach all of the files in the current user's temporary storage. Attachment.moveAll(UserApp.currentUser().asResource(), newIssue.asResource()); final Call issueCall = routes.IssueApp.issue(project.owner, project.name, newIssue.getNumber()); String title = NotificationEvent.formatNewTitle(newIssue); Set<User> watchers = newIssue.getWatchers(); watchers.addAll(NotificationEvent.getMentionedUsers(newIssue.body)); watchers.remove(newIssue.getAuthor()); NotificationEvent notiEvent = new NotificationEvent(); notiEvent.created = new Date(); notiEvent.title = title; notiEvent.senderId = UserApp.currentUser().id; notiEvent.receivers = watchers; notiEvent.urlToView = issueCall.absoluteURL(request()); notiEvent.resourceId = newIssue.id.toString(); notiEvent.resourceType = newIssue.asResource().getType(); notiEvent.type = NotificationType.NEW_ISSUE; notiEvent.oldValue = null; notiEvent.newValue = newIssue.body; NotificationEvent.add(notiEvent); return redirect(issueCall); } /** * 이슈 수정 폼 * * <p>when: 기존 이슈 수정</p> * * 이슈 수정 권한이 없을 경우 Forbidden 으로 응답한다. * * @param ownerName 프로젝트 소유자 이름 * @param projectName 프로젝트 이름 * @param number 이슈 번호 * @return */ public static Result editIssueForm(String ownerName, String projectName, Long number) { Project project = ProjectApp.getProject(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } Issue issue = Issue.findByNumber(project, number); if (!AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.UPDATE)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } Form<Issue> editForm = new Form<>(Issue.class).fill(issue); return ok(edit.render("title.editIssue", editForm, issue, project)); } /** * 이슈 상태 전이 * * <p>when: 특정 이슈를 다음 상태로 전이시킬 때</p> * * OPEN 된 이슈의 다음 상태는 CLOSED가 된다. * 단, CLOSED 된 상태의 이슈를 다음 상태로 전이시키면 OPEN 상태가 된다. * * @param ownerName 프로젝트 소유자 이름 * @param projectName 프로젝트 이름 * @param number 이슈 번호 * @return * @throws IOException */ public static Result nextState(String ownerName, String projectName, Long number) { Project project = ProjectApp.getProject(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } final Issue issue = Issue.findByNumber(project, number); Call redirectTo = routes.IssueApp.issue(project.owner, project.name, number); if (!AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.UPDATE)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", issue.project)); } issue.toNextState(); addStateChangedNotification(issue.previousState(), issue, redirectTo.absoluteURL(request() )); return redirect(redirectTo); } /** * 이슈 수정 * * <p>when: 이슈 수정 폼에서 저장</p> * * 폼에서 전달 받은 내용, 마일스톤, 라벨 정보와 * 기존 이슈에 작성되어 있던 댓글 정보를 정리하여 저장한다. * 저장후 목록 화면으로 돌아간다. * * @param ownerName 프로젝트 소유자 이름 * @param projectName 프로젝트 이름 * @param number 이슈 번호 * @return * @throws IOException * @see {@link AbstractPostingApp#editPosting(models.AbstractPosting, models.AbstractPosting, play.data.Form} */ public static Result editIssue(String ownerName, String projectName, Long number) throws IOException { Form<Issue> issueForm = new Form<>(Issue.class).bindFromRequest(); final Issue issue = issueForm.get(); setMilestone(issueForm, issue); Project project = ProjectApp.getProject(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } final Issue originalIssue = Issue.findByNumber(project, number); Call redirectTo = routes.IssueApp.issue(project.owner, project.name, number); // updateIssueBeforeSave.run would be called just before this issue is saved. // It updates some properties only for issues, such as assignee or labels, but not for non-issues. Runnable updateIssueBeforeSave = new Runnable() { @Override public void run() { issue.comments = originalIssue.comments; addLabels(issue.labels, request()); } }; Result result = editPosting(originalIssue, issue, issueForm, redirectTo, updateIssueBeforeSave); if(!originalIssue.assigneeEquals(issue.assignee)) { Issue updatedIssue = Issue.finder.byId(originalIssue.id); User oldAssignee = null; if(originalIssue.assignee != null) { oldAssignee = originalIssue.assignee.user; } addAssigneeChangedNotification(oldAssignee, updatedIssue, redirectTo.absoluteURL(request())); } if(issue.state != originalIssue.state) { Issue updatedIssue = Issue.finder.byId(originalIssue.id); addStateChangedNotification(issue.state, updatedIssue, redirectTo.absoluteURL(request() )); } return result; } /** * 상태 변경에 대한 notification을 등록한다. * * 등록된 notification은 사이트 메인 페이지를 통해 사용자에게 보여지며 또한 * {@link models.NotificationMail#startSchedule()} 에 의해 메일로 발송된다. * * @param oldState * @param updatedIssue * @param urlToView */ private static void addStateChangedNotification(State oldState, Issue updatedIssue, String urlToView) { NotificationEvent notiEvent = new NotificationEvent(); notiEvent.oldValue = oldState.state(); notiEvent.newValue = updatedIssue.state.state(); notiEvent.receivers = updatedIssue.getWatchers(); notiEvent.receivers.remove(UserApp.currentUser()); notiEvent.senderId = UserApp.currentUser().id; notiEvent.title = NotificationEvent.formatReplyTitle(updatedIssue); notiEvent.created = new Date(); notiEvent.urlToView = urlToView; notiEvent.resourceId = updatedIssue.id.toString(); notiEvent.resourceType = updatedIssue.asResource().getType(); notiEvent.type = NotificationType.ISSUE_STATE_CHANGED; NotificationEvent.add(notiEvent); } /** * 담당자 변경에 대한 notification을 등록한다. * * 등록된 notification은 사이트 메인 페이지를 통해 사용자에게 보여지며 또한 * {@link models.NotificationMail#startSchedule()} 에 의해 메일로 발송된다. * * @param oldAssignee * @param updatedIssue * @param urlToView */ private static void addAssigneeChangedNotification(User oldAssignee, Issue updatedIssue, String urlToView) { NotificationEvent notiEvent = new NotificationEvent(); Set<User> receivers = updatedIssue.getWatchers(); if(oldAssignee != null) { notiEvent.oldValue = oldAssignee.loginId; receivers.add(oldAssignee); } receivers.remove(UserApp.currentUser()); notiEvent.title = NotificationEvent.formatReplyTitle(updatedIssue); if (updatedIssue.assignee != null) { notiEvent.newValue = User.find.byId(updatedIssue.assignee.user.id).loginId; } notiEvent.created = new Date(); notiEvent.senderId = UserApp.currentUser().id; notiEvent.receivers = receivers; notiEvent.urlToView = urlToView; notiEvent.resourceId = updatedIssue.id.toString(); notiEvent.resourceType = updatedIssue.asResource().getType(); notiEvent.type = NotificationType.ISSUE_ASSIGNEE_CHANGED; NotificationEvent.add(notiEvent); } /* * form 에서 전달받은 마일스톤ID를 이용해서 이슈객체에 마일스톤 객체를 set한다 */ private static void setMilestone(Form<Issue> issueForm, Issue issue) { String milestoneId = issueForm.data().get("milestoneId"); if(milestoneId != null && !milestoneId.isEmpty()) { issue.milestone = Milestone.findById(Long.parseLong(milestoneId)); } else { issue.milestone = null; } } /** * 이슈 삭제 * * <p>when: 이슈 조회화면에서 삭제</p> * * 이슈 번호에 해당하는 이슈 삭제 후 이슈 목록 화면으로 돌아간다. * * @param ownerName 프로젝트 소유자 이름 * @param projectName 프로젝트 이름 * @param number 이슈 번호 * @return * @ see {@link AbstractPostingApp#delete(play.db.ebean.Model, models.resource.Resource, Call)} */ public static Result deleteIssue(String ownerName, String projectName, Long number) { Project project = ProjectApp.getProject(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } Issue issue = Issue.findByNumber(project, number); Call redirectTo = routes.IssueApp.issues(project.owner, project.name, State.OPEN.state(), "html", 1); return delete(issue, issue.asResource(), redirectTo); } /** * 댓글 작성 * * <p>when: 이슈 조회화면에서 댓글 작성하고 저장</p> * * 현재 사용자를 댓글 작성자로 하여 저장하고 이슈 조회화면으로 돌아간다. * * @param ownerName 프로젝트 소유자 이름 * @param projectName 프로젝트 이름 * @param number 이슈 번호 * @return * @throws IOException * @see {@link AbstractPostingApp#newComment(models.Comment, play.data.Form} */ public static Result newComment(String ownerName, String projectName, Long number) throws IOException { Project project = Project.findByOwnerAndProjectName(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound")); } final Issue issue = Issue.findByNumber(project, number); Call redirectTo = routes.IssueApp.issue(project.owner, project.name, number); Form<IssueComment> commentForm = new Form<>(IssueComment.class) .bindFromRequest(); if (commentForm.hasErrors()) { return badRequest(ErrorViews.BadRequest.render(commentForm.errors().toString(), project)); } if (!AccessControl.isProjectResourceCreatable( UserApp.currentUser(), project, ResourceType.ISSUE_COMMENT)) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } final IssueComment comment = commentForm.get(); return newComment(comment, commentForm, redirectTo, new Runnable() { @Override public void run() { comment.issue = issue; } }); } /** * 댓글 삭제 * * <p>when: 댓글 삭제 버튼</p> * * 댓글을 삭제하고 이슈 조회 화면으로 돌아간다. * 삭제 권한이 없을 경우 Forbidden 으로 응답한다. * * @param ownerName 프로젝트 소유자 이름 * @param projectName 프로젝트 이름 * @param issueNumber 이슈 번호 * @param commentId 댓글ID * @return * @see {@link AbstractPostingApp#delete(play.db.ebean.Model, models.resource.Resource, Call)} */ public static Result deleteComment(String ownerName, String projectName, Long issueNumber, Long commentId) { Comment comment = IssueComment.find.byId(commentId); Project project = comment.asResource().getProject(); Call redirectTo = routes.IssueApp.issue(project.owner, project.name, issueNumber); return delete(comment, comment.asResource(), redirectTo); } /** * 이슈 라벨 구성 * * <p>when: 새로 이슈를 작성하거나, 기존 이슈를 수정할때</p> * * {@code request} 에서 이슈 라벨 ID들을 추출하여 이에 대응하는 이슈라벨 정보들을 * {@code labels} 에 저장한다. * * @param labels 이슈 라벨을 저장할 대상 * @param request 요청 정보 (이슈라벨 ID를 추출하여 사용한다) */ public static void addLabels(Set<IssueLabel> labels, Http.Request request) { Http.MultipartFormData multipart = request.body().asMultipartFormData(); Map<String, String[]> form; if (multipart != null) { form = multipart.asFormUrlEncoded(); } else { form = request.body().asFormUrlEncoded(); } String[] labelIds = form.get("labelIds"); if (labelIds != null) { for (String labelId : labelIds) { labels.add(IssueLabel.finder.byId(Long.parseLong(labelId))); } } } }
true
true
public static Result massUpdate(String ownerName, String projectName) throws IOException { Form<IssueMassUpdate> issueMassUpdateForm = new Form<>(IssueMassUpdate.class).bindFromRequest(); if (issueMassUpdateForm.hasErrors()) { return badRequest(issueMassUpdateForm.errorsAsJson()); } IssueMassUpdate issueMassUpdate = issueMassUpdateForm.get(); Project project = Project.findByOwnerAndProjectName(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound", project, null)); } int updatedItems = 0; int rejectedByPermission = 0; for (Issue issue : issueMassUpdate.issues) { issue.refresh(); if (issueMassUpdate.delete == true) { if (AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.DELETE)) { issue.delete(); continue; } else { rejectedByPermission++; continue; } } if (!AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.UPDATE)) { rejectedByPermission++; continue; } boolean assigneeChanged = false; User oldAssignee = null; if (issueMassUpdate.assignee != null) { if(issue.assignee != null) { oldAssignee = issue.assignee.user; } Assignee newAssignee = null; if (issueMassUpdate.assignee.isAnonymous()) { newAssignee = null; } else { newAssignee = Assignee.add(issueMassUpdate.assignee.id, project.id); } assigneeChanged = !issue.assigneeEquals(newAssignee); issue.assignee = newAssignee; } boolean stateChanged = false; State oldState = null; if ((issueMassUpdate.state != null) && (issue.state != issueMassUpdate.state)) { stateChanged = true; oldState = issue.state; issue.state = issueMassUpdate.state; } if (issueMassUpdate.milestone != null) { if(issueMassUpdate.milestone.isNullMilestone()) { issue.milestone = null; } else { issue.milestone = issueMassUpdate.milestone; } } if (issueMassUpdate.attachingLabel != null) { issue.labels.add(issueMassUpdate.attachingLabel); } if (issueMassUpdate.detachingLabel != null) { issue.labels.remove(issueMassUpdate.detachingLabel); } issue.update(); updatedItems++; Issue updatedIssue = Issue.finder.byId(issue.id); String urlToView = routes.IssueApp.issue(issue.project.owner, issue.project.name, issue.getNumber()).absoluteURL(request()); if(assigneeChanged) { addAssigneeChangedNotification(oldAssignee, updatedIssue, urlToView); } if(stateChanged) { addStateChangedNotification(oldState, updatedIssue, urlToView); } } if (updatedItems == 0 && rejectedByPermission > 0) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } // Response as JSON on XHR String contentType = HttpUtil.getPreferType(request(), "application/json"); Boolean isXHR = contentType.equals("application/json"); return isXHR ? ok() : redirect(request().getHeader("Referer")); }
public static Result massUpdate(String ownerName, String projectName) throws IOException { Form<IssueMassUpdate> issueMassUpdateForm = new Form<>(IssueMassUpdate.class).bindFromRequest(); if (issueMassUpdateForm.hasErrors()) { return badRequest(issueMassUpdateForm.errorsAsJson()); } IssueMassUpdate issueMassUpdate = issueMassUpdateForm.get(); Project project = Project.findByOwnerAndProjectName(ownerName, projectName); if (project == null) { return notFound(ErrorViews.NotFound.render("error.notfound", project, null)); } int updatedItems = 0; int rejectedByPermission = 0; for (Issue issue : issueMassUpdate.issues) { issue.refresh(); if (issueMassUpdate.delete == true) { if (AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.DELETE)) { issue.delete(); continue; } else { rejectedByPermission++; continue; } } if (!AccessControl.isAllowed(UserApp.currentUser(), issue.asResource(), Operation.UPDATE)) { rejectedByPermission++; continue; } boolean assigneeChanged = false; User oldAssignee = null; if (issueMassUpdate.assignee != null) { if(issue.assignee != null) { oldAssignee = issue.assignee.user; } Assignee newAssignee = null; if (issueMassUpdate.assignee.isAnonymous()) { newAssignee = null; } else { newAssignee = Assignee.add(issueMassUpdate.assignee.id, project.id); } assigneeChanged = !issue.assigneeEquals(newAssignee); issue.assignee = newAssignee; } boolean stateChanged = false; State oldState = null; if ((issueMassUpdate.state != null) && (issue.state != issueMassUpdate.state)) { stateChanged = true; oldState = issue.state; issue.state = issueMassUpdate.state; } if (issueMassUpdate.milestone != null) { if(issueMassUpdate.milestone.isNullMilestone()) { issue.milestone = null; } else { issue.milestone = issueMassUpdate.milestone; } } if (issueMassUpdate.attachingLabel != null) { issue.labels.add(issueMassUpdate.attachingLabel); } if (issueMassUpdate.detachingLabel != null) { issue.labels.remove(issueMassUpdate.detachingLabel); } issue.update(); updatedItems++; Issue updatedIssue = Issue.finder.byId(issue.id); String urlToView = routes.IssueApp.issue(issue.project.owner, issue.project.name, issue.getNumber()).absoluteURL(request()); if(assigneeChanged) { addAssigneeChangedNotification(oldAssignee, updatedIssue, urlToView); } if(stateChanged) { addStateChangedNotification(oldState, updatedIssue, urlToView); } } if (updatedItems == 0 && rejectedByPermission > 0) { return forbidden(ErrorViews.Forbidden.render("error.forbidden", project)); } // Response as JSON on XHR String contentType = HttpUtil.getPreferType(request(), "application/json", "text/html"); Boolean isXHR = contentType.equals("application/json"); return isXHR ? ok() : redirect(request().getHeader("Referer")); }
diff --git a/dotnet/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java b/dotnet/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java index 54b7e1677..4c1bf3117 100644 --- a/dotnet/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java +++ b/dotnet/sonar/sonar-plugin-sourcemonitor/src/test/java/org/sonar/plugin/dotnet/srcmon/SourceMonitorResultParserTest.java @@ -1,74 +1,73 @@ /* * Maven and Sonar plugin for .Net * Copyright (C) 2010 Jose Chillan and Alexandre Victoor * mailto: [email protected] or [email protected] * * Sonar 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. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugin.dotnet.srcmon; import static org.junit.Assert.*; import java.io.File; import java.io.IOException; import java.util.List; import org.junit.Test; import org.sonar.plugin.dotnet.srcmon.model.FileMetrics; public class SourceMonitorResultParserTest { @Test public void testParse() throws IOException { File reportFile = new File("target/test-classes/solution/MessyTestSolution/target/metrics-report.xml"); simpleTest(reportFile); } /** * Same as above with a latinlocale where ',' is the decimal delimiter instead of '.' * See http://jira.codehaus.org/browse/SONARPLUGINS-965 * @throws IOException */ @Test public void testParseLatinLocale() throws IOException { File reportFile = new File("target/test-classes/solution/MessyTestSolution/target/metrics-report-latin.xml"); simpleTest(reportFile); } private void simpleTest(File reportFile) throws IOException { SourceMonitorResultParser parser = new SourceMonitorResultStaxParser(); - File moneyFile = new File("target/test-classes/solution/MessyTestSolution/MessyTestApplication/Money.cs"); List<FileMetrics> metrics = parser.parse(reportFile); assertNotNull(metrics); assertEquals(5, metrics.size()); FileMetrics firstFile = metrics.get(0); assertEquals(62, firstFile.getComplexity()); - assertEquals(moneyFile.getCanonicalPath(), firstFile.getSourcePath().getCanonicalPath()); + assertTrue(firstFile.getSourcePath().getCanonicalPath().endsWith("Money.cs")); assertEquals(3, firstFile.getCountClasses()); assertEquals(29, firstFile.getCommentLines()); assertEquals(1.77, firstFile.getAverageComplexity(),0.00001D); assertEquals("MessyTestApplication.Money", firstFile.getClassName()); assertEquals(10, firstFile.getCountAccessors()); assertEquals(53, firstFile.getCountBlankLines()); assertEquals(3, firstFile.getCountCalls()); assertEquals(387, firstFile.getCountLines()); assertEquals(11, firstFile.getCountMethods()); assertEquals(4, firstFile.getCountMethodStatements()); assertEquals(199, firstFile.getCountStatements()); assertEquals(10, firstFile.getDocumentationLines()); } }
false
true
private void simpleTest(File reportFile) throws IOException { SourceMonitorResultParser parser = new SourceMonitorResultStaxParser(); File moneyFile = new File("target/test-classes/solution/MessyTestSolution/MessyTestApplication/Money.cs"); List<FileMetrics> metrics = parser.parse(reportFile); assertNotNull(metrics); assertEquals(5, metrics.size()); FileMetrics firstFile = metrics.get(0); assertEquals(62, firstFile.getComplexity()); assertEquals(moneyFile.getCanonicalPath(), firstFile.getSourcePath().getCanonicalPath()); assertEquals(3, firstFile.getCountClasses()); assertEquals(29, firstFile.getCommentLines()); assertEquals(1.77, firstFile.getAverageComplexity(),0.00001D); assertEquals("MessyTestApplication.Money", firstFile.getClassName()); assertEquals(10, firstFile.getCountAccessors()); assertEquals(53, firstFile.getCountBlankLines()); assertEquals(3, firstFile.getCountCalls()); assertEquals(387, firstFile.getCountLines()); assertEquals(11, firstFile.getCountMethods()); assertEquals(4, firstFile.getCountMethodStatements()); assertEquals(199, firstFile.getCountStatements()); assertEquals(10, firstFile.getDocumentationLines()); }
private void simpleTest(File reportFile) throws IOException { SourceMonitorResultParser parser = new SourceMonitorResultStaxParser(); List<FileMetrics> metrics = parser.parse(reportFile); assertNotNull(metrics); assertEquals(5, metrics.size()); FileMetrics firstFile = metrics.get(0); assertEquals(62, firstFile.getComplexity()); assertTrue(firstFile.getSourcePath().getCanonicalPath().endsWith("Money.cs")); assertEquals(3, firstFile.getCountClasses()); assertEquals(29, firstFile.getCommentLines()); assertEquals(1.77, firstFile.getAverageComplexity(),0.00001D); assertEquals("MessyTestApplication.Money", firstFile.getClassName()); assertEquals(10, firstFile.getCountAccessors()); assertEquals(53, firstFile.getCountBlankLines()); assertEquals(3, firstFile.getCountCalls()); assertEquals(387, firstFile.getCountLines()); assertEquals(11, firstFile.getCountMethods()); assertEquals(4, firstFile.getCountMethodStatements()); assertEquals(199, firstFile.getCountStatements()); assertEquals(10, firstFile.getDocumentationLines()); }
diff --git a/src/frontend/org/voltcore/network/VoltNetworkPool.java b/src/frontend/org/voltcore/network/VoltNetworkPool.java index 5fa3907f3..f4c99d793 100644 --- a/src/frontend/org/voltcore/network/VoltNetworkPool.java +++ b/src/frontend/org/voltcore/network/VoltNetworkPool.java @@ -1,119 +1,119 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2012 VoltDB Inc. * * 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.voltcore.network; import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicLong; import org.voltcore.logging.VoltLogger; import org.voltcore.utils.Pair; public class VoltNetworkPool { private static final VoltLogger m_logger = new VoltLogger(VoltNetworkPool.class.getName()); private static final VoltLogger networkLog = new VoltLogger("NETWORK"); private final VoltNetwork m_networks[]; private final AtomicLong m_nextWorkerSelection = new AtomicLong(); public VoltNetworkPool() { this(1, null); } public VoltNetworkPool(int numThreads, ScheduledExecutorService ses) { if (numThreads < 1) { throw new IllegalArgumentException("Must specify a postive number of threads"); } m_networks = new VoltNetwork[numThreads]; for (int ii = 0; ii < numThreads; ii++) { m_networks[ii] = new VoltNetwork(ii, ses); } } public void start() { for (VoltNetwork vn : m_networks) { vn.start(); } } public void shutdown() throws InterruptedException { for (VoltNetwork vn : m_networks) { vn.shutdown(); } } public Connection registerChannel( final SocketChannel channel, final InputHandler handler) throws IOException { return registerChannel( channel, handler, SelectionKey.OP_READ); } public Connection registerChannel( final SocketChannel channel, final InputHandler handler, final int interestOps) throws IOException { VoltNetwork vn = m_networks[(int)(m_nextWorkerSelection.incrementAndGet() % m_networks.length)]; return vn.registerChannel(channel, handler, interestOps); } public List<Long> getThreadIds() { ArrayList<Long> ids = new ArrayList<Long>(); for (VoltNetwork vn : m_networks) { ids.add(vn.getThreadId()); } return ids; } public Map<Long, Pair<String, long[]>> getIOStats(final boolean interval) throws ExecutionException, InterruptedException { HashMap<Long, Pair<String, long[]>> retval = new HashMap<Long, Pair<String, long[]>>(); LinkedList<Future<Map<Long, Pair<String, long[]>>>> statTasks = new LinkedList<Future<Map<Long, Pair<String, long[]>>>>(); for (VoltNetwork vn : m_networks) { statTasks.add(vn.getIOStats(interval)); } long globalStats[] = null; for (Future<Map<Long, Pair<String, long[]>>> statsFuture : statTasks) { Map<Long, Pair<String, long[]>> stats = statsFuture.get(); if (globalStats == null) { globalStats = stats.get(-1L).getSecond(); } else { - int ii = 0; - for (long stat : stats.get(-1L).getSecond()) { - globalStats[ii] += stat; + final long localStats[] = stats.get(-1L).getSecond(); + for (int ii = 0; ii < localStats.length; ii++) { + globalStats[ii] += localStats[ii]; } } retval.putAll(stats); } retval.put(-1L, Pair.of("GLOBAL", globalStats)); return retval; } }
true
true
public Map<Long, Pair<String, long[]>> getIOStats(final boolean interval) throws ExecutionException, InterruptedException { HashMap<Long, Pair<String, long[]>> retval = new HashMap<Long, Pair<String, long[]>>(); LinkedList<Future<Map<Long, Pair<String, long[]>>>> statTasks = new LinkedList<Future<Map<Long, Pair<String, long[]>>>>(); for (VoltNetwork vn : m_networks) { statTasks.add(vn.getIOStats(interval)); } long globalStats[] = null; for (Future<Map<Long, Pair<String, long[]>>> statsFuture : statTasks) { Map<Long, Pair<String, long[]>> stats = statsFuture.get(); if (globalStats == null) { globalStats = stats.get(-1L).getSecond(); } else { int ii = 0; for (long stat : stats.get(-1L).getSecond()) { globalStats[ii] += stat; } } retval.putAll(stats); } retval.put(-1L, Pair.of("GLOBAL", globalStats)); return retval; }
public Map<Long, Pair<String, long[]>> getIOStats(final boolean interval) throws ExecutionException, InterruptedException { HashMap<Long, Pair<String, long[]>> retval = new HashMap<Long, Pair<String, long[]>>(); LinkedList<Future<Map<Long, Pair<String, long[]>>>> statTasks = new LinkedList<Future<Map<Long, Pair<String, long[]>>>>(); for (VoltNetwork vn : m_networks) { statTasks.add(vn.getIOStats(interval)); } long globalStats[] = null; for (Future<Map<Long, Pair<String, long[]>>> statsFuture : statTasks) { Map<Long, Pair<String, long[]>> stats = statsFuture.get(); if (globalStats == null) { globalStats = stats.get(-1L).getSecond(); } else { final long localStats[] = stats.get(-1L).getSecond(); for (int ii = 0; ii < localStats.length; ii++) { globalStats[ii] += localStats[ii]; } } retval.putAll(stats); } retval.put(-1L, Pair.of("GLOBAL", globalStats)); return retval; }
diff --git a/src/nl/giantit/minecraft/GiantShop/core/Commands/buy.java b/src/nl/giantit/minecraft/GiantShop/core/Commands/buy.java index 314a46a..c99bae0 100644 --- a/src/nl/giantit/minecraft/GiantShop/core/Commands/buy.java +++ b/src/nl/giantit/minecraft/GiantShop/core/Commands/buy.java @@ -1,434 +1,437 @@ package nl.giantit.minecraft.GiantShop.core.Commands; import nl.giantit.minecraft.GiantShop.GiantShop; import nl.giantit.minecraft.GiantShop.core.config; import nl.giantit.minecraft.GiantShop.core.perm; import nl.giantit.minecraft.GiantShop.core.Database.db; import nl.giantit.minecraft.GiantShop.core.Items.*; import nl.giantit.minecraft.GiantShop.core.Logger.*; import nl.giantit.minecraft.GiantShop.core.Eco.iEco; import nl.giantit.minecraft.GiantShop.Misc.Heraut; import nl.giantit.minecraft.GiantShop.Misc.Messages; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.material.MaterialData; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; import java.util.logging.Level; /** * * @author Giant */ public class buy { private static config conf = config.Obtain(); private static db DB = db.Obtain(); private static perm perms = perm.Obtain(); private static Messages mH = GiantShop.getPlugin().getMsgHandler(); private static Items iH = GiantShop.getPlugin().getItemHandler(); private static iEco eH = GiantShop.getPlugin().getEcoHandler().getEngine(); public static void buy(Player player, String[] args) { Heraut.savePlayer(player); if(perms.has(player, "giantshop.shop.buy")) { if(args.length >= 2) { int itemID; Integer itemType = -1; int quantity; if(!args[1].matches("[0-9]+:[0-9]+")) { try { itemID = Integer.parseInt(args[1]); itemType = -1; }catch(NumberFormatException e) { ItemID key = iH.getItemIDByName(args[1]); if(key != null) { itemID = key.getId(); itemType = key.getType(); }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound")); return; } }catch(Exception e) { if(conf.getBoolean("GiantShop.global.debug") == true) { GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage()); GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace()); } Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown")); return; } }else{ try { String[] data = args[1].split(":"); itemID = Integer.parseInt(data[0]); itemType = Integer.parseInt(data[1]); }catch(NumberFormatException e) { HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "buy"); Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "syntaxError", data)); return; }catch(Exception e) { if(conf.getBoolean("GiantShop.global.debug") == true) { GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage()); GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace()); } Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown")); return; } } if(args.length >= 3) { try { quantity = Integer.parseInt(args[2]); quantity = (quantity > 0) ? quantity : 1; }catch(NumberFormatException e) { //Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "invQuantity")); Heraut.say("As you did not specify a normal quantity, we'll just use 1 ok? :)"); quantity = 1; } }else quantity = 1; Integer iT = ((itemType == null || itemType == -1 || itemType == 0) ? null : itemType); if(iH.isValidItem(itemID, iT)) { ArrayList<String> fields = new ArrayList<String>(); fields.add("perStack"); fields.add("sellFor"); fields.add("stock"); fields.add("maxStock"); fields.add("shops"); HashMap<String, String> where = new HashMap<String, String>(); where.put("itemID", String.valueOf(itemID)); where.put("type", String.valueOf((itemType == null || itemType <= 0) ? -1 : itemType)); ArrayList<HashMap<String, String>> resSet = DB.select(fields).from("#__items").where(where).execQuery(); if(resSet.size() == 1) { HashMap<String, String> res = resSet.get(0); if(!res.get("sellFor").equals("-1.0")) { String name = iH.getItemNameByID(itemID, iT); int perStack = Integer.parseInt(res.get("perStack")); int stock = Integer.parseInt(res.get("stock")); int maxStock = Integer.parseInt(res.get("maxStock")); double sellFor = Double.parseDouble(res.get("sellFor")); double balance = eH.getBalance(player); double cost = sellFor * (double) quantity; int amount = perStack * quantity; if(!conf.getBoolean("GiantShop.stock.useStock") || stock == -1 || (stock - amount) >= 0) { if(conf.getBoolean("GiantShop.stock.useStock") && conf.getBoolean("GiantShop.stock.stockDefinesCost") && maxStock != -1 && stock != -1) { double maxInfl = conf.getDouble("GiantShop.stock.maxInflation"); double maxDefl = conf.getDouble("GiantShop.stock.maxDeflation"); int atmi = conf.getInt("GiantShop.stock.amountTillMaxInflation"); int atmd = conf.getInt("GiantShop.stock.amountTillMaxDeflation"); double split = Math.round((atmi + atmd) / 2); if(maxStock <= atmi + atmd); { split = maxStock / 2; atmi = 0; atmd = maxStock; } if(stock >= atmd) { cost = (sellFor * (1.0 - maxDefl / 100.0)) * (double) quantity; }else if(stock <= atmi) { cost = (sellFor * (1.0 + maxInfl / 100.0)) * (double) quantity; }else{ if(stock < split) { cost = (double)Math.round(((sellFor * (1.0 + (maxInfl / stock) / 100)) * (double) quantity) * 100.0) / 100.0; }else if(stock > split) { cost = 2.0 + (double)Math.round(((sellFor / (maxDefl * stock / 100)) * (double) quantity) * 100.0) / 100.0; } } } if((balance - cost) < 0) { HashMap<String, String> data = new HashMap<String, String>(); data.put("needed", String.valueOf(cost)); data.put("have", String.valueOf(balance)); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "insufFunds", data)); }else{ if(eH.withdraw(player, cost)) { ItemStack iStack; Inventory inv = player.getInventory(); if(itemType != null && itemType != -1) { - iStack = new MaterialData(itemID, (byte) ((int) itemType)).toItemStack(amount); + if(itemID != 373) + iStack = new MaterialData(itemID, (byte) ((int) itemType)).toItemStack(amount); + else + iStack = new ItemStack(itemID, amount, (short) ((int) itemType)); }else{ iStack = new ItemStack(itemID, amount); } if(conf.getBoolean("GiantShop.global.broadcastBuy")) Heraut.broadcast(player.getName() + " bought some " + name); Heraut.say("You have just bought " + amount + " of " + name + " for " + cost); Heraut.say("Your new balance is: " + eH.getBalance(player)); Logger.Log(LoggerType.BUY, player, "{id: " + String.valueOf(itemID) + "; " + "type:" + String.valueOf((itemType == null || itemType <= 0) ? -1 : itemType) + "; " + "oS:" + String.valueOf(stock) + "; " + "nS:" + String.valueOf(stock - amount) + "; " + "amount:" + String.valueOf(amount) + ";" + "total:" + String.valueOf(cost) + ";}"); HashMap<Integer, ItemStack> left; left = inv.addItem(iStack); if(conf.getBoolean("GiantShop.stock.useStock") && stock != -1) { HashMap<String, String> t = new HashMap<String, String>(); t.put("stock", String.valueOf((stock - amount))); DB.update("#__items").set(t).where(where).updateQuery(); } if(!left.isEmpty()) { Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "infFull")); for(Map.Entry<Integer, ItemStack> stack : left.entrySet()) { player.getWorld().dropItem(player.getLocation(), stack.getValue()); } } } } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("name", String.valueOf(cost)); Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemOutOfStock", data)); } //More future stuff /*if(conf.getBoolean("GiantShop.Location.useGiantShopLocation") == true) { * ArrayList<Indaface> shops = GiantShop.getPlugin().getLocationHandler().parseShops(res.get("shops")); * for(Indaface shop : shops) { * if(shop.inShop(player.getLocation())) { * //Player can get the item he wants! :D * } * } * }else{ * //Just a global store then :) * } */ }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "notForSale")); } }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noneOrMoreResults")); } }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound")); } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "buy"); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "syntaxError", data)); } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "buy"); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "noPermissions", data)); } } public static void gift(Player player, String[] args) { Heraut.savePlayer(player); if(perms.has(player, "giantshop.shop.gift")) { if(args.length >= 3) { Player giftReceiver = GiantShop.getPlugin().getServer().getPlayer(args[1]); if(giftReceiver == null) { Heraut.say("Receiver does not exist!"); }else if(!giftReceiver.isOnline()) { Heraut.say("Gift receiver is not online!"); }else{ int itemID; Integer itemType = -1; int quantity; if(!args[2].matches("[0-9]+:[0-9]+")) { try { itemID = Integer.parseInt(args[2]); itemType = -1; }catch(NumberFormatException e) { ItemID key = iH.getItemIDByName(args[2]); if(key != null) { itemID = key.getId(); itemType = key.getType(); }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound")); return; } }catch(Exception e) { if(conf.getBoolean("GiantShop.global.debug") == true) { GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage()); GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace()); } Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown")); return; } }else{ try { String[] data = args[2].split(":"); itemID = Integer.parseInt(data[0]); itemType = Integer.parseInt(data[1]); }catch(NumberFormatException e) { HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "gift"); Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "syntaxError", data)); return; }catch(Exception e) { if(conf.getBoolean("GiantShop.global.debug") == true) { GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage()); GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace()); } Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown")); return; } } if(args.length >= 4) { try { quantity = Integer.parseInt(args[3]); quantity = (quantity > 0) ? quantity : 1; }catch(NumberFormatException e) { //Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "invQuantity")); Heraut.say("As you did not specify a normal quantity, we'll just use 1 ok? :)"); quantity = 1; } }else quantity = 1; Integer iT = ((itemType == null || itemType == -1 || itemType == 0) ? null : itemType); if(iH.isValidItem(itemID, iT)) { ArrayList<String> fields = new ArrayList<String>(); fields.add("perStack"); fields.add("sellFor"); fields.add("stock"); fields.add("shops"); HashMap<String, String> where = new HashMap<String, String>(); where.put("itemID", String.valueOf(itemID)); where.put("type", String.valueOf((itemType == null || itemType <= 0) ? -1 : itemType)); ArrayList<HashMap<String, String>> resSet = DB.select(fields).from("#__items").where(where).execQuery(); if(resSet.size() == 1) { HashMap<String, String> res = resSet.get(0); if(!res.get("sellFor").equals("-1.0")) { String name = iH.getItemNameByID(itemID, iT); int perStack = Integer.parseInt(res.get("perStack")); int stock = Integer.parseInt(res.get("stock")); double sellFor = Double.parseDouble(res.get("sellFor")); double balance = eH.getBalance(player); double cost = sellFor * (double) quantity; int amount = perStack * quantity; if(!conf.getBoolean("GiantShop.stock.useStock") || stock == -1 || (stock - amount) >= 0) { if((balance - cost) < 0) { HashMap<String, String> data = new HashMap<String, String>(); data.put("needed", String.valueOf(cost)); data.put("have", String.valueOf(balance)); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "insufFunds", data)); }else{ if(eH.withdraw(player, cost)) { ItemStack iStack; Inventory inv = giftReceiver.getInventory(); if(itemType != null && itemType != -1) { iStack = new MaterialData(itemID, (byte) ((int) itemType)).toItemStack(amount); }else{ iStack = new ItemStack(itemID, amount); } if(conf.getBoolean("GiantShop.global.broadcastBuy")) Heraut.broadcast(player.getName() + " gifted some " + name + " to " + giftReceiver.getDisplayName()); HashMap<String, String> data = new HashMap<String, String>(); data.put("amount", String.valueOf(amount)); data.put("item", name); data.put("giftReceiver", giftReceiver.getDisplayName()); data.put("cash", String.valueOf(cost)); Heraut.say(mH.getMsg(Messages.msgType.MAIN, "giftSender", data)); Heraut.say("Your new balance is: " + eH.getBalance(player)); data = new HashMap<String, String>(); data.put("amount", String.valueOf(amount)); data.put("item", name); data.put("giftSender", player.getDisplayName()); Heraut.say(giftReceiver, mH.getMsg(Messages.msgType.MAIN, "giftReceiver", data)); Logger.Log(LoggerType.GIFT, player, "{id: " + String.valueOf(itemID) + "; " + "type:" + String.valueOf((itemType == null || itemType <= 0) ? -1 : itemType) + "; " + "oS:" + String.valueOf(stock) + "; " + "nS:" + String.valueOf(stock - amount) + "; " + "amount:" + String.valueOf(amount) + ";" + "total:" + String.valueOf(cost) + ";" + "receiver:" + giftReceiver.getName() + "}"); HashMap<Integer, ItemStack> left; left = inv.addItem(iStack); if(conf.getBoolean("GiantShop.stock.useStock") && stock != -1) { HashMap<String, String> t = new HashMap<String, String>(); t.put("stock", String.valueOf((stock - amount))); DB.update("#__items").set(t).where(where).updateQuery(); } if(!left.isEmpty()) { Heraut.say(giftReceiver, mH.getMsg(Messages.msgType.ERROR, "infFull")); for(Map.Entry<Integer, ItemStack> stack : left.entrySet()) { giftReceiver.getWorld().dropItem(giftReceiver.getLocation(), stack.getValue()); } } } } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("name", String.valueOf(cost)); Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemOutOfStock", data)); } }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "notForSale")); } }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noneOrMoreResults")); } }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound")); } } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "gift"); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "syntaxError", data)); } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "gift"); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "noPermissions", data)); } } }
true
true
public static void buy(Player player, String[] args) { Heraut.savePlayer(player); if(perms.has(player, "giantshop.shop.buy")) { if(args.length >= 2) { int itemID; Integer itemType = -1; int quantity; if(!args[1].matches("[0-9]+:[0-9]+")) { try { itemID = Integer.parseInt(args[1]); itemType = -1; }catch(NumberFormatException e) { ItemID key = iH.getItemIDByName(args[1]); if(key != null) { itemID = key.getId(); itemType = key.getType(); }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound")); return; } }catch(Exception e) { if(conf.getBoolean("GiantShop.global.debug") == true) { GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage()); GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace()); } Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown")); return; } }else{ try { String[] data = args[1].split(":"); itemID = Integer.parseInt(data[0]); itemType = Integer.parseInt(data[1]); }catch(NumberFormatException e) { HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "buy"); Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "syntaxError", data)); return; }catch(Exception e) { if(conf.getBoolean("GiantShop.global.debug") == true) { GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage()); GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace()); } Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown")); return; } } if(args.length >= 3) { try { quantity = Integer.parseInt(args[2]); quantity = (quantity > 0) ? quantity : 1; }catch(NumberFormatException e) { //Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "invQuantity")); Heraut.say("As you did not specify a normal quantity, we'll just use 1 ok? :)"); quantity = 1; } }else quantity = 1; Integer iT = ((itemType == null || itemType == -1 || itemType == 0) ? null : itemType); if(iH.isValidItem(itemID, iT)) { ArrayList<String> fields = new ArrayList<String>(); fields.add("perStack"); fields.add("sellFor"); fields.add("stock"); fields.add("maxStock"); fields.add("shops"); HashMap<String, String> where = new HashMap<String, String>(); where.put("itemID", String.valueOf(itemID)); where.put("type", String.valueOf((itemType == null || itemType <= 0) ? -1 : itemType)); ArrayList<HashMap<String, String>> resSet = DB.select(fields).from("#__items").where(where).execQuery(); if(resSet.size() == 1) { HashMap<String, String> res = resSet.get(0); if(!res.get("sellFor").equals("-1.0")) { String name = iH.getItemNameByID(itemID, iT); int perStack = Integer.parseInt(res.get("perStack")); int stock = Integer.parseInt(res.get("stock")); int maxStock = Integer.parseInt(res.get("maxStock")); double sellFor = Double.parseDouble(res.get("sellFor")); double balance = eH.getBalance(player); double cost = sellFor * (double) quantity; int amount = perStack * quantity; if(!conf.getBoolean("GiantShop.stock.useStock") || stock == -1 || (stock - amount) >= 0) { if(conf.getBoolean("GiantShop.stock.useStock") && conf.getBoolean("GiantShop.stock.stockDefinesCost") && maxStock != -1 && stock != -1) { double maxInfl = conf.getDouble("GiantShop.stock.maxInflation"); double maxDefl = conf.getDouble("GiantShop.stock.maxDeflation"); int atmi = conf.getInt("GiantShop.stock.amountTillMaxInflation"); int atmd = conf.getInt("GiantShop.stock.amountTillMaxDeflation"); double split = Math.round((atmi + atmd) / 2); if(maxStock <= atmi + atmd); { split = maxStock / 2; atmi = 0; atmd = maxStock; } if(stock >= atmd) { cost = (sellFor * (1.0 - maxDefl / 100.0)) * (double) quantity; }else if(stock <= atmi) { cost = (sellFor * (1.0 + maxInfl / 100.0)) * (double) quantity; }else{ if(stock < split) { cost = (double)Math.round(((sellFor * (1.0 + (maxInfl / stock) / 100)) * (double) quantity) * 100.0) / 100.0; }else if(stock > split) { cost = 2.0 + (double)Math.round(((sellFor / (maxDefl * stock / 100)) * (double) quantity) * 100.0) / 100.0; } } } if((balance - cost) < 0) { HashMap<String, String> data = new HashMap<String, String>(); data.put("needed", String.valueOf(cost)); data.put("have", String.valueOf(balance)); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "insufFunds", data)); }else{ if(eH.withdraw(player, cost)) { ItemStack iStack; Inventory inv = player.getInventory(); if(itemType != null && itemType != -1) { iStack = new MaterialData(itemID, (byte) ((int) itemType)).toItemStack(amount); }else{ iStack = new ItemStack(itemID, amount); } if(conf.getBoolean("GiantShop.global.broadcastBuy")) Heraut.broadcast(player.getName() + " bought some " + name); Heraut.say("You have just bought " + amount + " of " + name + " for " + cost); Heraut.say("Your new balance is: " + eH.getBalance(player)); Logger.Log(LoggerType.BUY, player, "{id: " + String.valueOf(itemID) + "; " + "type:" + String.valueOf((itemType == null || itemType <= 0) ? -1 : itemType) + "; " + "oS:" + String.valueOf(stock) + "; " + "nS:" + String.valueOf(stock - amount) + "; " + "amount:" + String.valueOf(amount) + ";" + "total:" + String.valueOf(cost) + ";}"); HashMap<Integer, ItemStack> left; left = inv.addItem(iStack); if(conf.getBoolean("GiantShop.stock.useStock") && stock != -1) { HashMap<String, String> t = new HashMap<String, String>(); t.put("stock", String.valueOf((stock - amount))); DB.update("#__items").set(t).where(where).updateQuery(); } if(!left.isEmpty()) { Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "infFull")); for(Map.Entry<Integer, ItemStack> stack : left.entrySet()) { player.getWorld().dropItem(player.getLocation(), stack.getValue()); } } } } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("name", String.valueOf(cost)); Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemOutOfStock", data)); } //More future stuff /*if(conf.getBoolean("GiantShop.Location.useGiantShopLocation") == true) { * ArrayList<Indaface> shops = GiantShop.getPlugin().getLocationHandler().parseShops(res.get("shops")); * for(Indaface shop : shops) { * if(shop.inShop(player.getLocation())) { * //Player can get the item he wants! :D * } * } * }else{ * //Just a global store then :) * } */ }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "notForSale")); } }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noneOrMoreResults")); } }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound")); } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "buy"); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "syntaxError", data)); } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "buy"); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "noPermissions", data)); } }
public static void buy(Player player, String[] args) { Heraut.savePlayer(player); if(perms.has(player, "giantshop.shop.buy")) { if(args.length >= 2) { int itemID; Integer itemType = -1; int quantity; if(!args[1].matches("[0-9]+:[0-9]+")) { try { itemID = Integer.parseInt(args[1]); itemType = -1; }catch(NumberFormatException e) { ItemID key = iH.getItemIDByName(args[1]); if(key != null) { itemID = key.getId(); itemType = key.getType(); }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound")); return; } }catch(Exception e) { if(conf.getBoolean("GiantShop.global.debug") == true) { GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage()); GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace()); } Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown")); return; } }else{ try { String[] data = args[1].split(":"); itemID = Integer.parseInt(data[0]); itemType = Integer.parseInt(data[1]); }catch(NumberFormatException e) { HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "buy"); Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "syntaxError", data)); return; }catch(Exception e) { if(conf.getBoolean("GiantShop.global.debug") == true) { GiantShop.log.log(Level.SEVERE, "GiantShop Error: " + e.getMessage()); GiantShop.log.log(Level.INFO, "Stacktrace: " + e.getStackTrace()); } Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "unknown")); return; } } if(args.length >= 3) { try { quantity = Integer.parseInt(args[2]); quantity = (quantity > 0) ? quantity : 1; }catch(NumberFormatException e) { //Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "invQuantity")); Heraut.say("As you did not specify a normal quantity, we'll just use 1 ok? :)"); quantity = 1; } }else quantity = 1; Integer iT = ((itemType == null || itemType == -1 || itemType == 0) ? null : itemType); if(iH.isValidItem(itemID, iT)) { ArrayList<String> fields = new ArrayList<String>(); fields.add("perStack"); fields.add("sellFor"); fields.add("stock"); fields.add("maxStock"); fields.add("shops"); HashMap<String, String> where = new HashMap<String, String>(); where.put("itemID", String.valueOf(itemID)); where.put("type", String.valueOf((itemType == null || itemType <= 0) ? -1 : itemType)); ArrayList<HashMap<String, String>> resSet = DB.select(fields).from("#__items").where(where).execQuery(); if(resSet.size() == 1) { HashMap<String, String> res = resSet.get(0); if(!res.get("sellFor").equals("-1.0")) { String name = iH.getItemNameByID(itemID, iT); int perStack = Integer.parseInt(res.get("perStack")); int stock = Integer.parseInt(res.get("stock")); int maxStock = Integer.parseInt(res.get("maxStock")); double sellFor = Double.parseDouble(res.get("sellFor")); double balance = eH.getBalance(player); double cost = sellFor * (double) quantity; int amount = perStack * quantity; if(!conf.getBoolean("GiantShop.stock.useStock") || stock == -1 || (stock - amount) >= 0) { if(conf.getBoolean("GiantShop.stock.useStock") && conf.getBoolean("GiantShop.stock.stockDefinesCost") && maxStock != -1 && stock != -1) { double maxInfl = conf.getDouble("GiantShop.stock.maxInflation"); double maxDefl = conf.getDouble("GiantShop.stock.maxDeflation"); int atmi = conf.getInt("GiantShop.stock.amountTillMaxInflation"); int atmd = conf.getInt("GiantShop.stock.amountTillMaxDeflation"); double split = Math.round((atmi + atmd) / 2); if(maxStock <= atmi + atmd); { split = maxStock / 2; atmi = 0; atmd = maxStock; } if(stock >= atmd) { cost = (sellFor * (1.0 - maxDefl / 100.0)) * (double) quantity; }else if(stock <= atmi) { cost = (sellFor * (1.0 + maxInfl / 100.0)) * (double) quantity; }else{ if(stock < split) { cost = (double)Math.round(((sellFor * (1.0 + (maxInfl / stock) / 100)) * (double) quantity) * 100.0) / 100.0; }else if(stock > split) { cost = 2.0 + (double)Math.round(((sellFor / (maxDefl * stock / 100)) * (double) quantity) * 100.0) / 100.0; } } } if((balance - cost) < 0) { HashMap<String, String> data = new HashMap<String, String>(); data.put("needed", String.valueOf(cost)); data.put("have", String.valueOf(balance)); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "insufFunds", data)); }else{ if(eH.withdraw(player, cost)) { ItemStack iStack; Inventory inv = player.getInventory(); if(itemType != null && itemType != -1) { if(itemID != 373) iStack = new MaterialData(itemID, (byte) ((int) itemType)).toItemStack(amount); else iStack = new ItemStack(itemID, amount, (short) ((int) itemType)); }else{ iStack = new ItemStack(itemID, amount); } if(conf.getBoolean("GiantShop.global.broadcastBuy")) Heraut.broadcast(player.getName() + " bought some " + name); Heraut.say("You have just bought " + amount + " of " + name + " for " + cost); Heraut.say("Your new balance is: " + eH.getBalance(player)); Logger.Log(LoggerType.BUY, player, "{id: " + String.valueOf(itemID) + "; " + "type:" + String.valueOf((itemType == null || itemType <= 0) ? -1 : itemType) + "; " + "oS:" + String.valueOf(stock) + "; " + "nS:" + String.valueOf(stock - amount) + "; " + "amount:" + String.valueOf(amount) + ";" + "total:" + String.valueOf(cost) + ";}"); HashMap<Integer, ItemStack> left; left = inv.addItem(iStack); if(conf.getBoolean("GiantShop.stock.useStock") && stock != -1) { HashMap<String, String> t = new HashMap<String, String>(); t.put("stock", String.valueOf((stock - amount))); DB.update("#__items").set(t).where(where).updateQuery(); } if(!left.isEmpty()) { Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "infFull")); for(Map.Entry<Integer, ItemStack> stack : left.entrySet()) { player.getWorld().dropItem(player.getLocation(), stack.getValue()); } } } } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("name", String.valueOf(cost)); Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemOutOfStock", data)); } //More future stuff /*if(conf.getBoolean("GiantShop.Location.useGiantShopLocation") == true) { * ArrayList<Indaface> shops = GiantShop.getPlugin().getLocationHandler().parseShops(res.get("shops")); * for(Indaface shop : shops) { * if(shop.inShop(player.getLocation())) { * //Player can get the item he wants! :D * } * } * }else{ * //Just a global store then :) * } */ }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "notForSale")); } }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "noneOrMoreResults")); } }else{ Heraut.say(player, mH.getMsg(Messages.msgType.ERROR, "itemNotFound")); } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "buy"); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "syntaxError", data)); } }else{ HashMap<String, String> data = new HashMap<String, String>(); data.put("command", "buy"); Heraut.say(mH.getMsg(Messages.msgType.ERROR, "noPermissions", data)); } }
diff --git a/core/src/main/java/com/google/bitcoin/store/WalletProtobufSerializer.java b/core/src/main/java/com/google/bitcoin/store/WalletProtobufSerializer.java index 7dfbe52..15fce75 100644 --- a/core/src/main/java/com/google/bitcoin/store/WalletProtobufSerializer.java +++ b/core/src/main/java/com/google/bitcoin/store/WalletProtobufSerializer.java @@ -1,443 +1,443 @@ /** * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.bitcoin.store; import com.google.bitcoin.core.*; import com.google.bitcoin.core.TransactionConfidence.ConfidenceType; import com.google.common.base.Preconditions; import com.google.protobuf.ByteString; import com.google.protobuf.TextFormat; import org.bitcoinj.wallet.Protos; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Serialize and de-serialize a wallet to a byte stream containing a * <a href="http://code.google.com/apis/protocolbuffers/docs/overview.html">protocol buffer</a>. Protocol buffers are * a data interchange format developed by Google with an efficient binary representation, a type safe specification * language and compilers that generate code to work with those data structures for many languages. Protocol buffers * can have their format evolved over time: conceptually they represent data using (tag, length, value) tuples. The * format is defined by the <tt>bitcoin.proto</tt> file in the BitCoinJ source distribution.<p> * * This class is used through its static methods. The most common operations are writeWallet and readWallet, which do * the obvious operations on Output/InputStreams. You can use a {@link java.io.ByteArrayInputStream} and equivalent * {@link java.io.ByteArrayOutputStream} if you'd like byte arrays instead. The protocol buffer can also be manipulated * in its object form if you'd like to modify the flattened data structure before serialization to binary.<p> * * You can extend the wallet format with additional fields specific to your application if you want, but make sure * to either put the extra data in the provided extension areas, or select tag numbers that are unlikely to be used * by anyone else.<p> * * @author Miron Cuperman */ public class WalletProtobufSerializer { private static final Logger log = LoggerFactory.getLogger(WalletProtobufSerializer.class); // Used for de-serialization private Map<ByteString, Transaction> txMap; private WalletExtensionSerializer helper; // Temporary hack for migrating 0.5 wallets to 0.6 wallets. In 0.5 transactions stored the height at which they // appeared in the block chain (for the current best chain) but not the depth. In 0.6 we store both and update // every transaction every time we receive a block, so we need to fill out depth from best chain height. private int chainHeight; public WalletProtobufSerializer() { txMap = new HashMap<ByteString, Transaction>(); helper = new WalletExtensionSerializer(); } /** * Set the WalletExtensionSerializer used to create new wallet objects * and handle extensions */ public void setWalletExtensionSerializer(WalletExtensionSerializer h) { this.helper = h; } /** * Formats the given wallet (transactions and keys) to the given output stream in protocol buffer format.<p> * * Equivalent to <tt>walletToProto(wallet).writeTo(output);</tt> */ public void writeWallet(Wallet wallet, OutputStream output) throws IOException { Protos.Wallet walletProto = walletToProto(wallet); walletProto.writeTo(output); } /** * Returns the given wallet formatted as text. The text format is that used by protocol buffers and although it * can also be parsed using {@link TextFormat#merge(CharSequence, com.google.protobuf.Message.Builder)}, * it is designed more for debugging than storage. It is not well specified and wallets are largely binary data * structures anyway, consisting as they do of keys (large random numbers) and {@link Transaction}s which also * mostly contain keys and hashes. */ public String walletToText(Wallet wallet) { Protos.Wallet walletProto = walletToProto(wallet); return TextFormat.printToString(walletProto); } /** * Converts the given wallet to the object representation of the protocol buffers. This can be modified, or * additional data fields set, before serialization takes place. */ public Protos.Wallet walletToProto(Wallet wallet) { Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder(); walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId()); for (WalletTransaction wtx : wallet.getWalletTransactions()) { Protos.Transaction txProto = makeTxProto(wtx); walletBuilder.addTransaction(txProto); } for (ECKey key : wallet.getKeys()) { Protos.Key.Builder buf = Protos.Key.newBuilder().setCreationTimestamp(key.getCreationTimeSeconds() * 1000) // .setLabel() TODO .setType(Protos.Key.Type.ORIGINAL); if (key.getPrivKeyBytes() != null) buf.setPrivateKey(ByteString.copyFrom(key.getPrivKeyBytes())); // We serialize the public key even if the private key is present for speed reasons: we don't want to do // lots of slow EC math to load the wallet, we prefer to store the redundant data instead. It matters more // on mobile platforms. buf.setPublicKey(ByteString.copyFrom(key.getPubKey())); walletBuilder.addKey(buf); } Sha256Hash lastSeenBlockHash = wallet.getLastBlockSeenHash(); if (lastSeenBlockHash != null) { walletBuilder.setLastSeenBlockHash(hashToByteString(lastSeenBlockHash)); } Collection<Protos.Extension> extensions = helper.getExtensionsToWrite(wallet); for(Protos.Extension ext : extensions) { walletBuilder.addExtension(ext); } return walletBuilder.build(); } private static Protos.Transaction makeTxProto(WalletTransaction wtx) { Transaction tx = wtx.getTransaction(); Protos.Transaction.Builder txBuilder = Protos.Transaction.newBuilder(); txBuilder.setPool(Protos.Transaction.Pool.valueOf(wtx.getPool().getValue())) .setHash(hashToByteString(tx.getHash())) .setVersion((int) tx.getVersion()); if (tx.getUpdateTime() != null) { txBuilder.setUpdatedAt(tx.getUpdateTime().getTime()); } if (tx.getLockTime() > 0) { txBuilder.setLockTime((int)tx.getLockTime()); } // Handle inputs. for (TransactionInput input : tx.getInputs()) { Protos.TransactionInput.Builder inputBuilder = Protos.TransactionInput.newBuilder() .setScriptBytes(ByteString.copyFrom(input.getScriptBytes())) .setTransactionOutPointHash(hashToByteString(input.getOutpoint().getHash())) .setTransactionOutPointIndex((int) input.getOutpoint().getIndex()); if (input.hasSequence()) { inputBuilder.setSequence((int)input.getSequence()); } txBuilder.addTransactionInput(inputBuilder); } // Handle outputs. for (TransactionOutput output : tx.getOutputs()) { Protos.TransactionOutput.Builder outputBuilder = Protos.TransactionOutput.newBuilder() .setScriptBytes(ByteString.copyFrom(output.getScriptBytes())) .setValue(output.getValue().longValue()); final TransactionInput spentBy = output.getSpentBy(); if (spentBy != null) { Sha256Hash spendingHash = spentBy.getParentTransaction().getHash(); int spentByTransactionIndex = spentBy.getParentTransaction().getInputs().indexOf(spentBy); outputBuilder.setSpentByTransactionHash(hashToByteString(spendingHash)) .setSpentByTransactionIndex(spentByTransactionIndex); } txBuilder.addTransactionOutput(outputBuilder); } // Handle which blocks tx was seen in. if (tx.getAppearsInHashes() != null) { for (Sha256Hash hash : tx.getAppearsInHashes()) { txBuilder.addBlockHash(hashToByteString(hash)); } } if (tx.hasConfidence()) { TransactionConfidence confidence = tx.getConfidence(); Protos.TransactionConfidence.Builder confidenceBuilder = Protos.TransactionConfidence.newBuilder(); writeConfidence(txBuilder, confidence, confidenceBuilder); } return txBuilder.build(); } private static void writeConfidence(Protos.Transaction.Builder txBuilder, TransactionConfidence confidence, Protos.TransactionConfidence.Builder confidenceBuilder) { confidenceBuilder.setType(Protos.TransactionConfidence.Type.valueOf(confidence.getConfidenceType().getValue())); if (confidence.getConfidenceType() == ConfidenceType.BUILDING) { confidenceBuilder.setAppearedAtHeight(confidence.getAppearedAtChainHeight()); confidenceBuilder.setDepth(confidence.getDepthInBlocks()); if (confidence.getWorkDone() != null) { confidenceBuilder.setWorkDone(confidence.getWorkDone().longValue()); } } if (confidence.getConfidenceType() == ConfidenceType.DEAD) { Sha256Hash overridingHash = confidence.getOverridingTransaction().getHash(); confidenceBuilder.setOverridingTransaction(hashToByteString(overridingHash)); } for (PeerAddress address : confidence.getBroadcastBy()) { Protos.PeerAddress proto = Protos.PeerAddress.newBuilder() .setIpAddress(ByteString.copyFrom(address.getAddr().getAddress())) .setPort(address.getPort()) .setServices(address.getServices().longValue()) .build(); confidenceBuilder.addBroadcastBy(proto); } txBuilder.setConfidence(confidenceBuilder); } private static ByteString hashToByteString(Sha256Hash hash) { return ByteString.copyFrom(hash.getBytes()); } private static Sha256Hash byteStringToHash(ByteString bs) { return new Sha256Hash(bs.toByteArray()); } /** * TEMPORARY API: Used for migrating 0.5 wallets to 0.6 - during deserialization we need to know the chain height * so the depth field of transaction confidence objects can be filled out correctly. Set this before loading a * wallet. It's only used for older wallets that lack the data already. * * @param chainHeight */ public void setChainHeight(int chainHeight) { this.chainHeight = chainHeight; } /** * Parses a wallet from the given stream. The stream is expected to contain a binary serialization of a * {@link Protos.Wallet} object.<p> * * If the stream is invalid or the serialized wallet contains unsupported features, * {@link IllegalArgumentException} is thrown. * */ public Wallet readWallet(InputStream input) throws IOException { // TODO: This method should throw more specific exception types than IllegalArgumentException. Protos.Wallet walletProto = parseToProto(input); // System.out.println(TextFormat.printToString(walletProto)); NetworkParameters params = NetworkParameters.fromID(walletProto.getNetworkIdentifier()); Wallet wallet = helper.newWallet(params); // Read all keys for (Protos.Key keyProto : walletProto.getKeyList()) { if (keyProto.getType() != Protos.Key.Type.ORIGINAL) { throw new IllegalArgumentException("Unknown key type in wallet"); } byte[] privKey = null; if (keyProto.hasPrivateKey()) { privKey = keyProto.getPrivateKey().toByteArray(); } byte[] pubKey = keyProto.hasPublicKey() ? keyProto.getPublicKey().toByteArray() : null; ECKey ecKey = new ECKey(privKey, pubKey); ecKey.setCreationTimeSeconds((keyProto.getCreationTimestamp() + 500) / 1000); wallet.addKey(ecKey); } // Read all transactions and insert into the txMap. for (Protos.Transaction txProto : walletProto.getTransactionList()) { readTransaction(txProto, params); } // Update transaction outputs to point to inputs that spend them for (Protos.Transaction txProto : walletProto.getTransactionList()) { WalletTransaction wtx = connectTransactionOutputs(txProto); wallet.addWalletTransaction(wtx); } // Update the lastBlockSeenHash. if (!walletProto.hasLastSeenBlockHash()) { wallet.setLastBlockSeenHash(null); } else { wallet.setLastBlockSeenHash(byteStringToHash(walletProto.getLastSeenBlockHash())); } for (Protos.Extension extProto : walletProto.getExtensionList()) { helper.readExtension(wallet, extProto); } return wallet; } /** * Returns the loaded protocol buffer from the given byte stream. You normally want * {@link Wallet#loadFromFile(java.io.File)} instead - this method is designed for low level work involving the * wallet file format itself. */ public static Protos.Wallet parseToProto(InputStream input) throws IOException { return Protos.Wallet.parseFrom(input); } private void readTransaction(Protos.Transaction txProto, NetworkParameters params) { Transaction tx = new Transaction(params); if (txProto.hasUpdatedAt()) { tx.setUpdateTime(new Date(txProto.getUpdatedAt())); } for (Protos.TransactionOutput outputProto : txProto.getTransactionOutputList()) { BigInteger value = BigInteger.valueOf(outputProto.getValue()); byte[] scriptBytes = outputProto.getScriptBytes().toByteArray(); TransactionOutput output = new TransactionOutput(params, tx, value, scriptBytes); tx.addOutput(output); } for (Protos.TransactionInput transactionInput : txProto.getTransactionInputList()) { byte[] scriptBytes = transactionInput.getScriptBytes().toByteArray(); TransactionOutPoint outpoint = new TransactionOutPoint(params, transactionInput.getTransactionOutPointIndex(), byteStringToHash(transactionInput.getTransactionOutPointHash()) ); TransactionInput input = new TransactionInput(params, tx, scriptBytes, outpoint); if (transactionInput.hasSequence()) { input.setSequence(transactionInput.getSequence()); } tx.addInput(input); } for (ByteString blockHash : txProto.getBlockHashList()) { tx.addBlockAppearance(byteStringToHash(blockHash)); } if (txProto.hasLockTime()) { tx.setLockTime(txProto.getLockTime()); } // Transaction should now be complete. Sha256Hash protoHash = byteStringToHash(txProto.getHash()); Preconditions.checkState(tx.getHash().equals(protoHash), "Transaction did not deserialize completely: %s vs %s", tx.getHash(), protoHash); Preconditions.checkState(!txMap.containsKey(txProto.getHash()), "Wallet contained duplicate transaction %s", byteStringToHash(txProto.getHash())); txMap.put(txProto.getHash(), tx); } private WalletTransaction connectTransactionOutputs(org.bitcoinj.wallet.Protos.Transaction txProto) { Transaction tx = txMap.get(txProto.getHash()); WalletTransaction.Pool pool = WalletTransaction.Pool.valueOf(txProto.getPool().getNumber()); for (int i = 0 ; i < tx.getOutputs().size() ; i++) { TransactionOutput output = tx.getOutputs().get(i); final Protos.TransactionOutput transactionOutput = txProto.getTransactionOutput(i); if (transactionOutput.hasSpentByTransactionHash()) { Transaction spendingTx = txMap.get(transactionOutput.getSpentByTransactionHash()); final int spendingIndex = transactionOutput.getSpentByTransactionIndex(); TransactionInput input = spendingTx.getInputs().get(spendingIndex); input.connect(output); } } if (txProto.hasConfidence()) { Protos.TransactionConfidence confidenceProto = txProto.getConfidence(); TransactionConfidence confidence = tx.getConfidence(); readConfidence(tx, confidenceProto, confidence); } return new WalletTransaction(pool, tx); } private void readConfidence(Transaction tx, Protos.TransactionConfidence confidenceProto, TransactionConfidence confidence) { // We are lenient here because tx confidence is not an essential part of the wallet. // If the tx has an unknown type of confidence, ignore. if (!confidenceProto.hasType()) { log.warn("Unknown confidence type for tx {}", tx.getHashAsString()); return; } ConfidenceType confidenceType = TransactionConfidence.ConfidenceType.valueOf(confidenceProto.getType().getNumber()); confidence.setConfidenceType(confidenceType); if (confidenceProto.hasAppearedAtHeight()) { if (confidence.getConfidenceType() != ConfidenceType.BUILDING) { log.warn("Have appearedAtHeight but not BUILDING for tx {}", tx.getHashAsString()); return; } confidence.setAppearedAtChainHeight(confidenceProto.getAppearedAtHeight()); } if (confidenceProto.hasDepth()) { if (confidence.getConfidenceType() != ConfidenceType.BUILDING) { log.warn("Have depth but not BUILDING for tx {}", tx.getHashAsString()); return; } confidence.setDepthInBlocks(confidenceProto.getDepth()); } else { // TEMPORARY CODE FOR MIGRATING 0.5 WALLETS TO 0.6 - if (chainHeight != 0) { + if (chainHeight != 0 && confidenceProto.hasAppearedAtHeight()) { confidence.setDepthInBlocks(chainHeight - confidence.getAppearedAtChainHeight() + 1); } } if (confidenceProto.hasWorkDone()) { if (confidence.getConfidenceType() != ConfidenceType.BUILDING) { log.warn("Have workDone but not BUILDING for tx {}", tx.getHashAsString()); return; } confidence.setWorkDone(BigInteger.valueOf(confidenceProto.getWorkDone())); } if (confidenceProto.hasOverridingTransaction()) { if (confidence.getConfidenceType() != ConfidenceType.DEAD) { log.warn("Have overridingTransaction but not OVERRIDDEN for tx {}", tx.getHashAsString()); return; } Transaction overridingTransaction = txMap.get(confidenceProto.getOverridingTransaction()); if (overridingTransaction == null) { log.warn("Have overridingTransaction that is not in wallet for tx {}", tx.getHashAsString()); return; } confidence.setOverridingTransaction(overridingTransaction); } for (Protos.PeerAddress proto : confidenceProto.getBroadcastByList()) { InetAddress ip; try { ip = InetAddress.getByAddress(proto.getIpAddress().toByteArray()); } catch (UnknownHostException e) { throw new RuntimeException(e); // IP address is of invalid length. } int port = proto.getPort(); PeerAddress address = new PeerAddress(ip, port); address.setServices(BigInteger.valueOf(proto.getServices())); confidence.markBroadcastBy(address); } } }
true
true
private void readConfidence(Transaction tx, Protos.TransactionConfidence confidenceProto, TransactionConfidence confidence) { // We are lenient here because tx confidence is not an essential part of the wallet. // If the tx has an unknown type of confidence, ignore. if (!confidenceProto.hasType()) { log.warn("Unknown confidence type for tx {}", tx.getHashAsString()); return; } ConfidenceType confidenceType = TransactionConfidence.ConfidenceType.valueOf(confidenceProto.getType().getNumber()); confidence.setConfidenceType(confidenceType); if (confidenceProto.hasAppearedAtHeight()) { if (confidence.getConfidenceType() != ConfidenceType.BUILDING) { log.warn("Have appearedAtHeight but not BUILDING for tx {}", tx.getHashAsString()); return; } confidence.setAppearedAtChainHeight(confidenceProto.getAppearedAtHeight()); } if (confidenceProto.hasDepth()) { if (confidence.getConfidenceType() != ConfidenceType.BUILDING) { log.warn("Have depth but not BUILDING for tx {}", tx.getHashAsString()); return; } confidence.setDepthInBlocks(confidenceProto.getDepth()); } else { // TEMPORARY CODE FOR MIGRATING 0.5 WALLETS TO 0.6 if (chainHeight != 0) { confidence.setDepthInBlocks(chainHeight - confidence.getAppearedAtChainHeight() + 1); } } if (confidenceProto.hasWorkDone()) { if (confidence.getConfidenceType() != ConfidenceType.BUILDING) { log.warn("Have workDone but not BUILDING for tx {}", tx.getHashAsString()); return; } confidence.setWorkDone(BigInteger.valueOf(confidenceProto.getWorkDone())); } if (confidenceProto.hasOverridingTransaction()) { if (confidence.getConfidenceType() != ConfidenceType.DEAD) { log.warn("Have overridingTransaction but not OVERRIDDEN for tx {}", tx.getHashAsString()); return; } Transaction overridingTransaction = txMap.get(confidenceProto.getOverridingTransaction()); if (overridingTransaction == null) { log.warn("Have overridingTransaction that is not in wallet for tx {}", tx.getHashAsString()); return; } confidence.setOverridingTransaction(overridingTransaction); } for (Protos.PeerAddress proto : confidenceProto.getBroadcastByList()) { InetAddress ip; try { ip = InetAddress.getByAddress(proto.getIpAddress().toByteArray()); } catch (UnknownHostException e) { throw new RuntimeException(e); // IP address is of invalid length. } int port = proto.getPort(); PeerAddress address = new PeerAddress(ip, port); address.setServices(BigInteger.valueOf(proto.getServices())); confidence.markBroadcastBy(address); } }
private void readConfidence(Transaction tx, Protos.TransactionConfidence confidenceProto, TransactionConfidence confidence) { // We are lenient here because tx confidence is not an essential part of the wallet. // If the tx has an unknown type of confidence, ignore. if (!confidenceProto.hasType()) { log.warn("Unknown confidence type for tx {}", tx.getHashAsString()); return; } ConfidenceType confidenceType = TransactionConfidence.ConfidenceType.valueOf(confidenceProto.getType().getNumber()); confidence.setConfidenceType(confidenceType); if (confidenceProto.hasAppearedAtHeight()) { if (confidence.getConfidenceType() != ConfidenceType.BUILDING) { log.warn("Have appearedAtHeight but not BUILDING for tx {}", tx.getHashAsString()); return; } confidence.setAppearedAtChainHeight(confidenceProto.getAppearedAtHeight()); } if (confidenceProto.hasDepth()) { if (confidence.getConfidenceType() != ConfidenceType.BUILDING) { log.warn("Have depth but not BUILDING for tx {}", tx.getHashAsString()); return; } confidence.setDepthInBlocks(confidenceProto.getDepth()); } else { // TEMPORARY CODE FOR MIGRATING 0.5 WALLETS TO 0.6 if (chainHeight != 0 && confidenceProto.hasAppearedAtHeight()) { confidence.setDepthInBlocks(chainHeight - confidence.getAppearedAtChainHeight() + 1); } } if (confidenceProto.hasWorkDone()) { if (confidence.getConfidenceType() != ConfidenceType.BUILDING) { log.warn("Have workDone but not BUILDING for tx {}", tx.getHashAsString()); return; } confidence.setWorkDone(BigInteger.valueOf(confidenceProto.getWorkDone())); } if (confidenceProto.hasOverridingTransaction()) { if (confidence.getConfidenceType() != ConfidenceType.DEAD) { log.warn("Have overridingTransaction but not OVERRIDDEN for tx {}", tx.getHashAsString()); return; } Transaction overridingTransaction = txMap.get(confidenceProto.getOverridingTransaction()); if (overridingTransaction == null) { log.warn("Have overridingTransaction that is not in wallet for tx {}", tx.getHashAsString()); return; } confidence.setOverridingTransaction(overridingTransaction); } for (Protos.PeerAddress proto : confidenceProto.getBroadcastByList()) { InetAddress ip; try { ip = InetAddress.getByAddress(proto.getIpAddress().toByteArray()); } catch (UnknownHostException e) { throw new RuntimeException(e); // IP address is of invalid length. } int port = proto.getPort(); PeerAddress address = new PeerAddress(ip, port); address.setServices(BigInteger.valueOf(proto.getServices())); confidence.markBroadcastBy(address); } }
diff --git a/src/com/android/phone/GsmUmtsOptions.java b/src/com/android/phone/GsmUmtsOptions.java index 2b5bb145..703770ae 100644 --- a/src/com/android/phone/GsmUmtsOptions.java +++ b/src/com/android/phone/GsmUmtsOptions.java @@ -1,95 +1,94 @@ /* * Copyright (C) 2008, 2011 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 android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceScreen; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneFactory; /** * List of Network-specific settings screens. */ public class GsmUmtsOptions { private static final String LOG_TAG = "GsmUmtsOptions"; private PreferenceScreen mButtonAPNExpand; private PreferenceScreen mButtonOperatorSelectionExpand; private CheckBoxPreference mButtonPrefer2g; private static final String BUTTON_APN_EXPAND_KEY = "button_apn_key"; private static final String BUTTON_OPERATOR_SELECTION_EXPAND_KEY = "button_carrier_sel_key"; private static final String BUTTON_PREFER_2G_KEY = "button_prefer_2g_key"; private PreferenceActivity mPrefActivity; private PreferenceScreen mPrefScreen; public GsmUmtsOptions(PreferenceActivity prefActivity, PreferenceScreen prefScreen) { mPrefActivity = prefActivity; mPrefScreen = prefScreen; create(); } protected void create() { mPrefActivity.addPreferencesFromResource(R.xml.gsm_umts_options); mButtonAPNExpand = (PreferenceScreen) mPrefScreen.findPreference(BUTTON_APN_EXPAND_KEY); mButtonPrefer2g = (CheckBoxPreference) mPrefScreen.findPreference(BUTTON_PREFER_2G_KEY); enableScreen(); } public void enableScreen() { Phone phone = PhoneFactory.getDefaultPhone(); if (phone.getPhoneType() != Phone.PHONE_TYPE_GSM) { log("Not a GSM phone"); - mButtonAPNExpand.setEnabled(false); mButtonPrefer2g.setEnabled(false); } mButtonOperatorSelectionExpand = (PreferenceScreen) mPrefScreen .findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY); if (mButtonOperatorSelectionExpand != null) { if (phone.getPhoneType() != Phone.PHONE_TYPE_GSM) { mButtonOperatorSelectionExpand.setEnabled(false); } else if (!phone.isManualNetSelAllowed()) { mButtonOperatorSelectionExpand.setEnabled(false); } else if (mPrefActivity.getResources().getBoolean(R.bool.csp_enabled)) { if (phone.isCspPlmnEnabled()) { log("[CSP] Enabling Operator Selection menu."); mButtonOperatorSelectionExpand.setEnabled(true); } else { log("[CSP] Disabling Operator Selection menu."); mPrefScreen.removePreference(mPrefScreen .findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY)); } } } } public boolean preferenceTreeClick(Preference preference) { if (preference.getKey().equals(BUTTON_PREFER_2G_KEY)) { log("preferenceTreeClick: return true"); return true; } log("preferenceTreeClick: return false"); return false; } protected void log(String s) { android.util.Log.d(LOG_TAG, s); } }
true
true
public void enableScreen() { Phone phone = PhoneFactory.getDefaultPhone(); if (phone.getPhoneType() != Phone.PHONE_TYPE_GSM) { log("Not a GSM phone"); mButtonAPNExpand.setEnabled(false); mButtonPrefer2g.setEnabled(false); } mButtonOperatorSelectionExpand = (PreferenceScreen) mPrefScreen .findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY); if (mButtonOperatorSelectionExpand != null) { if (phone.getPhoneType() != Phone.PHONE_TYPE_GSM) { mButtonOperatorSelectionExpand.setEnabled(false); } else if (!phone.isManualNetSelAllowed()) { mButtonOperatorSelectionExpand.setEnabled(false); } else if (mPrefActivity.getResources().getBoolean(R.bool.csp_enabled)) { if (phone.isCspPlmnEnabled()) { log("[CSP] Enabling Operator Selection menu."); mButtonOperatorSelectionExpand.setEnabled(true); } else { log("[CSP] Disabling Operator Selection menu."); mPrefScreen.removePreference(mPrefScreen .findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY)); } } } }
public void enableScreen() { Phone phone = PhoneFactory.getDefaultPhone(); if (phone.getPhoneType() != Phone.PHONE_TYPE_GSM) { log("Not a GSM phone"); mButtonPrefer2g.setEnabled(false); } mButtonOperatorSelectionExpand = (PreferenceScreen) mPrefScreen .findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY); if (mButtonOperatorSelectionExpand != null) { if (phone.getPhoneType() != Phone.PHONE_TYPE_GSM) { mButtonOperatorSelectionExpand.setEnabled(false); } else if (!phone.isManualNetSelAllowed()) { mButtonOperatorSelectionExpand.setEnabled(false); } else if (mPrefActivity.getResources().getBoolean(R.bool.csp_enabled)) { if (phone.isCspPlmnEnabled()) { log("[CSP] Enabling Operator Selection menu."); mButtonOperatorSelectionExpand.setEnabled(true); } else { log("[CSP] Disabling Operator Selection menu."); mPrefScreen.removePreference(mPrefScreen .findPreference(BUTTON_OPERATOR_SELECTION_EXPAND_KEY)); } } } }
diff --git a/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/internal/core/SaxContextWriter.java b/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/internal/core/SaxContextWriter.java index 3c7e8f091..d587da7da 100644 --- a/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/internal/core/SaxContextWriter.java +++ b/org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/internal/core/SaxContextWriter.java @@ -1,196 +1,197 @@ /******************************************************************************* * Copyright (c) 2004 - 2006 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ package org.eclipse.mylar.internal.core; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import org.eclipse.mylar.core.InteractionEvent; import org.eclipse.mylar.internal.core.util.MylarStatusHandler; import org.eclipse.mylar.internal.core.util.XmlStringConverter; import org.xml.sax.ContentHandler; import org.xml.sax.DTDHandler; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.AttributesImpl; /** * @author Brock Janiczak * @author Mik Kersten (minor refactoring) */ public class SaxContextWriter implements IContextWriter { private OutputStream outputStream; public void setOutputStream(OutputStream outputStream) { this.outputStream = outputStream; } public void writeContextToStream(MylarContext context) throws IOException { if (outputStream == null) { IOException ioe = new IOException("OutputStream not set"); throw ioe; } try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(new SAXSource(new SaxWriter(), new MylarContextInputSource(context)), new StreamResult(outputStream)); } catch (TransformerException e) { MylarStatusHandler.fail(e, "could not write context", false); throw new IOException(e.getMessage()); } } private static class MylarContextInputSource extends InputSource { private MylarContext context; public MylarContextInputSource(MylarContext context) { this.context = context; } public MylarContext getContext() { return this.context; } public void setContext(MylarContext context) { this.context = context; } } private static class SaxWriter implements XMLReader { private ContentHandler handler; private ErrorHandler errorHandler; public boolean getFeature(String name) throws SAXNotRecognizedException, SAXNotSupportedException { return false; } public void setFeature(String name, boolean value) throws SAXNotRecognizedException, SAXNotSupportedException { } public Object getProperty(String name) throws SAXNotRecognizedException, SAXNotSupportedException { return null; } public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException { } public void setEntityResolver(EntityResolver resolver) { } public EntityResolver getEntityResolver() { return null; } public void setDTDHandler(DTDHandler handler) { } public DTDHandler getDTDHandler() { return null; } public void setContentHandler(ContentHandler handler) { this.handler = handler; } public ContentHandler getContentHandler() { return handler; } public void setErrorHandler(ErrorHandler handler) { this.errorHandler = handler; } public ErrorHandler getErrorHandler() { return errorHandler; } public void parse(InputSource input) throws IOException, SAXException { if (!(input instanceof MylarContextInputSource)) { throw new SAXException("Can only parse writable input sources"); } MylarContext context = ((MylarContextInputSource) input).getContext(); handler.startDocument(); AttributesImpl rootAttributes = new AttributesImpl(); rootAttributes.addAttribute("", MylarContextExternalizer.ATR_ID, MylarContextExternalizer.ATR_ID, "", context.getHandleIdentifier()); rootAttributes.addAttribute("", MylarContextExternalizer.ATR_VERSION, MylarContextExternalizer.ATR_VERSION, "", "1"); handler.startElement("", MylarContextExternalizer.ELMNT_INTERACTION_HISTORY, MylarContextExternalizer.ELMNT_INTERACTION_HISTORY, rootAttributes); + // List could get modified as we're writing for (InteractionEvent ie : new ArrayList<InteractionEvent>(context.getInteractionHistory())) { AttributesImpl ieAttributes = new AttributesImpl(); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_DELTA, MylarContextExternalizer.ATR_DELTA, "", XmlStringConverter.convertToXmlString(ie.getDelta())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_END_DATE, MylarContextExternalizer.ATR_END_DATE, "", MylarContextExternalizer.DATE_FORMAT.format(ie .getEndDate())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_INTEREST, MylarContextExternalizer.ATR_INTEREST, "", Float.toString(ie.getInterestContribution())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_KIND, MylarContextExternalizer.ATR_KIND, "", ie.getKind().toString()); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_NAVIGATION, MylarContextExternalizer.ATR_NAVIGATION, "", XmlStringConverter.convertToXmlString(ie .getNavigation())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_ORIGIN_ID, MylarContextExternalizer.ATR_ORIGIN_ID, "", XmlStringConverter.convertToXmlString(ie .getOriginId())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_START_DATE, MylarContextExternalizer.ATR_START_DATE, "", MylarContextExternalizer.DATE_FORMAT.format(ie .getDate())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_STRUCTURE_HANDLE, MylarContextExternalizer.ATR_STRUCTURE_HANDLE, "", XmlStringConverter.convertToXmlString(ie .getStructureHandle())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_STRUCTURE_KIND, MylarContextExternalizer.ATR_STRUCTURE_KIND, "", XmlStringConverter.convertToXmlString(ie .getContentType())); handler.startElement("", SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT, SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT, ieAttributes); handler.endElement("", SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT, SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT); } handler.endElement("", MylarContextExternalizer.ELMNT_INTERACTION_HISTORY, MylarContextExternalizer.ELMNT_INTERACTION_HISTORY); handler.endDocument(); } public void parse(String systemId) throws IOException, SAXException { throw new SAXException("Can only parse writable input sources"); } } }
true
true
public void parse(InputSource input) throws IOException, SAXException { if (!(input instanceof MylarContextInputSource)) { throw new SAXException("Can only parse writable input sources"); } MylarContext context = ((MylarContextInputSource) input).getContext(); handler.startDocument(); AttributesImpl rootAttributes = new AttributesImpl(); rootAttributes.addAttribute("", MylarContextExternalizer.ATR_ID, MylarContextExternalizer.ATR_ID, "", context.getHandleIdentifier()); rootAttributes.addAttribute("", MylarContextExternalizer.ATR_VERSION, MylarContextExternalizer.ATR_VERSION, "", "1"); handler.startElement("", MylarContextExternalizer.ELMNT_INTERACTION_HISTORY, MylarContextExternalizer.ELMNT_INTERACTION_HISTORY, rootAttributes); for (InteractionEvent ie : new ArrayList<InteractionEvent>(context.getInteractionHistory())) { AttributesImpl ieAttributes = new AttributesImpl(); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_DELTA, MylarContextExternalizer.ATR_DELTA, "", XmlStringConverter.convertToXmlString(ie.getDelta())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_END_DATE, MylarContextExternalizer.ATR_END_DATE, "", MylarContextExternalizer.DATE_FORMAT.format(ie .getEndDate())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_INTEREST, MylarContextExternalizer.ATR_INTEREST, "", Float.toString(ie.getInterestContribution())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_KIND, MylarContextExternalizer.ATR_KIND, "", ie.getKind().toString()); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_NAVIGATION, MylarContextExternalizer.ATR_NAVIGATION, "", XmlStringConverter.convertToXmlString(ie .getNavigation())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_ORIGIN_ID, MylarContextExternalizer.ATR_ORIGIN_ID, "", XmlStringConverter.convertToXmlString(ie .getOriginId())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_START_DATE, MylarContextExternalizer.ATR_START_DATE, "", MylarContextExternalizer.DATE_FORMAT.format(ie .getDate())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_STRUCTURE_HANDLE, MylarContextExternalizer.ATR_STRUCTURE_HANDLE, "", XmlStringConverter.convertToXmlString(ie .getStructureHandle())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_STRUCTURE_KIND, MylarContextExternalizer.ATR_STRUCTURE_KIND, "", XmlStringConverter.convertToXmlString(ie .getContentType())); handler.startElement("", SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT, SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT, ieAttributes); handler.endElement("", SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT, SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT); } handler.endElement("", MylarContextExternalizer.ELMNT_INTERACTION_HISTORY, MylarContextExternalizer.ELMNT_INTERACTION_HISTORY); handler.endDocument(); }
public void parse(InputSource input) throws IOException, SAXException { if (!(input instanceof MylarContextInputSource)) { throw new SAXException("Can only parse writable input sources"); } MylarContext context = ((MylarContextInputSource) input).getContext(); handler.startDocument(); AttributesImpl rootAttributes = new AttributesImpl(); rootAttributes.addAttribute("", MylarContextExternalizer.ATR_ID, MylarContextExternalizer.ATR_ID, "", context.getHandleIdentifier()); rootAttributes.addAttribute("", MylarContextExternalizer.ATR_VERSION, MylarContextExternalizer.ATR_VERSION, "", "1"); handler.startElement("", MylarContextExternalizer.ELMNT_INTERACTION_HISTORY, MylarContextExternalizer.ELMNT_INTERACTION_HISTORY, rootAttributes); // List could get modified as we're writing for (InteractionEvent ie : new ArrayList<InteractionEvent>(context.getInteractionHistory())) { AttributesImpl ieAttributes = new AttributesImpl(); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_DELTA, MylarContextExternalizer.ATR_DELTA, "", XmlStringConverter.convertToXmlString(ie.getDelta())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_END_DATE, MylarContextExternalizer.ATR_END_DATE, "", MylarContextExternalizer.DATE_FORMAT.format(ie .getEndDate())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_INTEREST, MylarContextExternalizer.ATR_INTEREST, "", Float.toString(ie.getInterestContribution())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_KIND, MylarContextExternalizer.ATR_KIND, "", ie.getKind().toString()); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_NAVIGATION, MylarContextExternalizer.ATR_NAVIGATION, "", XmlStringConverter.convertToXmlString(ie .getNavigation())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_ORIGIN_ID, MylarContextExternalizer.ATR_ORIGIN_ID, "", XmlStringConverter.convertToXmlString(ie .getOriginId())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_START_DATE, MylarContextExternalizer.ATR_START_DATE, "", MylarContextExternalizer.DATE_FORMAT.format(ie .getDate())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_STRUCTURE_HANDLE, MylarContextExternalizer.ATR_STRUCTURE_HANDLE, "", XmlStringConverter.convertToXmlString(ie .getStructureHandle())); ieAttributes.addAttribute("", MylarContextExternalizer.ATR_STRUCTURE_KIND, MylarContextExternalizer.ATR_STRUCTURE_KIND, "", XmlStringConverter.convertToXmlString(ie .getContentType())); handler.startElement("", SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT, SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT, ieAttributes); handler.endElement("", SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT, SaxContextContentHandler.ATTRIBUTE_INTERACTION_EVENT); } handler.endElement("", MylarContextExternalizer.ELMNT_INTERACTION_HISTORY, MylarContextExternalizer.ELMNT_INTERACTION_HISTORY); handler.endDocument(); }
diff --git a/yamodroid/src/main/java/ru/yandex/money/droid/YandexMoneyDroid.java b/yamodroid/src/main/java/ru/yandex/money/droid/YandexMoneyDroid.java index f1c9b87..11f6041 100644 --- a/yamodroid/src/main/java/ru/yandex/money/droid/YandexMoneyDroid.java +++ b/yamodroid/src/main/java/ru/yandex/money/droid/YandexMoneyDroid.java @@ -1,196 +1,198 @@ package ru.yandex.money.droid; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import ru.yandex.money.api.rights.Permission; import java.math.BigDecimal; import java.util.Collection; import java.util.HashMap; /** * User: mdv * Date: 09.03.12 * Time: 14:31 */ public class YandexMoneyDroid { private final String clientId; private int activityCodeAuth; private DialogListener dialogListenerAuth; private int activityCodeHistory; private DialogListener dialogListenerHistory; private int activityCodeHistoryDetail; private DialogListener dialogListenerHistoryDetail; private int activityCodePaymentP2P; private DialogListener dialogListenerPaymentP2P; private DialogListener dialogListenerPaymentShop; private int activityCodePaymentShop; public YandexMoneyDroid(String clientId) { this.clientId = clientId; } public void authorize(Activity activity, int activityCode, String redirectUri, Collection<Permission> permissions, boolean showResultDialog, DialogListener dialogListener) { authorize(activity, activityCode, redirectUri, permissions, null, showResultDialog, dialogListener); } public void authorize(Activity activity, int activityCode, String redirectUri, Collection<Permission> permissions, String clientSecret, boolean showResultDialog, DialogListener dialogListener) { activityCodeAuth = activityCode; dialogListenerAuth = dialogListener; Intent auth = IntentCreator.createAuth(activity, clientId, redirectUri, permissions, clientSecret, showResultDialog); activity.startActivityForResult(auth, activityCodeAuth); } public void showHistory(Activity activity, int activityCode, String accessToken, DialogListener dialogListener) { activityCodeHistory = activityCode; dialogListenerHistory = dialogListener; Intent history = IntentCreator.createHistory(activity, clientId, accessToken); activity.startActivityForResult(history, activityCodeHistory); } public void showHistoryDetail(Activity activity, int activityCode, String accessToken, String operationId, DialogListener dialogListener) { activityCodeHistoryDetail = activityCode; dialogListenerHistoryDetail = dialogListener; Intent historyDetail = IntentCreator.createHistoryDetail(activity, clientId, accessToken, operationId); activity.startActivityForResult(historyDetail, activityCodeHistoryDetail); } public void showPaymentP2P(Activity activity, int activityCode, String accessToken, String accountTo, BigDecimal amount, String comment, String message, boolean showResultDialog, DialogListener dialogListener) { activityCodePaymentP2P = activityCode; dialogListenerPaymentP2P = dialogListener; Intent intent = IntentCreator.createPaymentP2P(activity, clientId, accessToken, accountTo, amount, comment, message, showResultDialog); activity.startActivityForResult(intent, activityCodePaymentP2P); } public void showPaymentShop(Activity activity, int activityCode, String accessToken, BigDecimal amount, String patternId, HashMap<String, String> params, boolean showResultDialog, DialogListener dialogListener) { activityCodePaymentShop = activityCode; dialogListenerPaymentShop = dialogListener; Intent intent = IntentCreator.createPaymentShop(activity, clientId, accessToken, amount, patternId, params, showResultDialog); activity.startActivityForResult(intent, activityCodePaymentShop); } public void callbackOnResult(int requestCode, int resultCode, Intent data) { - boolean isSuccess = data.getBooleanExtra(ActivityParams.AUTH_OUT_IS_SUCCESS, false); + boolean isSuccess = false; + if (data != null) + isSuccess = data.getBooleanExtra(ActivityParams.AUTH_OUT_IS_SUCCESS, false); if (requestCode == activityCodeAuth) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerAuth.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.AUTH_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.AUTH_OUT_ERROR); if (error == null) { dialogListenerAuth.onCancel(); } else { dialogListenerAuth.onFail(error); } } else { dialogListenerAuth.onException(e); } } } if (requestCode == activityCodeHistory) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerHistory.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.HISTORY_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.HISTORY_OUT_ERROR); if (error == null) { dialogListenerHistory.onCancel(); } else { dialogListenerHistory.onFail(error); } } else { dialogListenerHistory.onException(e); } } } if (requestCode == activityCodeHistoryDetail) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerHistoryDetail.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.HISTORY_DETAIL_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.HISTORY_DETAIL_OUT_ERROR); if (error == null) { dialogListenerHistoryDetail.onCancel(); } else { dialogListenerHistoryDetail.onFail(error); } } else { dialogListenerHistoryDetail.onException(e); } } } if (requestCode == activityCodePaymentP2P) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerPaymentP2P.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.PAYMENT_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.PAYMENT_OUT_ERROR); if (error == null) { dialogListenerPaymentP2P.onCancel(); } else { dialogListenerPaymentP2P.onFail(error); } } else { dialogListenerPaymentP2P.onException(e); } } } if (requestCode == activityCodePaymentShop) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerPaymentShop.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.PAYMENT_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.PAYMENT_OUT_ERROR); if (error == null) { dialogListenerPaymentShop.onCancel(); } else { dialogListenerPaymentShop.onFail(error); } } else { dialogListenerPaymentShop.onException(e); } } } } public static interface DialogListener { public void onSuccess(Bundle values); public void onFail(String cause); public void onException(Exception exception); public void onCancel(); } }
true
true
public void callbackOnResult(int requestCode, int resultCode, Intent data) { boolean isSuccess = data.getBooleanExtra(ActivityParams.AUTH_OUT_IS_SUCCESS, false); if (requestCode == activityCodeAuth) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerAuth.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.AUTH_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.AUTH_OUT_ERROR); if (error == null) { dialogListenerAuth.onCancel(); } else { dialogListenerAuth.onFail(error); } } else { dialogListenerAuth.onException(e); } } } if (requestCode == activityCodeHistory) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerHistory.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.HISTORY_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.HISTORY_OUT_ERROR); if (error == null) { dialogListenerHistory.onCancel(); } else { dialogListenerHistory.onFail(error); } } else { dialogListenerHistory.onException(e); } } } if (requestCode == activityCodeHistoryDetail) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerHistoryDetail.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.HISTORY_DETAIL_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.HISTORY_DETAIL_OUT_ERROR); if (error == null) { dialogListenerHistoryDetail.onCancel(); } else { dialogListenerHistoryDetail.onFail(error); } } else { dialogListenerHistoryDetail.onException(e); } } } if (requestCode == activityCodePaymentP2P) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerPaymentP2P.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.PAYMENT_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.PAYMENT_OUT_ERROR); if (error == null) { dialogListenerPaymentP2P.onCancel(); } else { dialogListenerPaymentP2P.onFail(error); } } else { dialogListenerPaymentP2P.onException(e); } } } if (requestCode == activityCodePaymentShop) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerPaymentShop.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.PAYMENT_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.PAYMENT_OUT_ERROR); if (error == null) { dialogListenerPaymentShop.onCancel(); } else { dialogListenerPaymentShop.onFail(error); } } else { dialogListenerPaymentShop.onException(e); } } } }
public void callbackOnResult(int requestCode, int resultCode, Intent data) { boolean isSuccess = false; if (data != null) isSuccess = data.getBooleanExtra(ActivityParams.AUTH_OUT_IS_SUCCESS, false); if (requestCode == activityCodeAuth) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerAuth.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.AUTH_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.AUTH_OUT_ERROR); if (error == null) { dialogListenerAuth.onCancel(); } else { dialogListenerAuth.onFail(error); } } else { dialogListenerAuth.onException(e); } } } if (requestCode == activityCodeHistory) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerHistory.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.HISTORY_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.HISTORY_OUT_ERROR); if (error == null) { dialogListenerHistory.onCancel(); } else { dialogListenerHistory.onFail(error); } } else { dialogListenerHistory.onException(e); } } } if (requestCode == activityCodeHistoryDetail) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerHistoryDetail.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.HISTORY_DETAIL_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.HISTORY_DETAIL_OUT_ERROR); if (error == null) { dialogListenerHistoryDetail.onCancel(); } else { dialogListenerHistoryDetail.onFail(error); } } else { dialogListenerHistoryDetail.onException(e); } } } if (requestCode == activityCodePaymentP2P) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerPaymentP2P.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.PAYMENT_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.PAYMENT_OUT_ERROR); if (error == null) { dialogListenerPaymentP2P.onCancel(); } else { dialogListenerPaymentP2P.onFail(error); } } else { dialogListenerPaymentP2P.onException(e); } } } if (requestCode == activityCodePaymentShop) { if (resultCode == Activity.RESULT_OK) { if (isSuccess) dialogListenerPaymentShop.onSuccess(data.getExtras()); } else { Exception e = (Exception) data.getSerializableExtra(ActivityParams.PAYMENT_OUT_EXCEPTION); if (e == null) { String error = data.getStringExtra(ActivityParams.PAYMENT_OUT_ERROR); if (error == null) { dialogListenerPaymentShop.onCancel(); } else { dialogListenerPaymentShop.onFail(error); } } else { dialogListenerPaymentShop.onException(e); } } } }
diff --git a/cinderella-web/src/main/java/io/cinderella/security/AuthenticationServiceImpl.java b/cinderella-web/src/main/java/io/cinderella/security/AuthenticationServiceImpl.java index bb61f6213..ed7c1c161 100644 --- a/cinderella-web/src/main/java/io/cinderella/security/AuthenticationServiceImpl.java +++ b/cinderella-web/src/main/java/io/cinderella/security/AuthenticationServiceImpl.java @@ -1,200 +1,206 @@ package io.cinderella.security; import com.cloud.bridge.service.UserContext; import com.cloud.bridge.util.EC2RestAuth; import io.cinderella.exception.PermissionDeniedException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLEncoder; import java.security.SignatureException; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.Enumeration; /** * @author shane * @since 9/26/12 */ @Component @PropertySource("file:${user.home}/.cinderella/ec2-service.properties") public class AuthenticationServiceImpl implements AuthenticationService { private static final Logger logger = LoggerFactory.getLogger(AuthenticationServiceImpl.class); @Autowired Environment env; /** * This function implements the EC2 REST authentication algorithm. It uses * the given "AWSAccessKeyId" parameter to look up the Cloud.com account * holder's secret key which is used as input to the signature calculation. * In addition, it tests the given "Expires" parameter to see if the * signature has expired and if so the request fails. */ @Override public boolean authenticateRequest(HttpServletRequest request, HttpServletResponse response) throws SignatureException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, ParseException { String cloudAccessKey = null; String signature = null; String sigMethod = null; // [A] Basic parameters required for an authenticated rest request // -> note that the Servlet engine will un-URL encode all parameters we // extract via "getParameterValues()" calls String[] awsAccess = request.getParameterValues("AWSAccessKeyId"); if (null != awsAccess && 0 < awsAccess.length) cloudAccessKey = awsAccess[0]; else { response.sendError(530, "Missing AWSAccessKeyId parameter"); return false; } String[] clientSig = request.getParameterValues("Signature"); if (null != clientSig && 0 < clientSig.length) signature = clientSig[0]; else { response.sendError(530, "Missing Signature parameter"); return false; } String[] method = request.getParameterValues("SignatureMethod"); if (null != method && 0 < method.length) { sigMethod = method[0]; if (!sigMethod.equals("HmacSHA256") && !sigMethod.equals("HmacSHA1")) { response.sendError(531, "Unsupported SignatureMethod value: " + sigMethod + " expecting: HmacSHA256 or HmacSHA1"); return false; } } else { response.sendError(530, "Missing SignatureMethod parameter"); return false; } /* * String[] version = request.getParameterValues( "Version" ); if ( null * != version && 0 < version.length ) { if (!version[0].equals( * wsdlVersion )) { response.sendError(531, "Unsupported Version value: " * + version[0] + " expecting: " + wsdlVersion ); return false; } } else { * response.sendError(530, "Missing Version parameter" ); return false; } */ String[] sigVersion = request.getParameterValues("SignatureVersion"); if (null != sigVersion && 0 < sigVersion.length) { if (!sigVersion[0].equals("2")) { response.sendError(531, "Unsupported SignatureVersion value: " + sigVersion[0] + " expecting: 2"); return false; } } else { response.sendError(530, "Missing SignatureVersion parameter"); return false; } // -> can have only one but not both { Expires | Timestamp } headers String[] expires = request.getParameterValues("Expires"); if (null != expires && 0 < expires.length) { // -> contains the date and time at which the signature included in the // request EXPIRES if (hasSignatureExpired(expires[0])) { response.sendError(531, "Expires parameter indicates signature has expired: " + expires[0]); return false; } } else { // -> contains the date and time at which the request is SIGNED String[] time = request.getParameterValues("Timestamp"); if (null == time || 0 == time.length) { response.sendError(530, "Missing Timestamp and Expires parameter, one is required"); return false; } } // [B] Use the cloudAccessKey to get the users secret key in the db // UserCredentialsDao credentialDao = new UserCredentialsDao(); /* * UserCredentials cloudKeys = credentialDao.getByAccessKey( * cloudAccessKey ); if ( null == cloudKeys ) { logger.debug( * cloudAccessKey + * " is not defined in the EC2 service - call SetUserKeys" ); * response.sendError(404, cloudAccessKey + * " is not defined in the EC2 service - call SetUserKeys" ); return * false; } else cloudSecretKey = cloudKeys.getSecretKey(); */ // cloudSecretKey = ec2properties.getProperty("key." + cloudAccessKey); String cloudSecretKey = env.getProperty("key." + cloudAccessKey); if (null == cloudSecretKey) { throw new PermissionDeniedException("No secret key configured for access key: "+ cloudAccessKey); } // [C] Verify the signature // -> getting the query-string in this way maintains its URL encoding EC2RestAuth restAuth = new EC2RestAuth(); restAuth.setHostHeader(request.getHeader("Host")); String requestUri = request.getRequestURI(); // If forwarded from another basepath: String forwardedPath = (String) request.getAttribute("javax.servlet.forward.request_uri"); if (forwardedPath != null) { requestUri = forwardedPath; } restAuth.setHTTPRequestURI(requestUri); String queryString = request.getQueryString(); // getQueryString returns null (does it ever NOT return null for these), // we need to construct queryString to avoid changing the auth code... if (queryString == null) { // construct our idea of a queryString with parameters! Enumeration<?> params = request.getParameterNames(); if (params != null) { while (params.hasMoreElements()) { String paramName = (String) params.nextElement(); // exclude the signature string obviously. ;) if (paramName.equalsIgnoreCase("Signature")) continue; if (queryString == null) - queryString = paramName + "=" + request.getParameter(paramName); + queryString = paramName + "=" + URLEncoder.encode(request.getParameter(paramName), "UTF-8"). + replace("+", "%20"). + replace("*", "%2A"). + replace("%7E", "~"); else queryString = queryString + "&" + paramName + "=" - + URLEncoder.encode(request.getParameter(paramName), "UTF-8"); + + URLEncoder.encode(request.getParameter(paramName), "UTF-8"). + replace("+", "%20"). + replace("*", "%2A"). + replace("%7E", "~"); } } } restAuth.setQueryString(queryString); if (restAuth.verifySignature(request.getMethod(), cloudSecretKey, signature, sigMethod)) { UserContext.current().initContext(cloudAccessKey, cloudSecretKey, cloudAccessKey, "REST request", null); return true; } else throw new PermissionDeniedException("Invalid signature"); } /** * We check this to reduce replay attacks. * * @param timeStamp * @return true - if the request is not longer valid, false otherwise * @throws ParseException */ private boolean hasSignatureExpired(String timeStamp) { Calendar cal = EC2RestAuth.parseDateString(timeStamp); if (null == cal) return false; Date expiredTime = cal.getTime(); Date today = new Date(); // -> gets set to time of creation if (0 >= expiredTime.compareTo(today)) { logger.debug("timestamp given: [" + timeStamp + "], now: [" + today.toString() + "]"); return true; } else return false; } }
false
true
public boolean authenticateRequest(HttpServletRequest request, HttpServletResponse response) throws SignatureException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, ParseException { String cloudAccessKey = null; String signature = null; String sigMethod = null; // [A] Basic parameters required for an authenticated rest request // -> note that the Servlet engine will un-URL encode all parameters we // extract via "getParameterValues()" calls String[] awsAccess = request.getParameterValues("AWSAccessKeyId"); if (null != awsAccess && 0 < awsAccess.length) cloudAccessKey = awsAccess[0]; else { response.sendError(530, "Missing AWSAccessKeyId parameter"); return false; } String[] clientSig = request.getParameterValues("Signature"); if (null != clientSig && 0 < clientSig.length) signature = clientSig[0]; else { response.sendError(530, "Missing Signature parameter"); return false; } String[] method = request.getParameterValues("SignatureMethod"); if (null != method && 0 < method.length) { sigMethod = method[0]; if (!sigMethod.equals("HmacSHA256") && !sigMethod.equals("HmacSHA1")) { response.sendError(531, "Unsupported SignatureMethod value: " + sigMethod + " expecting: HmacSHA256 or HmacSHA1"); return false; } } else { response.sendError(530, "Missing SignatureMethod parameter"); return false; } /* * String[] version = request.getParameterValues( "Version" ); if ( null * != version && 0 < version.length ) { if (!version[0].equals( * wsdlVersion )) { response.sendError(531, "Unsupported Version value: " * + version[0] + " expecting: " + wsdlVersion ); return false; } } else { * response.sendError(530, "Missing Version parameter" ); return false; } */ String[] sigVersion = request.getParameterValues("SignatureVersion"); if (null != sigVersion && 0 < sigVersion.length) { if (!sigVersion[0].equals("2")) { response.sendError(531, "Unsupported SignatureVersion value: " + sigVersion[0] + " expecting: 2"); return false; } } else { response.sendError(530, "Missing SignatureVersion parameter"); return false; } // -> can have only one but not both { Expires | Timestamp } headers String[] expires = request.getParameterValues("Expires"); if (null != expires && 0 < expires.length) { // -> contains the date and time at which the signature included in the // request EXPIRES if (hasSignatureExpired(expires[0])) { response.sendError(531, "Expires parameter indicates signature has expired: " + expires[0]); return false; } } else { // -> contains the date and time at which the request is SIGNED String[] time = request.getParameterValues("Timestamp"); if (null == time || 0 == time.length) { response.sendError(530, "Missing Timestamp and Expires parameter, one is required"); return false; } } // [B] Use the cloudAccessKey to get the users secret key in the db // UserCredentialsDao credentialDao = new UserCredentialsDao(); /* * UserCredentials cloudKeys = credentialDao.getByAccessKey( * cloudAccessKey ); if ( null == cloudKeys ) { logger.debug( * cloudAccessKey + * " is not defined in the EC2 service - call SetUserKeys" ); * response.sendError(404, cloudAccessKey + * " is not defined in the EC2 service - call SetUserKeys" ); return * false; } else cloudSecretKey = cloudKeys.getSecretKey(); */ // cloudSecretKey = ec2properties.getProperty("key." + cloudAccessKey); String cloudSecretKey = env.getProperty("key." + cloudAccessKey); if (null == cloudSecretKey) { throw new PermissionDeniedException("No secret key configured for access key: "+ cloudAccessKey); } // [C] Verify the signature // -> getting the query-string in this way maintains its URL encoding EC2RestAuth restAuth = new EC2RestAuth(); restAuth.setHostHeader(request.getHeader("Host")); String requestUri = request.getRequestURI(); // If forwarded from another basepath: String forwardedPath = (String) request.getAttribute("javax.servlet.forward.request_uri"); if (forwardedPath != null) { requestUri = forwardedPath; } restAuth.setHTTPRequestURI(requestUri); String queryString = request.getQueryString(); // getQueryString returns null (does it ever NOT return null for these), // we need to construct queryString to avoid changing the auth code... if (queryString == null) { // construct our idea of a queryString with parameters! Enumeration<?> params = request.getParameterNames(); if (params != null) { while (params.hasMoreElements()) { String paramName = (String) params.nextElement(); // exclude the signature string obviously. ;) if (paramName.equalsIgnoreCase("Signature")) continue; if (queryString == null) queryString = paramName + "=" + request.getParameter(paramName); else queryString = queryString + "&" + paramName + "=" + URLEncoder.encode(request.getParameter(paramName), "UTF-8"); } } } restAuth.setQueryString(queryString); if (restAuth.verifySignature(request.getMethod(), cloudSecretKey, signature, sigMethod)) { UserContext.current().initContext(cloudAccessKey, cloudSecretKey, cloudAccessKey, "REST request", null); return true; } else throw new PermissionDeniedException("Invalid signature"); }
public boolean authenticateRequest(HttpServletRequest request, HttpServletResponse response) throws SignatureException, IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, ParseException { String cloudAccessKey = null; String signature = null; String sigMethod = null; // [A] Basic parameters required for an authenticated rest request // -> note that the Servlet engine will un-URL encode all parameters we // extract via "getParameterValues()" calls String[] awsAccess = request.getParameterValues("AWSAccessKeyId"); if (null != awsAccess && 0 < awsAccess.length) cloudAccessKey = awsAccess[0]; else { response.sendError(530, "Missing AWSAccessKeyId parameter"); return false; } String[] clientSig = request.getParameterValues("Signature"); if (null != clientSig && 0 < clientSig.length) signature = clientSig[0]; else { response.sendError(530, "Missing Signature parameter"); return false; } String[] method = request.getParameterValues("SignatureMethod"); if (null != method && 0 < method.length) { sigMethod = method[0]; if (!sigMethod.equals("HmacSHA256") && !sigMethod.equals("HmacSHA1")) { response.sendError(531, "Unsupported SignatureMethod value: " + sigMethod + " expecting: HmacSHA256 or HmacSHA1"); return false; } } else { response.sendError(530, "Missing SignatureMethod parameter"); return false; } /* * String[] version = request.getParameterValues( "Version" ); if ( null * != version && 0 < version.length ) { if (!version[0].equals( * wsdlVersion )) { response.sendError(531, "Unsupported Version value: " * + version[0] + " expecting: " + wsdlVersion ); return false; } } else { * response.sendError(530, "Missing Version parameter" ); return false; } */ String[] sigVersion = request.getParameterValues("SignatureVersion"); if (null != sigVersion && 0 < sigVersion.length) { if (!sigVersion[0].equals("2")) { response.sendError(531, "Unsupported SignatureVersion value: " + sigVersion[0] + " expecting: 2"); return false; } } else { response.sendError(530, "Missing SignatureVersion parameter"); return false; } // -> can have only one but not both { Expires | Timestamp } headers String[] expires = request.getParameterValues("Expires"); if (null != expires && 0 < expires.length) { // -> contains the date and time at which the signature included in the // request EXPIRES if (hasSignatureExpired(expires[0])) { response.sendError(531, "Expires parameter indicates signature has expired: " + expires[0]); return false; } } else { // -> contains the date and time at which the request is SIGNED String[] time = request.getParameterValues("Timestamp"); if (null == time || 0 == time.length) { response.sendError(530, "Missing Timestamp and Expires parameter, one is required"); return false; } } // [B] Use the cloudAccessKey to get the users secret key in the db // UserCredentialsDao credentialDao = new UserCredentialsDao(); /* * UserCredentials cloudKeys = credentialDao.getByAccessKey( * cloudAccessKey ); if ( null == cloudKeys ) { logger.debug( * cloudAccessKey + * " is not defined in the EC2 service - call SetUserKeys" ); * response.sendError(404, cloudAccessKey + * " is not defined in the EC2 service - call SetUserKeys" ); return * false; } else cloudSecretKey = cloudKeys.getSecretKey(); */ // cloudSecretKey = ec2properties.getProperty("key." + cloudAccessKey); String cloudSecretKey = env.getProperty("key." + cloudAccessKey); if (null == cloudSecretKey) { throw new PermissionDeniedException("No secret key configured for access key: "+ cloudAccessKey); } // [C] Verify the signature // -> getting the query-string in this way maintains its URL encoding EC2RestAuth restAuth = new EC2RestAuth(); restAuth.setHostHeader(request.getHeader("Host")); String requestUri = request.getRequestURI(); // If forwarded from another basepath: String forwardedPath = (String) request.getAttribute("javax.servlet.forward.request_uri"); if (forwardedPath != null) { requestUri = forwardedPath; } restAuth.setHTTPRequestURI(requestUri); String queryString = request.getQueryString(); // getQueryString returns null (does it ever NOT return null for these), // we need to construct queryString to avoid changing the auth code... if (queryString == null) { // construct our idea of a queryString with parameters! Enumeration<?> params = request.getParameterNames(); if (params != null) { while (params.hasMoreElements()) { String paramName = (String) params.nextElement(); // exclude the signature string obviously. ;) if (paramName.equalsIgnoreCase("Signature")) continue; if (queryString == null) queryString = paramName + "=" + URLEncoder.encode(request.getParameter(paramName), "UTF-8"). replace("+", "%20"). replace("*", "%2A"). replace("%7E", "~"); else queryString = queryString + "&" + paramName + "=" + URLEncoder.encode(request.getParameter(paramName), "UTF-8"). replace("+", "%20"). replace("*", "%2A"). replace("%7E", "~"); } } } restAuth.setQueryString(queryString); if (restAuth.verifySignature(request.getMethod(), cloudSecretKey, signature, sigMethod)) { UserContext.current().initContext(cloudAccessKey, cloudSecretKey, cloudAccessKey, "REST request", null); return true; } else throw new PermissionDeniedException("Invalid signature"); }
diff --git a/pivot4j-analytics/src/main/java/com/eyeq/pivot4j/analytics/ui/PrimeFacesPivotRenderer.java b/pivot4j-analytics/src/main/java/com/eyeq/pivot4j/analytics/ui/PrimeFacesPivotRenderer.java index 0b89d8e6..9c2f7b7a 100644 --- a/pivot4j-analytics/src/main/java/com/eyeq/pivot4j/analytics/ui/PrimeFacesPivotRenderer.java +++ b/pivot4j-analytics/src/main/java/com/eyeq/pivot4j/analytics/ui/PrimeFacesPivotRenderer.java @@ -1,554 +1,554 @@ package com.eyeq.pivot4j.analytics.ui; import java.sql.ResultSet; import java.text.MessageFormat; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import javax.el.ExpressionFactory; import javax.el.MethodExpression; import javax.faces.application.Application; import javax.faces.application.FacesMessage; import javax.faces.component.UIParameter; import javax.faces.component.html.HtmlOutputLink; import javax.faces.component.html.HtmlOutputText; import javax.faces.component.html.HtmlPanelGroup; import javax.faces.context.FacesContext; import org.apache.commons.lang.StringUtils; import org.olap4j.Axis; import org.olap4j.Cell; import org.olap4j.metadata.Measure; import org.primefaces.component.column.Column; import org.primefaces.component.commandbutton.CommandButton; import org.primefaces.component.panelgrid.PanelGrid; import org.primefaces.component.row.Row; import org.primefaces.context.RequestContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.eyeq.pivot4j.PivotModel; import com.eyeq.pivot4j.el.EvaluationFailedException; import com.eyeq.pivot4j.ui.AbstractPivotUIRenderer; import com.eyeq.pivot4j.ui.CellType; import com.eyeq.pivot4j.ui.PivotUIRenderer; import com.eyeq.pivot4j.ui.RenderContext; import com.eyeq.pivot4j.ui.aggregator.Aggregator; import com.eyeq.pivot4j.ui.command.BasicDrillThroughCommand; import com.eyeq.pivot4j.ui.command.CellCommand; import com.eyeq.pivot4j.ui.command.CellParameters; import com.eyeq.pivot4j.ui.property.PropertySupport; public class PrimeFacesPivotRenderer extends AbstractPivotUIRenderer { private Logger logger = LoggerFactory.getLogger(getClass()); private Map<String, String> iconMap; private PanelGrid component; private FacesContext facesContext; private ExpressionFactory expressionFactory; private HtmlPanelGroup header; private Row row; private Column column; private int commandIndex = 0; private ResourceBundle bundle; /** * @param facesContext */ public PrimeFacesPivotRenderer(FacesContext facesContext) { this.facesContext = facesContext; if (facesContext != null) { Application application = facesContext.getApplication(); this.expressionFactory = application.getExpressionFactory(); this.bundle = facesContext.getApplication().getResourceBundle( facesContext, "msg"); } // Map command mode names to jQuery's predefined icon names. It can be // also done by CSS. this.iconMap = new HashMap<String, String>(); iconMap.put("expandPosition-position", "ui-icon-plus"); iconMap.put("collapsePosition-position", "ui-icon-minus"); iconMap.put("expandMember-member", "ui-icon-plusthick"); iconMap.put("collapseMember-member", "ui-icon-minusthick"); iconMap.put("drillDown-replace", "ui-icon-arrowthick-1-e"); iconMap.put("drillUp-replace", "ui-icon-arrowthick-1-n"); iconMap.put("sort-basic-natural", "ui-icon-triangle-2-n-s"); iconMap.put("sort-basic-other-up", "ui-icon-triangle-1-n"); iconMap.put("sort-basic-other-down", "ui-icon-triangle-1-s"); iconMap.put("sort-basic-current-up", "ui-icon-circle-triangle-n"); iconMap.put("sort-basic-current-down", "ui-icon-circle-triangle-s"); iconMap.put("drillThrough", "ui-icon-search"); this.commandIndex = 0; } /** * @return the parent JSF component */ public PanelGrid getComponent() { return component; } /** * @param component */ public void setComponent(PanelGrid component) { this.component = component; } /** * @return the logger */ protected Logger getLogger() { return logger; } /** * @return bundle */ protected ResourceBundle getBundle() { return bundle; } /** * @see com.eyeq.pivot4j.ui.AbstractPivotUIRenderer#registerCommands() */ @Override protected void registerCommands() { super.registerCommands(); addCommand(new DrillThroughCommandImpl(this)); } /** * @see com.eyeq.pivot4j.ui.AbstractPivotRenderer#getCellLabel(com.eyeq.pivot4j.ui.RenderContext) */ @Override protected String getCellLabel(RenderContext context) { String label = super.getCellLabel(context); if (context.getCellType() == CellType.Aggregation) { Aggregator aggregator = context.getAggregator(); if (aggregator != null && (context.getMember() == null || !(context.getMember() instanceof Measure))) { String key = "label.aggregation.type." + aggregator.getName(); String value = bundle.getString(key); if (value != null) { label = value; } } } return label; } /** * @see com.eyeq.pivot4j.ui.PivotLayoutCallback#startTable(com.eyeq.pivot4j.ui.RenderContext) */ @Override public void startTable(RenderContext context) { component.getChildren().clear(); } /** * @see com.eyeq.pivot4j.ui.PivotLayoutCallback#startHeader(com.eyeq.pivot4j.ui.RenderContext) */ @Override public void startHeader(RenderContext context) { this.header = new HtmlPanelGroup(); header.setId("pivot-header"); } /** * @see com.eyeq.pivot4j.ui.PivotLayoutCallback#endHeader(com.eyeq.pivot4j.ui.RenderContext) */ @Override public void endHeader(RenderContext context) { component.getFacets().put("header", header); this.header = null; } /** * @see com.eyeq.pivot4j.ui.PivotLayoutCallback#startBody(com.eyeq.pivot4j.ui.RenderContext) */ @Override public void startBody(RenderContext context) { } /** * @see com.eyeq.pivot4j.ui.PivotLayoutCallback#startRow(com.eyeq.pivot4j.ui.RenderContext) */ @Override public void startRow(RenderContext context) { this.row = new Row(); } /** * @see com.eyeq.pivot4j.ui.AbstractPivotUIRenderer#startCell(com.eyeq.pivot4j.ui.RenderContext, * java.util.List) */ @Override public void startCell(RenderContext context, List<CellCommand<?>> commands) { this.column = new Column(); String id = "col-" + column.hashCode(); column.setId(id); column.setColspan(context.getColSpan()); column.setRowspan(context.getRowSpan()); String styleClass; switch (context.getCellType()) { case Header: case Title: case None: if (context.getAxis() == Axis.COLUMNS) { styleClass = "col-hdr-cell"; } else { if (context.getCellType() == CellType.Header) { styleClass = "row-hdr-cell ui-widget-header"; } else { styleClass = "ui-widget-header"; } } if (!getShowParentMembers() && context.getMember() != null) { int padding = context.getMember().getDepth() * 10; column.setStyle("padding-left: " + padding + "px"); } break; case Aggregation: if (context.getAxis() == Axis.ROWS) { styleClass = "ui-widget-header "; } else { styleClass = ""; } styleClass += "agg-title"; if (!getShowParentMembers() && context.getMember() != null) { int padding = context.getMember().getDepth() * 10; column.setStyle("padding-left: " + padding + "px"); } break; case Value: if (context.getAggregator() == null) { // PrimeFaces' Row class doesn't have the styleClass property. if (context.getRowIndex() % 2 == 0) { styleClass = "value-cell cell-even"; } else { styleClass = "value-cell cell-odd"; } } else { styleClass = "ui-widget-header agg-cell"; if (context.getAxis() == Axis.COLUMNS) { styleClass += " col-agg-cell"; } else if (context.getAxis() == Axis.ROWS) { styleClass += " row-agg-cell"; } } break; default: styleClass = null; } if (expressionFactory != null) { for (CellCommand<?> command : commands) { CellParameters parameters = command.createParameters(context); CommandButton button = new CommandButton(); // JSF requires an unique id for command components. button.setId("btn-" + commandIndex++); button.setTitle(command.getDescription()); String icon = null; String mode = command.getMode(context); if (mode == null) { icon = iconMap.get(command.getName()); } else { icon = iconMap.get(command.getName() + "-" + mode); } button.setIcon(icon); MethodExpression expression = expressionFactory .createMethodExpression(facesContext.getELContext(), "#{pivotGridHandler.executeCommand}", Void.class, new Class<?>[0]); button.setActionExpression(expression); button.setUpdate(":grid-form,:editor-form:mdx-editor,:editor-form:editor-toolbar,:source-tree-form,:target-tree-form"); button.setOncomplete("onViewChanged()"); UIParameter commandParam = new UIParameter(); commandParam.setName("command"); commandParam.setValue(command.getName()); button.getChildren().add(commandParam); UIParameter axisParam = new UIParameter(); axisParam.setName("axis"); axisParam.setValue(parameters.getAxisOrdinal()); button.getChildren().add(axisParam); UIParameter positionParam = new UIParameter(); positionParam.setName("position"); positionParam.setValue(parameters.getPositionOrdinal()); button.getChildren().add(positionParam); UIParameter memberParam = new UIParameter(); memberParam.setName("member"); memberParam.setValue(parameters.getMemberOrdinal()); button.getChildren().add(memberParam); UIParameter hierarchyParam = new UIParameter(); hierarchyParam.setName("hierarchy"); hierarchyParam.setValue(parameters.getHierarchyOrdinal()); button.getChildren().add(hierarchyParam); UIParameter cellParam = new UIParameter(); - hierarchyParam.setName("cell"); - hierarchyParam.setValue(parameters.getCellOrdinal()); + cellParam.setName("cell"); + cellParam.setValue(parameters.getCellOrdinal()); button.getChildren().add(cellParam); column.getChildren().add(button); } } PropertySupport properties = getProperties(context); if (properties != null) { StringBuilder builder = new StringBuilder(); addPropertyStyle("fgColor", "color", properties, builder, context); addPropertyStyle("bgColor", "background-color", properties, builder, context); addPropertyStyle("fontFamily", "font-family", properties, builder, context); addPropertyStyle("fontSize", "font-size", properties, builder, context); String fontStyle = getPropertyValue("fontStyle", properties, context); if (fontStyle != null) { if (fontStyle.contains("bold")) { builder.append("font-weight: bold;"); } if (fontStyle.contains("italic")) { builder.append("font-style: oblique;"); } } String style = builder.toString(); if (StringUtils.isNotEmpty(style)) { column.setStyle(style); } String styleClassProperty = getPropertyValue("styleClass", properties, context); if (styleClassProperty != null) { if (styleClass == null) { styleClass = styleClassProperty; } else { styleClass += " " + styleClassProperty; } } } column.setStyleClass(styleClass); } /** * @param key * @param style * @param properties * @param builder * @param context */ private void addPropertyStyle(String key, String style, PropertySupport properties, StringBuilder builder, RenderContext context) { String value = getPropertyValue(key, properties, context); if (value != null) { builder.append(style); builder.append(": "); builder.append(value); builder.append(";"); if (style.equals("background-color")) { builder.append("background-image: none;"); } } } /** * @param key * @param properties * @param context * @return */ protected String getPropertyValue(String key, PropertySupport properties, RenderContext context) { String value = null; try { value = properties.getString(key, null, context); } catch (EvaluationFailedException e) { // In order not to bombard users with similar error messages. String attributeName = "property.hasError." + key; if (context.getAttribute(attributeName) == null) { FacesContext facesContext = FacesContext.getCurrentInstance(); ResourceBundle bundle = getBundle(); MessageFormat mf = new MessageFormat( bundle.getString("error.property.expression.title")); String title = mf.format(new String[] { bundle .getString("properties." + key) }); facesContext.addMessage(null, new FacesMessage( FacesMessage.SEVERITY_ERROR, title, e.getMessage())); if (logger.isWarnEnabled()) { logger.warn(title, e); } context.setAttribute(attributeName, true); } } return value; } /** * @see com.eyeq.pivot4j.ui.AbstractPivotRenderer#cellContent(com.eyeq.pivot4j.ui.RenderContext, * java.lang.String) */ @Override public void cellContent(RenderContext context, String label) { PropertySupport properties = getProperties(context); HtmlOutputText text = new HtmlOutputText(); String id = "txt-" + text.hashCode(); text.setId(id); text.setValue(label); String link = null; if (properties != null) { link = getPropertyValue("link", properties, context); } if (link == null) { column.getChildren().add(text); } else { HtmlOutputLink anchor = new HtmlOutputLink(); anchor.setValue(link); anchor.getChildren().add(text); column.getChildren().add(anchor); } } /** * @see com.eyeq.pivot4j.ui.PivotLayoutCallback#endCell(com.eyeq.pivot4j.ui.RenderContext) */ @Override public void endCell(RenderContext context) { row.getChildren().add(column); this.column = null; } /** * @see com.eyeq.pivot4j.ui.PivotLayoutCallback#endRow(com.eyeq.pivot4j.ui.RenderContext) */ @Override public void endRow(RenderContext context) { if (header == null) { component.getChildren().add(row); } else { header.getChildren().add(row); } this.row = null; } /** * @see com.eyeq.pivot4j.ui.PivotLayoutCallback#endBody(com.eyeq.pivot4j.ui.RenderContext) */ @Override public void endBody(RenderContext context) { } /** * @see com.eyeq.pivot4j.ui.PivotLayoutCallback#endTable(com.eyeq.pivot4j.ui.RenderContext) */ @Override public void endTable(RenderContext context) { this.commandIndex = 0; } /** * Workaround to implement lazy rendering due to limitation in Olap4J's API * : * * @see http://sourceforge.net/p/olap4j/bugs/15/ */ class DrillThroughCommandImpl extends BasicDrillThroughCommand { /** * @param renderer */ public DrillThroughCommandImpl(PivotUIRenderer renderer) { super(renderer); } /** * @see com.eyeq.pivot4j.ui.command.BasicDrillThroughCommand#execute(com.eyeq.pivot4j.PivotModel, * com.eyeq.pivot4j.ui.command.CellParameters) */ @Override public ResultSet execute(PivotModel model, CellParameters parameters) { Cell cell = model.getCellSet().getCell(parameters.getCellOrdinal()); DrillThroughDataModel data = facesContext.getApplication() .evaluateExpressionGet(facesContext, "#{drillThroughData}", DrillThroughDataModel.class); data.initialize(cell); data.setPageSize(15); RequestContext context = RequestContext.getCurrentInstance(); context.execute("drillThrough();"); return null; } } }
true
true
public void startCell(RenderContext context, List<CellCommand<?>> commands) { this.column = new Column(); String id = "col-" + column.hashCode(); column.setId(id); column.setColspan(context.getColSpan()); column.setRowspan(context.getRowSpan()); String styleClass; switch (context.getCellType()) { case Header: case Title: case None: if (context.getAxis() == Axis.COLUMNS) { styleClass = "col-hdr-cell"; } else { if (context.getCellType() == CellType.Header) { styleClass = "row-hdr-cell ui-widget-header"; } else { styleClass = "ui-widget-header"; } } if (!getShowParentMembers() && context.getMember() != null) { int padding = context.getMember().getDepth() * 10; column.setStyle("padding-left: " + padding + "px"); } break; case Aggregation: if (context.getAxis() == Axis.ROWS) { styleClass = "ui-widget-header "; } else { styleClass = ""; } styleClass += "agg-title"; if (!getShowParentMembers() && context.getMember() != null) { int padding = context.getMember().getDepth() * 10; column.setStyle("padding-left: " + padding + "px"); } break; case Value: if (context.getAggregator() == null) { // PrimeFaces' Row class doesn't have the styleClass property. if (context.getRowIndex() % 2 == 0) { styleClass = "value-cell cell-even"; } else { styleClass = "value-cell cell-odd"; } } else { styleClass = "ui-widget-header agg-cell"; if (context.getAxis() == Axis.COLUMNS) { styleClass += " col-agg-cell"; } else if (context.getAxis() == Axis.ROWS) { styleClass += " row-agg-cell"; } } break; default: styleClass = null; } if (expressionFactory != null) { for (CellCommand<?> command : commands) { CellParameters parameters = command.createParameters(context); CommandButton button = new CommandButton(); // JSF requires an unique id for command components. button.setId("btn-" + commandIndex++); button.setTitle(command.getDescription()); String icon = null; String mode = command.getMode(context); if (mode == null) { icon = iconMap.get(command.getName()); } else { icon = iconMap.get(command.getName() + "-" + mode); } button.setIcon(icon); MethodExpression expression = expressionFactory .createMethodExpression(facesContext.getELContext(), "#{pivotGridHandler.executeCommand}", Void.class, new Class<?>[0]); button.setActionExpression(expression); button.setUpdate(":grid-form,:editor-form:mdx-editor,:editor-form:editor-toolbar,:source-tree-form,:target-tree-form"); button.setOncomplete("onViewChanged()"); UIParameter commandParam = new UIParameter(); commandParam.setName("command"); commandParam.setValue(command.getName()); button.getChildren().add(commandParam); UIParameter axisParam = new UIParameter(); axisParam.setName("axis"); axisParam.setValue(parameters.getAxisOrdinal()); button.getChildren().add(axisParam); UIParameter positionParam = new UIParameter(); positionParam.setName("position"); positionParam.setValue(parameters.getPositionOrdinal()); button.getChildren().add(positionParam); UIParameter memberParam = new UIParameter(); memberParam.setName("member"); memberParam.setValue(parameters.getMemberOrdinal()); button.getChildren().add(memberParam); UIParameter hierarchyParam = new UIParameter(); hierarchyParam.setName("hierarchy"); hierarchyParam.setValue(parameters.getHierarchyOrdinal()); button.getChildren().add(hierarchyParam); UIParameter cellParam = new UIParameter(); hierarchyParam.setName("cell"); hierarchyParam.setValue(parameters.getCellOrdinal()); button.getChildren().add(cellParam); column.getChildren().add(button); } } PropertySupport properties = getProperties(context); if (properties != null) { StringBuilder builder = new StringBuilder(); addPropertyStyle("fgColor", "color", properties, builder, context); addPropertyStyle("bgColor", "background-color", properties, builder, context); addPropertyStyle("fontFamily", "font-family", properties, builder, context); addPropertyStyle("fontSize", "font-size", properties, builder, context); String fontStyle = getPropertyValue("fontStyle", properties, context); if (fontStyle != null) { if (fontStyle.contains("bold")) { builder.append("font-weight: bold;"); } if (fontStyle.contains("italic")) { builder.append("font-style: oblique;"); } } String style = builder.toString(); if (StringUtils.isNotEmpty(style)) { column.setStyle(style); } String styleClassProperty = getPropertyValue("styleClass", properties, context); if (styleClassProperty != null) { if (styleClass == null) { styleClass = styleClassProperty; } else { styleClass += " " + styleClassProperty; } } } column.setStyleClass(styleClass); }
public void startCell(RenderContext context, List<CellCommand<?>> commands) { this.column = new Column(); String id = "col-" + column.hashCode(); column.setId(id); column.setColspan(context.getColSpan()); column.setRowspan(context.getRowSpan()); String styleClass; switch (context.getCellType()) { case Header: case Title: case None: if (context.getAxis() == Axis.COLUMNS) { styleClass = "col-hdr-cell"; } else { if (context.getCellType() == CellType.Header) { styleClass = "row-hdr-cell ui-widget-header"; } else { styleClass = "ui-widget-header"; } } if (!getShowParentMembers() && context.getMember() != null) { int padding = context.getMember().getDepth() * 10; column.setStyle("padding-left: " + padding + "px"); } break; case Aggregation: if (context.getAxis() == Axis.ROWS) { styleClass = "ui-widget-header "; } else { styleClass = ""; } styleClass += "agg-title"; if (!getShowParentMembers() && context.getMember() != null) { int padding = context.getMember().getDepth() * 10; column.setStyle("padding-left: " + padding + "px"); } break; case Value: if (context.getAggregator() == null) { // PrimeFaces' Row class doesn't have the styleClass property. if (context.getRowIndex() % 2 == 0) { styleClass = "value-cell cell-even"; } else { styleClass = "value-cell cell-odd"; } } else { styleClass = "ui-widget-header agg-cell"; if (context.getAxis() == Axis.COLUMNS) { styleClass += " col-agg-cell"; } else if (context.getAxis() == Axis.ROWS) { styleClass += " row-agg-cell"; } } break; default: styleClass = null; } if (expressionFactory != null) { for (CellCommand<?> command : commands) { CellParameters parameters = command.createParameters(context); CommandButton button = new CommandButton(); // JSF requires an unique id for command components. button.setId("btn-" + commandIndex++); button.setTitle(command.getDescription()); String icon = null; String mode = command.getMode(context); if (mode == null) { icon = iconMap.get(command.getName()); } else { icon = iconMap.get(command.getName() + "-" + mode); } button.setIcon(icon); MethodExpression expression = expressionFactory .createMethodExpression(facesContext.getELContext(), "#{pivotGridHandler.executeCommand}", Void.class, new Class<?>[0]); button.setActionExpression(expression); button.setUpdate(":grid-form,:editor-form:mdx-editor,:editor-form:editor-toolbar,:source-tree-form,:target-tree-form"); button.setOncomplete("onViewChanged()"); UIParameter commandParam = new UIParameter(); commandParam.setName("command"); commandParam.setValue(command.getName()); button.getChildren().add(commandParam); UIParameter axisParam = new UIParameter(); axisParam.setName("axis"); axisParam.setValue(parameters.getAxisOrdinal()); button.getChildren().add(axisParam); UIParameter positionParam = new UIParameter(); positionParam.setName("position"); positionParam.setValue(parameters.getPositionOrdinal()); button.getChildren().add(positionParam); UIParameter memberParam = new UIParameter(); memberParam.setName("member"); memberParam.setValue(parameters.getMemberOrdinal()); button.getChildren().add(memberParam); UIParameter hierarchyParam = new UIParameter(); hierarchyParam.setName("hierarchy"); hierarchyParam.setValue(parameters.getHierarchyOrdinal()); button.getChildren().add(hierarchyParam); UIParameter cellParam = new UIParameter(); cellParam.setName("cell"); cellParam.setValue(parameters.getCellOrdinal()); button.getChildren().add(cellParam); column.getChildren().add(button); } } PropertySupport properties = getProperties(context); if (properties != null) { StringBuilder builder = new StringBuilder(); addPropertyStyle("fgColor", "color", properties, builder, context); addPropertyStyle("bgColor", "background-color", properties, builder, context); addPropertyStyle("fontFamily", "font-family", properties, builder, context); addPropertyStyle("fontSize", "font-size", properties, builder, context); String fontStyle = getPropertyValue("fontStyle", properties, context); if (fontStyle != null) { if (fontStyle.contains("bold")) { builder.append("font-weight: bold;"); } if (fontStyle.contains("italic")) { builder.append("font-style: oblique;"); } } String style = builder.toString(); if (StringUtils.isNotEmpty(style)) { column.setStyle(style); } String styleClassProperty = getPropertyValue("styleClass", properties, context); if (styleClassProperty != null) { if (styleClass == null) { styleClass = styleClassProperty; } else { styleClass += " " + styleClassProperty; } } } column.setStyleClass(styleClass); }
diff --git a/src/com/db/training/blb/cron/CronServlet.java b/src/com/db/training/blb/cron/CronServlet.java index 23f4685..a3ea7ce 100644 --- a/src/com/db/training/blb/cron/CronServlet.java +++ b/src/com/db/training/blb/cron/CronServlet.java @@ -1,95 +1,95 @@ package com.db.training.blb.cron; import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.db.training.blb.dao.ConnectionEngine; import com.db.training.blb.dao.QueryEngine; /** * Servlet implementation class CronServlet */ @WebServlet("/CronServlet") public class CronServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Timer timer=new Timer(); /** * @see HttpServlet#HttpServlet() */ public CronServlet() { super(); // TODO Auto-generated constructor stub } /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { System.out.println(new Date()+" INFO: Cron Job Started"); timer.schedule(new TimerTask(){ @Override public void run() { try { QueryEngine queryEngine=new QueryEngine(new ConnectionEngine()); ResultSet rs=queryEngine.query("select id from blb.transactions where transaction_status=0 and timestampdiff(MINUTE,timestamp(transaction_date),timestamp(now()))>1"); while(rs.next()){ - queryEngine.getConnectionEngine().update("update blb.transactions set transaction_status=1 where id=?", rs.getString(1)); + queryEngine.getConnectionEngine().update("insert into blb.transactions(buyer_id,seller_id,trader_id,transaction_date,bond_cusip,quantity,transaction_status) values (select t.buyer_id,t.seller_id,t.trader_id,now(),t.bond_cusip,t.quantity,1 from blb.transactions t where id=?)", rs.getString(1)); } rs.close(); rs=queryEngine.query("select id from blb.transactions where transaction_status=1 and timestampdiff(MINUTE,timestamp(transaction_date),timestamp(now()))>5"); while(rs.next()){ - queryEngine.getConnectionEngine().update("update blb.transactions set transaction_status=2 where id=?", rs.getString(1)); + queryEngine.getConnectionEngine().update("insert into blb.transactions(buyer_id,seller_id,trader_id,transaction_date,bond_cusip,quantity,transaction_status) values (select t.buyer_id,t.seller_id,t.trader_id,now(),t.bond_cusip,t.quantity,2 from blb.transactions t where id=?)", rs.getString(1)); } rs.close(); } catch (Exception e) { e.printStackTrace(); }finally{ System.out.println(new Date()+" INFO: Cron Job Executed"); } } }, 0, 30000); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Content-Type", "text/plain"); response.getOutputStream().write("Cron job started".getBytes()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Content-Type", "text/plain"); response.getOutputStream().write("Cron job started".getBytes()); } @Override protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("Content-Type", "text/plain"); resp.getOutputStream().write("Cron job started".getBytes()); } }
false
true
public void init(ServletConfig config) throws ServletException { System.out.println(new Date()+" INFO: Cron Job Started"); timer.schedule(new TimerTask(){ @Override public void run() { try { QueryEngine queryEngine=new QueryEngine(new ConnectionEngine()); ResultSet rs=queryEngine.query("select id from blb.transactions where transaction_status=0 and timestampdiff(MINUTE,timestamp(transaction_date),timestamp(now()))>1"); while(rs.next()){ queryEngine.getConnectionEngine().update("update blb.transactions set transaction_status=1 where id=?", rs.getString(1)); } rs.close(); rs=queryEngine.query("select id from blb.transactions where transaction_status=1 and timestampdiff(MINUTE,timestamp(transaction_date),timestamp(now()))>5"); while(rs.next()){ queryEngine.getConnectionEngine().update("update blb.transactions set transaction_status=2 where id=?", rs.getString(1)); } rs.close(); } catch (Exception e) { e.printStackTrace(); }finally{ System.out.println(new Date()+" INFO: Cron Job Executed"); } } }, 0, 30000); }
public void init(ServletConfig config) throws ServletException { System.out.println(new Date()+" INFO: Cron Job Started"); timer.schedule(new TimerTask(){ @Override public void run() { try { QueryEngine queryEngine=new QueryEngine(new ConnectionEngine()); ResultSet rs=queryEngine.query("select id from blb.transactions where transaction_status=0 and timestampdiff(MINUTE,timestamp(transaction_date),timestamp(now()))>1"); while(rs.next()){ queryEngine.getConnectionEngine().update("insert into blb.transactions(buyer_id,seller_id,trader_id,transaction_date,bond_cusip,quantity,transaction_status) values (select t.buyer_id,t.seller_id,t.trader_id,now(),t.bond_cusip,t.quantity,1 from blb.transactions t where id=?)", rs.getString(1)); } rs.close(); rs=queryEngine.query("select id from blb.transactions where transaction_status=1 and timestampdiff(MINUTE,timestamp(transaction_date),timestamp(now()))>5"); while(rs.next()){ queryEngine.getConnectionEngine().update("insert into blb.transactions(buyer_id,seller_id,trader_id,transaction_date,bond_cusip,quantity,transaction_status) values (select t.buyer_id,t.seller_id,t.trader_id,now(),t.bond_cusip,t.quantity,2 from blb.transactions t where id=?)", rs.getString(1)); } rs.close(); } catch (Exception e) { e.printStackTrace(); }finally{ System.out.println(new Date()+" INFO: Cron Job Executed"); } } }, 0, 30000); }
diff --git a/restnet-c/src/main/java/net/idea/restnet/c/reporters/CatalogHTMLReporter.java b/restnet-c/src/main/java/net/idea/restnet/c/reporters/CatalogHTMLReporter.java index f3edcbc..1c9e1cd 100644 --- a/restnet-c/src/main/java/net/idea/restnet/c/reporters/CatalogHTMLReporter.java +++ b/restnet-c/src/main/java/net/idea/restnet/c/reporters/CatalogHTMLReporter.java @@ -1,67 +1,67 @@ package net.idea.restnet.c.reporters; import java.io.Writer; import java.util.Iterator; import net.idea.restnet.c.ResourceDoc; import net.idea.restnet.c.html.HTMLBeauty; import org.restlet.Request; /** * HTML reporter for {@link AlgorithmResource} * @author nina * * @param <T> */ public class CatalogHTMLReporter<T> extends CatalogURIReporter<T> { /** * */ private static final long serialVersionUID = 7644836050657868159L; protected HTMLBeauty htmlBeauty; public HTMLBeauty getHtmlBeauty() { return htmlBeauty; } public void setHtmlBeauty(HTMLBeauty htmlBeauty) { this.htmlBeauty = htmlBeauty; } public CatalogHTMLReporter(Request request,ResourceDoc doc) { this(request,doc,null); } public CatalogHTMLReporter(Request request,ResourceDoc doc,HTMLBeauty htmlbeauty) { super(request,doc); this.htmlBeauty = htmlbeauty; } @Override public void header(Writer output, Iterator<T> query) { try { if (htmlBeauty==null) htmlBeauty = new HTMLBeauty(); - htmlBeauty.writeHTMLHeader(output, "AMBIT", getRequest(), + htmlBeauty.writeHTMLHeader(output, htmlBeauty.getTitle(), getRequest(), getDocumentation());//,"<meta http-equiv=\"refresh\" content=\"10\">"); } catch (Exception x) { } } public void processItem(T item, Writer output) { try { String t = super.getURI(item); output.write(String.format("<a href='%s'>%s</a><br>", t,item)); } catch (Exception x) { } }; @Override public void footer(Writer output, Iterator<T> query) { try { if (htmlBeauty == null) htmlBeauty = new HTMLBeauty(); htmlBeauty.writeHTMLFooter(output, "", getRequest()); output.flush(); } catch (Exception x) { } } }
true
true
public void header(Writer output, Iterator<T> query) { try { if (htmlBeauty==null) htmlBeauty = new HTMLBeauty(); htmlBeauty.writeHTMLHeader(output, "AMBIT", getRequest(), getDocumentation());//,"<meta http-equiv=\"refresh\" content=\"10\">"); } catch (Exception x) { } }
public void header(Writer output, Iterator<T> query) { try { if (htmlBeauty==null) htmlBeauty = new HTMLBeauty(); htmlBeauty.writeHTMLHeader(output, htmlBeauty.getTitle(), getRequest(), getDocumentation());//,"<meta http-equiv=\"refresh\" content=\"10\">"); } catch (Exception x) { } }
diff --git a/src/itopos/ItoPosFrame.java b/src/itopos/ItoPosFrame.java index 4c6c21d..674bcfe 100644 --- a/src/itopos/ItoPosFrame.java +++ b/src/itopos/ItoPosFrame.java @@ -1,560 +1,560 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * ItoPosFrame.java * * Created on 2009/04/10, 7:34:18 */ package itopos; import db.DaoFactry; import db.HistoryDao; import db.ItemDao; import db.UserDao; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.concurrent.FutureTask; import javax.swing.DefaultListModel; import javax.swing.JLabel; import javax.swing.Timer; import obj.Customer; import obj.History; import obj.Item; import sound.Sound; import twitter.TwitterAccount; import twitter4j.TwitterException; /** * * @author yasuhiro-i,shinya-m */ @SuppressWarnings("serial") public class ItoPosFrame extends javax.swing.JFrame implements Mediator, ActionListener { ItemDao idao; UserDao udao; HistoryDao hdao; UdpFelica udpFelica; protected DefaultListModel model; constant.Status.ItoPosStatus itoposStatus; ArrayList<Item> bucket; Customer user; Timer timer; sound.Sound sound; boolean updateItem; TwitterAccount tw; void requestRePaint() { this.configPanel.validate(); } /** Creates new form ItoPosFrame */ public ItoPosFrame() { initComponents(); this.idao = DaoFactry.createItemDao(); this.udao = DaoFactry.createUserDao(); this.hdao = DaoFactry.createHistoryDao(); model = new DefaultListModel(); bucket = new ArrayList<Item>(); udpFelica = new UdpFelica(50005); Thread th = new Thread(udpFelica); th.start(); createCollegues(); jListBacket.setModel(model); itoposStatus = constant.Status.ItoPosStatus.INIT; centerImagePanel.setFolder(constant.Graphics.CENTER_LOGO_FOLDER); sound = new Sound("hogehoge"); try { tw=new TwitterAccount(this); } catch (TwitterException e1) { e1.printStackTrace(); } catch (URISyntaxException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } barcodeField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { //System.out.println(e.getKeyCode()); if (e.getKeyCode() == 10) {//バーコードを読み込んだら if (!barcodeField.isEditable()) { return; } if (barcodeField.getText().equals(constant.Barcode.HISTORY)) {//読み取ったバーコードがヒストリーならば ArrayList<String> histories = hdao.getHistory(); barcodeField.setText(""); configPanel.removeAll(); configPanel.setLayout(new GridLayout(0, 1, 5, 5)); int index = 0; for (String history : histories) { index++; if (index > 10) { break; } JLabel obj = new JLabel(history); obj.setFont(new java.awt.Font("HGS創英角ポップ体", 0, 12)); configPanel.add(obj); } configPanel.repaint(); configPanel.validate(); return; } if (barcodeField.getText().equals(constant.Barcode.LANKING)) {//読み取ったバーコードがランキングならば ArrayList<Customer> users = udao.selectUserLanking(); barcodeField.setText(""); configPanel.removeAll(); configPanel.setLayout(new GridLayout(0, 2, 10, 10)); //configPanel.removeAll(); //configPanel.setLayout(new GridLayout(10, 0)); int index = 0; for (Customer user : users) { index++; if (index > 10) { break; } JLabel name = new JLabel(user.getNickName()); JLabel money = new JLabel(Integer.toString((int) user.getAllConsumedPoint()) + "円"); name.setFont(new java.awt.Font("HGS創英角ポップ体", 0, 18)); money.setFont(new java.awt.Font("HGS創英角ポップ体", 0, 18)); configPanel.add(name); configPanel.add(money); } configPanel.repaint(); configPanel.validate(); return; } if (barcodeField.getText().equals(constant.Barcode.CANCEL)) {//読み取ったバーコードがキャンセルならば messageLabel.setText("キャンセルされました"); requestResetSystem(3); return; } if (barcodeField.getText().equals(constant.Barcode.BUY)) {//読み取ったバーコードが購入ならば if (bucket.size() == 0) {//買い物かごに何もなければ barcodeField.setText(""); messageLabel.setText("恐れ入ります。カゴに何も入っていません。もう一度ゆっくりとお願いします。"); FutureTask task = new FutureTask(new Sound(constant.SoundFile.DENY)); new Thread(task).start(); itoposStatus = constant.Status.ItoPosStatus.REBOOT; requestResetSystem(3); return; } if (itoposStatus.equals(constant.Status.ItoPosStatus.AUTHORIZED)) {//学生証が読み込まれていれば int cost = 0; int count=0; StringBuilder sb=new StringBuilder(); for (Item item : bucket) { cost += item.getSold_cost(); //item.setPro_num(item.getPro_num()-1); Item tmp = idao.selectByBarCode(item.getBarcode()); sb.append(tmp.getName()); if(count<bucket.size()-1)sb.append(","); count++; int stock = tmp.getPro_num() - 1; item.setPro_num(stock);//在庫を減らす idao.updateBuppin(item); if(stock==0){ try { tw.tweet(item.getName()+"の在庫が無くなりました。完売御礼!"); } catch (TwitterException e1) { e1.printStackTrace(); } } } int aftercost = user.getCost() - cost;//残金 double allcost = user.getAllConsumedPoint(); udao.updateUser(user.getFelicaId(), aftercost, allcost + cost); messageLabel.setText("お買い上げ金額は " + cost + "円です。 ありがとうございました。" + "残金は" + aftercost + "円です(買う前" + user.getCost() + ")"); sound.PlayWave(constant.SoundFile.END); barcodeField.setText(""); for (Item item : bucket) { History h = new History(); h.setBid(item.getBarcode()); h.setUid(user.getFelicaId()); hdao.insertHistory(h); } itoposStatus = constant.Status.ItoPosStatus.REBOOT; requestResetSystem(3); try { String s=user.getNickName()+"さんが"; String ss="を購入しました!"; - String sss=user.getNickName()+"はこれまでに"+(int)user.getAllConsumedPoint()+"円使ってますよ。"; + String sss=user.getNickName()+"さんはこれまでに"+((int)user.getAllConsumedPoint()+cost)+"円使ってますよ。"; String tweet=s+tw.shrinkString(sb.toString(),140-s.length()-ss.length()-sss.length())+ss+sss; tw.tweet(tweet); } catch (TwitterException e1) { e1.printStackTrace(); } return; } } String bcode = barcodeField.getText(); if(!idao.isBuppinExist(bcode)){//読み取ったバーコードの商品がない場合は登録フォームを出す new ItemRegistrationForm(idao,ItoPosFrame.this,bcode,tw); barcodeField.setText(""); return; // barcodeField.setText(""); // messageLabel.setText("存在しないバーコードです"); // FutureTask task = new FutureTask(new Sound(constant.SoundFile.DENY)); // new Thread(task).start(); } if (idao.isBuppinExist(bcode)) {//読み取ったバーコードの商品がある場合 if(itoposStatus.equals(constant.Status.ItoPosStatus.AUTHORIZED)){//学生証が読み込まれていれば Item item = idao.selectByBarCode(bcode); model.addElement(item.getName() + ", " + item.getSold_cost() + "円"); bucket.add(item); barcodeField.setText(""); barcodeField.requestFocus(); messageLabel.setText("かごに入れました"); }else if(updateItem){//在庫追加モードならば new ItemRegistrationForm(idao, ItoPosFrame.this,tw).set(idao.selectByBarCode(bcode)); barcodeField.setText(""); }else{ messageLabel.setText("認証してください"); requestResetSystem(3); return; } } } else if(e.getKeyCode()==27){//ESCで終了 System.exit(0); }else if(e.getKeyCode()==KeyEvent.VK_F5){//F5キー if (itoposStatus.equals(constant.Status.ItoPosStatus.AUTHORIZED)){ new CostForm(udao, user,ItoPosFrame.this); } }else if(e.getKeyCode()==KeyEvent.VK_F1){//F1キー、在庫追加モード updateItem=true; return; } super.keyPressed(e); } }); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jDialog1 = new javax.swing.JDialog(); jPanel1 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); messageLabel = new javax.swing.JLabel(); statusLabel = new javax.swing.JLabel(); countDown1 = new count.countDown(); jPanel2 = new javax.swing.JPanel(); barcodeField = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jListBacket = new javax.swing.JList(); jLabel2 = new javax.swing.JLabel(); configPanel = new javax.swing.JPanel(); centerImagePanel = new util.ImagePanel(); javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane()); jDialog1.getContentPane().setLayout(jDialog1Layout); jDialog1Layout.setHorizontalGroup( jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 400, Short.MAX_VALUE) ); jDialog1Layout.setVerticalGroup( jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setUndecorated(true); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setLayout(new java.awt.BorderLayout(10, 10)); jPanel4.setBackground(new java.awt.Color(255, 204, 204)); jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); messageLabel.setFont(new java.awt.Font("HGS創英角ポップ体", 0, 18)); messageLabel.setText("メッセージ"); statusLabel.setFont(new java.awt.Font("HGP創英角ポップ体", 0, 18)); statusLabel.setText("ステータス"); countDown1.setFont(new java.awt.Font("MS UI Gothic", 1, 14)); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(messageLabel) .addComponent(statusLabel) .addComponent(countDown1, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(916, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(messageLabel) .addGap(29, 29, 29) .addComponent(statusLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(countDown1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(62, Short.MAX_VALUE)) ); jPanel1.add(jPanel4, java.awt.BorderLayout.SOUTH); jPanel2.setBackground(new java.awt.Color(255, 153, 153)); jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); barcodeField.setBackground(new java.awt.Color(255, 255, 204)); barcodeField.setFont(new java.awt.Font("HG創英角ポップ体", 0, 18)); barcodeField.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jLabel1.setFont(new java.awt.Font("HGP創英角ポップ体", 3, 18)); jLabel1.setText("バーコード"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(barcodeField, javax.swing.GroupLayout.DEFAULT_SIZE, 994, Short.MAX_VALUE))) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(barcodeField, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(95, Short.MAX_VALUE)) ); jPanel1.add(jPanel2, java.awt.BorderLayout.PAGE_START); jPanel3.setBackground(new java.awt.Color(255, 204, 204)); jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jListBacket.setBackground(new java.awt.Color(204, 255, 204)); jListBacket.setFont(new java.awt.Font("HGP創英角ポップ体", 0, 18)); jScrollPane1.setViewportView(jListBacket); jLabel2.setFont(new java.awt.Font("HGS創英角ポップ体", 0, 18)); jLabel2.setText("買い物かご"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE) .addComponent(jLabel2)) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE) .addContainerGap()) ); jPanel1.add(jPanel3, java.awt.BorderLayout.WEST); configPanel.setBackground(new java.awt.Color(255, 204, 204)); configPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); configPanel.setMinimumSize(new java.awt.Dimension(300, 300)); javax.swing.GroupLayout configPanelLayout = new javax.swing.GroupLayout(configPanel); configPanel.setLayout(configPanelLayout); configPanelLayout.setHorizontalGroup( configPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); configPanelLayout.setVerticalGroup( configPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 276, Short.MAX_VALUE) ); jPanel1.add(configPanel, java.awt.BorderLayout.EAST); centerImagePanel.setBackground(new java.awt.Color(204, 204, 204)); centerImagePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); centerImagePanel.setMaximumSize(new java.awt.Dimension(300, 300)); javax.swing.GroupLayout centerImagePanelLayout = new javax.swing.GroupLayout(centerImagePanel); centerImagePanel.setLayout(centerImagePanelLayout); centerImagePanelLayout.setHorizontalGroup( centerImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 421, Short.MAX_VALUE) ); centerImagePanelLayout.setVerticalGroup( centerImagePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 276, Short.MAX_VALUE) ); jPanel1.add(centerImagePanel, java.awt.BorderLayout.CENTER); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 1020, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 682, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField barcodeField; private util.ImagePanel centerImagePanel; private javax.swing.JPanel configPanel; private count.countDown countDown1; private javax.swing.JDialog jDialog1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JList jListBacket; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel messageLabel; private javax.swing.JLabel statusLabel; // End of variables declaration//GEN-END:variables public void resetSystem() { barcodeField.setText(""); messageLabel.setText("ようこそ"); barcodeField.requestFocus(); model.clear(); bucket.clear(); barcodeField.requestFocus(); itoposStatus = constant.Status.ItoPosStatus.INIT; statusLabel.setText("初期状態"); barcodeField.setEnabled(true); } private void requestResetSystem(int sec) { //timer = new Timer(sec * 1000, this); //timer.start(); barcodeField.setEnabled(false); countDown1.setCount(sec); } public void requestResetSystem(int sec, boolean editable) { barcodeField.setEnabled(editable); countDown1.setCount(sec); } public void createCollegues() { udpFelica.setMediator(this); countDown1.setMediator(this); } @Override public void collegueChanged(String message) { if (message.equals("GETPACKET")) { user = udao.selectUser(udpFelica.getMID()); if (!this.itoposStatus.equals(constant.Status.ItoPosStatus.INIT)) { return; } if (user.getName() != null) { if (user.getCost() >= 100) { messageLabel.setText("毎度ありがとうございます" + user.getName() + "さん。 " + "残金は" + user.getCost() + "円です"); itoposStatus = constant.Status.ItoPosStatus.AUTHORIZED; statusLabel.setText("認証済み"); barcodeField.setEditable(false); FutureTask task = new FutureTask(new Sound(constant.SoundFile.AUTH_SOUND)); new Thread(task).start(); barcodeField.setEditable(true); requestResetSystem(360, true); } else { messageLabel.setText("毎度ありがとうございます" + user.getName() + "さん。 " + " 残金は" + user.getCost() + "円ですが、少なすぎないですか?"); itoposStatus = constant.Status.ItoPosStatus.AUTHORIZED; statusLabel.setText("認証済み"); barcodeField.setEditable(false); FutureTask task = new FutureTask(new Sound(constant.SoundFile.SAISOKU)); new Thread(task).start(); barcodeField.setEditable(true); requestResetSystem(360, true); } } else {//学生証が登録されていなかったら //TODO // messageLabel.setText("認証エラーです。やりなおしてください"); // FutureTask task = new FutureTask(new Sound(constant.SoundFile.DENY)); // new Thread(task).start(); // this.itoposStatus = constant.Status.ItoPosStatus.REBOOT; // requestResetSystem(3); new UserRegistrationForm(udpFelica.getMID(),udao); } } if (message.equals("TIME_OUT")) { resetSystem(); } } public void cancelUpdateItem(){ updateItem=false; } public void actionPerformed(ActionEvent e) { } }
true
true
public ItoPosFrame() { initComponents(); this.idao = DaoFactry.createItemDao(); this.udao = DaoFactry.createUserDao(); this.hdao = DaoFactry.createHistoryDao(); model = new DefaultListModel(); bucket = new ArrayList<Item>(); udpFelica = new UdpFelica(50005); Thread th = new Thread(udpFelica); th.start(); createCollegues(); jListBacket.setModel(model); itoposStatus = constant.Status.ItoPosStatus.INIT; centerImagePanel.setFolder(constant.Graphics.CENTER_LOGO_FOLDER); sound = new Sound("hogehoge"); try { tw=new TwitterAccount(this); } catch (TwitterException e1) { e1.printStackTrace(); } catch (URISyntaxException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } barcodeField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { //System.out.println(e.getKeyCode()); if (e.getKeyCode() == 10) {//バーコードを読み込んだら if (!barcodeField.isEditable()) { return; } if (barcodeField.getText().equals(constant.Barcode.HISTORY)) {//読み取ったバーコードがヒストリーならば ArrayList<String> histories = hdao.getHistory(); barcodeField.setText(""); configPanel.removeAll(); configPanel.setLayout(new GridLayout(0, 1, 5, 5)); int index = 0; for (String history : histories) { index++; if (index > 10) { break; } JLabel obj = new JLabel(history); obj.setFont(new java.awt.Font("HGS創英角ポップ体", 0, 12)); configPanel.add(obj); } configPanel.repaint(); configPanel.validate(); return; } if (barcodeField.getText().equals(constant.Barcode.LANKING)) {//読み取ったバーコードがランキングならば ArrayList<Customer> users = udao.selectUserLanking(); barcodeField.setText(""); configPanel.removeAll(); configPanel.setLayout(new GridLayout(0, 2, 10, 10)); //configPanel.removeAll(); //configPanel.setLayout(new GridLayout(10, 0)); int index = 0; for (Customer user : users) { index++; if (index > 10) { break; } JLabel name = new JLabel(user.getNickName()); JLabel money = new JLabel(Integer.toString((int) user.getAllConsumedPoint()) + "円"); name.setFont(new java.awt.Font("HGS創英角ポップ体", 0, 18)); money.setFont(new java.awt.Font("HGS創英角ポップ体", 0, 18)); configPanel.add(name); configPanel.add(money); } configPanel.repaint(); configPanel.validate(); return; } if (barcodeField.getText().equals(constant.Barcode.CANCEL)) {//読み取ったバーコードがキャンセルならば messageLabel.setText("キャンセルされました"); requestResetSystem(3); return; } if (barcodeField.getText().equals(constant.Barcode.BUY)) {//読み取ったバーコードが購入ならば if (bucket.size() == 0) {//買い物かごに何もなければ barcodeField.setText(""); messageLabel.setText("恐れ入ります。カゴに何も入っていません。もう一度ゆっくりとお願いします。"); FutureTask task = new FutureTask(new Sound(constant.SoundFile.DENY)); new Thread(task).start(); itoposStatus = constant.Status.ItoPosStatus.REBOOT; requestResetSystem(3); return; } if (itoposStatus.equals(constant.Status.ItoPosStatus.AUTHORIZED)) {//学生証が読み込まれていれば int cost = 0; int count=0; StringBuilder sb=new StringBuilder(); for (Item item : bucket) { cost += item.getSold_cost(); //item.setPro_num(item.getPro_num()-1); Item tmp = idao.selectByBarCode(item.getBarcode()); sb.append(tmp.getName()); if(count<bucket.size()-1)sb.append(","); count++; int stock = tmp.getPro_num() - 1; item.setPro_num(stock);//在庫を減らす idao.updateBuppin(item); if(stock==0){ try { tw.tweet(item.getName()+"の在庫が無くなりました。完売御礼!"); } catch (TwitterException e1) { e1.printStackTrace(); } } } int aftercost = user.getCost() - cost;//残金 double allcost = user.getAllConsumedPoint(); udao.updateUser(user.getFelicaId(), aftercost, allcost + cost); messageLabel.setText("お買い上げ金額は " + cost + "円です。 ありがとうございました。" + "残金は" + aftercost + "円です(買う前" + user.getCost() + ")"); sound.PlayWave(constant.SoundFile.END); barcodeField.setText(""); for (Item item : bucket) { History h = new History(); h.setBid(item.getBarcode()); h.setUid(user.getFelicaId()); hdao.insertHistory(h); } itoposStatus = constant.Status.ItoPosStatus.REBOOT; requestResetSystem(3); try { String s=user.getNickName()+"さんが"; String ss="を購入しました!"; String sss=user.getNickName()+"はこれまでに"+(int)user.getAllConsumedPoint()+"円使ってますよ。"; String tweet=s+tw.shrinkString(sb.toString(),140-s.length()-ss.length()-sss.length())+ss+sss; tw.tweet(tweet); } catch (TwitterException e1) { e1.printStackTrace(); } return; } } String bcode = barcodeField.getText(); if(!idao.isBuppinExist(bcode)){//読み取ったバーコードの商品がない場合は登録フォームを出す new ItemRegistrationForm(idao,ItoPosFrame.this,bcode,tw); barcodeField.setText(""); return; // barcodeField.setText(""); // messageLabel.setText("存在しないバーコードです"); // FutureTask task = new FutureTask(new Sound(constant.SoundFile.DENY)); // new Thread(task).start(); } if (idao.isBuppinExist(bcode)) {//読み取ったバーコードの商品がある場合 if(itoposStatus.equals(constant.Status.ItoPosStatus.AUTHORIZED)){//学生証が読み込まれていれば Item item = idao.selectByBarCode(bcode); model.addElement(item.getName() + ", " + item.getSold_cost() + "円"); bucket.add(item); barcodeField.setText(""); barcodeField.requestFocus(); messageLabel.setText("かごに入れました"); }else if(updateItem){//在庫追加モードならば new ItemRegistrationForm(idao, ItoPosFrame.this,tw).set(idao.selectByBarCode(bcode)); barcodeField.setText(""); }else{ messageLabel.setText("認証してください"); requestResetSystem(3); return; } } } else if(e.getKeyCode()==27){//ESCで終了 System.exit(0); }else if(e.getKeyCode()==KeyEvent.VK_F5){//F5キー if (itoposStatus.equals(constant.Status.ItoPosStatus.AUTHORIZED)){ new CostForm(udao, user,ItoPosFrame.this); } }else if(e.getKeyCode()==KeyEvent.VK_F1){//F1キー、在庫追加モード updateItem=true; return; } super.keyPressed(e); } }); }
public ItoPosFrame() { initComponents(); this.idao = DaoFactry.createItemDao(); this.udao = DaoFactry.createUserDao(); this.hdao = DaoFactry.createHistoryDao(); model = new DefaultListModel(); bucket = new ArrayList<Item>(); udpFelica = new UdpFelica(50005); Thread th = new Thread(udpFelica); th.start(); createCollegues(); jListBacket.setModel(model); itoposStatus = constant.Status.ItoPosStatus.INIT; centerImagePanel.setFolder(constant.Graphics.CENTER_LOGO_FOLDER); sound = new Sound("hogehoge"); try { tw=new TwitterAccount(this); } catch (TwitterException e1) { e1.printStackTrace(); } catch (URISyntaxException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } barcodeField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { //System.out.println(e.getKeyCode()); if (e.getKeyCode() == 10) {//バーコードを読み込んだら if (!barcodeField.isEditable()) { return; } if (barcodeField.getText().equals(constant.Barcode.HISTORY)) {//読み取ったバーコードがヒストリーならば ArrayList<String> histories = hdao.getHistory(); barcodeField.setText(""); configPanel.removeAll(); configPanel.setLayout(new GridLayout(0, 1, 5, 5)); int index = 0; for (String history : histories) { index++; if (index > 10) { break; } JLabel obj = new JLabel(history); obj.setFont(new java.awt.Font("HGS創英角ポップ体", 0, 12)); configPanel.add(obj); } configPanel.repaint(); configPanel.validate(); return; } if (barcodeField.getText().equals(constant.Barcode.LANKING)) {//読み取ったバーコードがランキングならば ArrayList<Customer> users = udao.selectUserLanking(); barcodeField.setText(""); configPanel.removeAll(); configPanel.setLayout(new GridLayout(0, 2, 10, 10)); //configPanel.removeAll(); //configPanel.setLayout(new GridLayout(10, 0)); int index = 0; for (Customer user : users) { index++; if (index > 10) { break; } JLabel name = new JLabel(user.getNickName()); JLabel money = new JLabel(Integer.toString((int) user.getAllConsumedPoint()) + "円"); name.setFont(new java.awt.Font("HGS創英角ポップ体", 0, 18)); money.setFont(new java.awt.Font("HGS創英角ポップ体", 0, 18)); configPanel.add(name); configPanel.add(money); } configPanel.repaint(); configPanel.validate(); return; } if (barcodeField.getText().equals(constant.Barcode.CANCEL)) {//読み取ったバーコードがキャンセルならば messageLabel.setText("キャンセルされました"); requestResetSystem(3); return; } if (barcodeField.getText().equals(constant.Barcode.BUY)) {//読み取ったバーコードが購入ならば if (bucket.size() == 0) {//買い物かごに何もなければ barcodeField.setText(""); messageLabel.setText("恐れ入ります。カゴに何も入っていません。もう一度ゆっくりとお願いします。"); FutureTask task = new FutureTask(new Sound(constant.SoundFile.DENY)); new Thread(task).start(); itoposStatus = constant.Status.ItoPosStatus.REBOOT; requestResetSystem(3); return; } if (itoposStatus.equals(constant.Status.ItoPosStatus.AUTHORIZED)) {//学生証が読み込まれていれば int cost = 0; int count=0; StringBuilder sb=new StringBuilder(); for (Item item : bucket) { cost += item.getSold_cost(); //item.setPro_num(item.getPro_num()-1); Item tmp = idao.selectByBarCode(item.getBarcode()); sb.append(tmp.getName()); if(count<bucket.size()-1)sb.append(","); count++; int stock = tmp.getPro_num() - 1; item.setPro_num(stock);//在庫を減らす idao.updateBuppin(item); if(stock==0){ try { tw.tweet(item.getName()+"の在庫が無くなりました。完売御礼!"); } catch (TwitterException e1) { e1.printStackTrace(); } } } int aftercost = user.getCost() - cost;//残金 double allcost = user.getAllConsumedPoint(); udao.updateUser(user.getFelicaId(), aftercost, allcost + cost); messageLabel.setText("お買い上げ金額は " + cost + "円です。 ありがとうございました。" + "残金は" + aftercost + "円です(買う前" + user.getCost() + ")"); sound.PlayWave(constant.SoundFile.END); barcodeField.setText(""); for (Item item : bucket) { History h = new History(); h.setBid(item.getBarcode()); h.setUid(user.getFelicaId()); hdao.insertHistory(h); } itoposStatus = constant.Status.ItoPosStatus.REBOOT; requestResetSystem(3); try { String s=user.getNickName()+"さんが"; String ss="を購入しました!"; String sss=user.getNickName()+"さんはこれまでに"+((int)user.getAllConsumedPoint()+cost)+"円使ってますよ。"; String tweet=s+tw.shrinkString(sb.toString(),140-s.length()-ss.length()-sss.length())+ss+sss; tw.tweet(tweet); } catch (TwitterException e1) { e1.printStackTrace(); } return; } } String bcode = barcodeField.getText(); if(!idao.isBuppinExist(bcode)){//読み取ったバーコードの商品がない場合は登録フォームを出す new ItemRegistrationForm(idao,ItoPosFrame.this,bcode,tw); barcodeField.setText(""); return; // barcodeField.setText(""); // messageLabel.setText("存在しないバーコードです"); // FutureTask task = new FutureTask(new Sound(constant.SoundFile.DENY)); // new Thread(task).start(); } if (idao.isBuppinExist(bcode)) {//読み取ったバーコードの商品がある場合 if(itoposStatus.equals(constant.Status.ItoPosStatus.AUTHORIZED)){//学生証が読み込まれていれば Item item = idao.selectByBarCode(bcode); model.addElement(item.getName() + ", " + item.getSold_cost() + "円"); bucket.add(item); barcodeField.setText(""); barcodeField.requestFocus(); messageLabel.setText("かごに入れました"); }else if(updateItem){//在庫追加モードならば new ItemRegistrationForm(idao, ItoPosFrame.this,tw).set(idao.selectByBarCode(bcode)); barcodeField.setText(""); }else{ messageLabel.setText("認証してください"); requestResetSystem(3); return; } } } else if(e.getKeyCode()==27){//ESCで終了 System.exit(0); }else if(e.getKeyCode()==KeyEvent.VK_F5){//F5キー if (itoposStatus.equals(constant.Status.ItoPosStatus.AUTHORIZED)){ new CostForm(udao, user,ItoPosFrame.this); } }else if(e.getKeyCode()==KeyEvent.VK_F1){//F1キー、在庫追加モード updateItem=true; return; } super.keyPressed(e); } }); }
diff --git a/src/com/VolunteerCoordinatorApp/addVolunteerServlet.java b/src/com/VolunteerCoordinatorApp/addVolunteerServlet.java index 487d5d9..df42ff9 100644 --- a/src/com/VolunteerCoordinatorApp/addVolunteerServlet.java +++ b/src/com/VolunteerCoordinatorApp/addVolunteerServlet.java @@ -1,490 +1,490 @@ package com.VolunteerCoordinatorApp; import java.io.*; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import javax.jdo.PersistenceManager; import javax.jdo.Transaction; import javax.servlet.http.*; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.gdata.client.calendar.CalendarQuery; import com.google.gdata.client.calendar.CalendarService; import com.google.gdata.data.*; import com.google.gdata.data.acl.*; import com.google.gdata.data.calendar.*; import com.google.gdata.data.extensions.*; import com.google.gdata.util.AuthenticationException; import com.google.gdata.util.ServiceException; @SuppressWarnings("serial") public class addVolunteerServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String date = req.getParameter("date"); String title = req.getParameter("title"); String name = req.getParameter("name"); //If no user in query string, prompt to log in. if (name == null || name.equalsIgnoreCase("null") || name.equals("")) { resp.sendRedirect("/loginredirect?url=" + req.getRequestURI() + "?" + req.getQueryString()); } //Otherwise proceed normally. else { URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full"); //&max-results=10"); CalendarQuery myQuery = new CalendarQuery(feedUrl); myQuery.setStringCustomParameter("orderby", "starttime"); myQuery.setStringCustomParameter("sortorder", "ascending"); myQuery.setStringCustomParameter("futureevents", "true"); myQuery.setStringCustomParameter("singleevents", "true"); //Get a date one day ahead of the event clicked on and make it the max date of the query String datePattern = "MM-dd-yyyy"; SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); DateTime searchMaxDate = null; long searchMaxTime = 0; try { searchMaxDate = new DateTime(dateFormat.parse(date)); searchMaxTime = searchMaxDate.getValue(); searchMaxTime += 86400000; //86400000 milliseconds = 1 day searchMaxDate.setValue(searchMaxTime); } catch (ParseException e6) { // TODO Auto-generated catch block e6.printStackTrace(); } if (searchMaxDate != null) { myQuery.setMaximumStartTime(searchMaxDate); } //Get a date one day before the event clicked on and make it the max date of the query DateTime searchMinDate = null; long searchMinTime = 0; try { searchMinDate = new DateTime(dateFormat.parse(date)); searchMinTime = searchMinDate.getValue(); searchMinTime -= 86400000; //86400000 milliseconds = 1 day searchMinDate.setValue(searchMinTime); } catch (ParseException e6) { // TODO Auto-generated catch block e6.printStackTrace(); } if (searchMinDate != null) { myQuery.setMinimumStartTime(searchMinDate); } CalendarService myService = new CalendarService("Volunteer-Coordinator-Calendar"); try { myService.setUserCredentials("[email protected]", "G0covenant"); } catch (AuthenticationException e) { // TODO Auto-generated catch block System.err.println( "Failed to authenticate service." ); e.printStackTrace(); } // Send the request and receive the response: CalendarEventFeed resultFeed = null; try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch (ServiceException e) { // TODO Auto-generated catch block System.err.println( "Failed to send query." ); e.printStackTrace(); } catch (IOException e) { // Retry try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } List<CalendarEventEntry> results = (List<CalendarEventEntry>)resultFeed.getEntries(); for (CalendarEventEntry entry : results) { // Get the start time for the event When time = entry.getTimes().get(0); DateTime start = time.getStartTime(); DateTime end = time.getEndTime(); PersistenceManager pManager = PMF.get().getPersistenceManager(); Key k = KeyFactory.createKey(Volunteer.class.getSimpleName(), name); Volunteer vol = pManager.getObjectById(Volunteer.class, k); String timeZone = vol.getTimeZone(); //Set time zone to be the time zone of whatever user is volunteering TimeZone TZ = TimeZone.getTimeZone( timeZone ); Date startDate = new Date(start.getValue()); Date endDate = new Date(end.getValue()); //Determine timezone offset in minutes, depending on whether or not //Daylight Savings Time is in effect if (TZ.inDaylightTime(startDate)) { start.setTzShift(-240); } else { start.setTzShift(-300); } if (TZ.inDaylightTime(endDate)) { end.setTzShift(-240); } else { end.setTzShift(-300); } // Convert to milliseconds to get a date object, which can be formatted easier. Date entryDate = new Date(start.getValue() + 1000 * (start.getTzShift() * 60)); String startDay = dateFormat.format(entryDate); String eventTitle = new String(entry.getTitle().getPlainText()); if (startDay.equals(date) && eventTitle.equals(title)) { //Updates the acceptedBy tag to show the username of the acceptor List<ExtendedProperty> propList = entry.getExtendedProperty(); boolean propFound = false; for (ExtendedProperty prop : propList) { if( prop.getName().equals( "acceptedBy" ) ) { + propFound = true; prop.setValue( name ); - //Shouldn't we set propFound to true? } } if( !propFound ) { ExtendedProperty acceptedBy = new ExtendedProperty(); acceptedBy.setName( "acceptedBy" ); acceptedBy.setValue( name ); entry.addExtendedProperty( acceptedBy ); } URL editUrl = new URL(entry.getEditLink().getHref()); try { myService.update(editUrl, entry); } catch (ServiceException e) { // TODO Auto-generated catch block System.err.println( "Failed to successfully set content." ); e.printStackTrace(); } catch (IOException e) { // Retry try { myService.update(editUrl, entry); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } //Get the ID of this user's calendar from the datastore. String usrCalUrl = vol.getCalendarId(); URL newUrl = new URL("http://www.google.com/calendar/feeds/" + usrCalUrl + "/private/full"); CalendarEventEntry newEvent = null; // If the event is recurring, create a non-recurring clone of the event to add to the user's calendar if (entry.getOriginalEvent() != null) { newEvent = new CalendarEventEntry(); newEvent.setTitle(entry.getTitle()); // Title newEvent.setContent(entry.getContent()); // Description newEvent.addTime( entry.getTimes().get(0) ); // Date/Time for (ExtendedProperty prop : propList) { // Other details ExtendedProperty ep = new ExtendedProperty(); ep.setName( prop.getName() ); ep.setValue( prop.getValue() ); newEvent.addExtendedProperty( ep ); } } else { newEvent = entry; } //If insert is unsuccessful, we look for a way to replace the stored //calendar URL, up to and including making a new calendar. try { try { myService.insert(newUrl, newEvent); } catch (IOException ioe) { //Retry myService.insert(newUrl, newEvent); } } catch ( ServiceException e ) { System.err.println( "Failed to insert into calendar at " + usrCalUrl ); e.printStackTrace(); URL newFeedUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full"); CalendarFeed newResultFeed = null; try { newResultFeed = myService.getFeed(newFeedUrl, CalendarFeed.class); } catch ( ServiceException e3 ) { // TODO Auto-generated catch block System.err.println( "Failed to fetch feed of calendars." ); e3.printStackTrace(); } catch (IOException e4) { // Retry try { newResultFeed = myService.getFeed(newFeedUrl, CalendarFeed.class); } catch (ServiceException e5) { // TODO Auto-generated catch block e5.printStackTrace(); } } String calUrl = null; for( int i = 0; i < newResultFeed.getEntries().size(); i++ ) { CalendarEntry newEntry = newResultFeed.getEntries().get( i ); //String compare is not a great way to do it, //but I'm not sure there is another option. if( newEntry.getTitle().getPlainText().equals( name+"'s Jobs" ) ) { CalendarEntry calendar = newEntry; // Get the calender's url calUrl = calendar.getId(); int splitHere = calUrl.lastIndexOf("/") + 1; calUrl = calUrl.substring(splitHere); break; } } boolean calendarDeleted = false; //Check to see if we can access the calendar calUrl links to. //If we can't, it's assumed to have been deleted, and we proceed to make a new one. if( calUrl != null ) { String nullString = null; try { URL testUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full/" + usrCalUrl); myService.getEntry( testUrl, CalendarEntry.class, nullString ); } catch( Exception e1 ) { System.err.println( "Failed to access calendar at " + calUrl ); calendarDeleted = true; } } //No extant calendars for this user; make a new one. if( calUrl == null || calendarDeleted ) { CalendarEntry calendar = new CalendarEntry(); calendar.setTitle(new PlainTextConstruct(name + "'s Jobs")); calendar.setSummary(new PlainTextConstruct("This calendar contains the jobs " + name + " has volunteered to coordinate for.")); calendar.setTimeZone(new TimeZoneProperty("America/New_York")); calendar.setHidden(HiddenProperty.FALSE); // Insert the calendar URL postUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full"); CalendarEntry newCalendar = null; try { newCalendar = myService.insert(postUrl, calendar); } catch ( ServiceException e2 ) { // TODO Auto-generated catch block System.err.println( "Failed at inserting new calendar." ); e2.printStackTrace(); } catch ( IOException e1 ) { // Retry try { newCalendar = myService.insert(postUrl, calendar); } catch (ServiceException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } // Get the calender's url calUrl = newCalendar.getId(); int splitHere = calUrl.lastIndexOf("/") + 1; calUrl = calUrl.substring(splitHere); //Find events on the calendar with this user's name attached newFeedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full"); myQuery = new CalendarQuery(feedUrl); myQuery.setFullTextQuery(name); resultFeed = null; try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Failed at getting a query." ); e1.printStackTrace(); } catch (IOException e8) { // Retry try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } List<CalendarEventEntry> entries = (List<CalendarEventEntry>)resultFeed.getEntries(); //Add all of those events to the new calendar if (!entries.isEmpty()) { for (CalendarEventEntry singleEntry : entries) { //Get the event's details TextConstruct entryTitle = singleEntry.getTitle(); String entryContent = singleEntry.getPlainTextContent(); When entryTime = singleEntry.getTimes().get(0); DateTime entryStart = entryTime.getStartTime(); DateTime entryEnd = entryTime.getEndTime(); //Date entryStartDate = new Date(start.getValue()); Date entryEndDate = new Date(entryEnd.getValue()); //Determine timezone offset in minutes, depending on whether or not //Daylight Savings Time is in effect if (TZ.inDaylightTime(startDate)) { entryStart.setTzShift(-240); } else { entryStart.setTzShift(-300); } if (TZ.inDaylightTime(entryEndDate)) { entryEnd.setTzShift(-240); } else { entryEnd.setTzShift(-300); } //Create a new entry and add it URL newEntryUrl = new URL( "http://www.google.com/calendar/feeds/" + calUrl + "/private/full"); CalendarEventEntry myEntry = new CalendarEventEntry(); myEntry.setTitle(entryTitle); myEntry.setContent(new PlainTextConstruct(entryContent)); When eventTimes = new When(); eventTimes.setStartTime(entryStart); eventTimes.setEndTime(entryEnd); myEntry.addTime(eventTimes); // Send the request and receive the response: try { myService.insert(newEntryUrl, myEntry); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Error inserting new entry into CalendarService." ); e1.printStackTrace(); } catch ( IOException e1 ) { //Retry try { myService.insert(newEntryUrl, myEntry); } catch (ServiceException e2) { // TODO Auto-generated catch block System.err.println( "Error inserting new entry into CalendarService." ); e2.printStackTrace(); } } } } // Access the Access Control List (ACL) for the calendar Link link = newCalendar.getLink(AclNamespace.LINK_REL_ACCESS_CONTROL_LIST, Link.Type.ATOM); URL aclUrl = new URL( link.getHref() ); AclFeed aclFeed = null; try { aclFeed = myService.getFeed(aclUrl, AclFeed.class); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Failed at getting ACL Feed." ); e1.printStackTrace(); } catch (IOException e8) { // Retry try { aclFeed = myService.getFeed(aclUrl, AclFeed.class); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } // Set the default to "read-only" for all users AclEntry aclEntry = aclFeed.createEntry(); aclEntry.setScope(new AclScope(AclScope.Type.DEFAULT, null)); aclEntry.setRole(CalendarAclRole.READ); // Add it to the ACL try { myService.insert(aclUrl, aclEntry); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Error inserting new entries into ACL." ); e1.printStackTrace(); } catch ( IOException e1 ) { //Retry try { myService.insert(aclUrl, aclEntry); } catch ( ServiceException e2 ) { // TODO Auto-generated catch block System.err.println( "Error inserting new entries into ACL." ); e2.printStackTrace(); } } } //Assign calendar ID to the Volunteer object for the user in question. Volunteer volunteer = null; PersistenceManager persistenceManager = PMF.get().getPersistenceManager(); Transaction tx = persistenceManager.currentTransaction(); try { tx.begin(); Key key = KeyFactory.createKey(Volunteer.class.getSimpleName(), name); volunteer = persistenceManager.getObjectById(Volunteer.class, key); volunteer.setCalendarId( calUrl ); tx.commit(); } catch (Exception e1) { if (tx.isActive()) { tx.rollback(); } } } } } resp.sendRedirect("/calendar.jsp?name=" + name); } } }
false
true
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String date = req.getParameter("date"); String title = req.getParameter("title"); String name = req.getParameter("name"); //If no user in query string, prompt to log in. if (name == null || name.equalsIgnoreCase("null") || name.equals("")) { resp.sendRedirect("/loginredirect?url=" + req.getRequestURI() + "?" + req.getQueryString()); } //Otherwise proceed normally. else { URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full"); //&max-results=10"); CalendarQuery myQuery = new CalendarQuery(feedUrl); myQuery.setStringCustomParameter("orderby", "starttime"); myQuery.setStringCustomParameter("sortorder", "ascending"); myQuery.setStringCustomParameter("futureevents", "true"); myQuery.setStringCustomParameter("singleevents", "true"); //Get a date one day ahead of the event clicked on and make it the max date of the query String datePattern = "MM-dd-yyyy"; SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); DateTime searchMaxDate = null; long searchMaxTime = 0; try { searchMaxDate = new DateTime(dateFormat.parse(date)); searchMaxTime = searchMaxDate.getValue(); searchMaxTime += 86400000; //86400000 milliseconds = 1 day searchMaxDate.setValue(searchMaxTime); } catch (ParseException e6) { // TODO Auto-generated catch block e6.printStackTrace(); } if (searchMaxDate != null) { myQuery.setMaximumStartTime(searchMaxDate); } //Get a date one day before the event clicked on and make it the max date of the query DateTime searchMinDate = null; long searchMinTime = 0; try { searchMinDate = new DateTime(dateFormat.parse(date)); searchMinTime = searchMinDate.getValue(); searchMinTime -= 86400000; //86400000 milliseconds = 1 day searchMinDate.setValue(searchMinTime); } catch (ParseException e6) { // TODO Auto-generated catch block e6.printStackTrace(); } if (searchMinDate != null) { myQuery.setMinimumStartTime(searchMinDate); } CalendarService myService = new CalendarService("Volunteer-Coordinator-Calendar"); try { myService.setUserCredentials("[email protected]", "G0covenant"); } catch (AuthenticationException e) { // TODO Auto-generated catch block System.err.println( "Failed to authenticate service." ); e.printStackTrace(); } // Send the request and receive the response: CalendarEventFeed resultFeed = null; try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch (ServiceException e) { // TODO Auto-generated catch block System.err.println( "Failed to send query." ); e.printStackTrace(); } catch (IOException e) { // Retry try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } List<CalendarEventEntry> results = (List<CalendarEventEntry>)resultFeed.getEntries(); for (CalendarEventEntry entry : results) { // Get the start time for the event When time = entry.getTimes().get(0); DateTime start = time.getStartTime(); DateTime end = time.getEndTime(); PersistenceManager pManager = PMF.get().getPersistenceManager(); Key k = KeyFactory.createKey(Volunteer.class.getSimpleName(), name); Volunteer vol = pManager.getObjectById(Volunteer.class, k); String timeZone = vol.getTimeZone(); //Set time zone to be the time zone of whatever user is volunteering TimeZone TZ = TimeZone.getTimeZone( timeZone ); Date startDate = new Date(start.getValue()); Date endDate = new Date(end.getValue()); //Determine timezone offset in minutes, depending on whether or not //Daylight Savings Time is in effect if (TZ.inDaylightTime(startDate)) { start.setTzShift(-240); } else { start.setTzShift(-300); } if (TZ.inDaylightTime(endDate)) { end.setTzShift(-240); } else { end.setTzShift(-300); } // Convert to milliseconds to get a date object, which can be formatted easier. Date entryDate = new Date(start.getValue() + 1000 * (start.getTzShift() * 60)); String startDay = dateFormat.format(entryDate); String eventTitle = new String(entry.getTitle().getPlainText()); if (startDay.equals(date) && eventTitle.equals(title)) { //Updates the acceptedBy tag to show the username of the acceptor List<ExtendedProperty> propList = entry.getExtendedProperty(); boolean propFound = false; for (ExtendedProperty prop : propList) { if( prop.getName().equals( "acceptedBy" ) ) { prop.setValue( name ); //Shouldn't we set propFound to true? } } if( !propFound ) { ExtendedProperty acceptedBy = new ExtendedProperty(); acceptedBy.setName( "acceptedBy" ); acceptedBy.setValue( name ); entry.addExtendedProperty( acceptedBy ); } URL editUrl = new URL(entry.getEditLink().getHref()); try { myService.update(editUrl, entry); } catch (ServiceException e) { // TODO Auto-generated catch block System.err.println( "Failed to successfully set content." ); e.printStackTrace(); } catch (IOException e) { // Retry try { myService.update(editUrl, entry); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } //Get the ID of this user's calendar from the datastore. String usrCalUrl = vol.getCalendarId(); URL newUrl = new URL("http://www.google.com/calendar/feeds/" + usrCalUrl + "/private/full"); CalendarEventEntry newEvent = null; // If the event is recurring, create a non-recurring clone of the event to add to the user's calendar if (entry.getOriginalEvent() != null) { newEvent = new CalendarEventEntry(); newEvent.setTitle(entry.getTitle()); // Title newEvent.setContent(entry.getContent()); // Description newEvent.addTime( entry.getTimes().get(0) ); // Date/Time for (ExtendedProperty prop : propList) { // Other details ExtendedProperty ep = new ExtendedProperty(); ep.setName( prop.getName() ); ep.setValue( prop.getValue() ); newEvent.addExtendedProperty( ep ); } } else { newEvent = entry; } //If insert is unsuccessful, we look for a way to replace the stored //calendar URL, up to and including making a new calendar. try { try { myService.insert(newUrl, newEvent); } catch (IOException ioe) { //Retry myService.insert(newUrl, newEvent); } } catch ( ServiceException e ) { System.err.println( "Failed to insert into calendar at " + usrCalUrl ); e.printStackTrace(); URL newFeedUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full"); CalendarFeed newResultFeed = null; try { newResultFeed = myService.getFeed(newFeedUrl, CalendarFeed.class); } catch ( ServiceException e3 ) { // TODO Auto-generated catch block System.err.println( "Failed to fetch feed of calendars." ); e3.printStackTrace(); } catch (IOException e4) { // Retry try { newResultFeed = myService.getFeed(newFeedUrl, CalendarFeed.class); } catch (ServiceException e5) { // TODO Auto-generated catch block e5.printStackTrace(); } } String calUrl = null; for( int i = 0; i < newResultFeed.getEntries().size(); i++ ) { CalendarEntry newEntry = newResultFeed.getEntries().get( i ); //String compare is not a great way to do it, //but I'm not sure there is another option. if( newEntry.getTitle().getPlainText().equals( name+"'s Jobs" ) ) { CalendarEntry calendar = newEntry; // Get the calender's url calUrl = calendar.getId(); int splitHere = calUrl.lastIndexOf("/") + 1; calUrl = calUrl.substring(splitHere); break; } } boolean calendarDeleted = false; //Check to see if we can access the calendar calUrl links to. //If we can't, it's assumed to have been deleted, and we proceed to make a new one. if( calUrl != null ) { String nullString = null; try { URL testUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full/" + usrCalUrl); myService.getEntry( testUrl, CalendarEntry.class, nullString ); } catch( Exception e1 ) { System.err.println( "Failed to access calendar at " + calUrl ); calendarDeleted = true; } } //No extant calendars for this user; make a new one. if( calUrl == null || calendarDeleted ) { CalendarEntry calendar = new CalendarEntry(); calendar.setTitle(new PlainTextConstruct(name + "'s Jobs")); calendar.setSummary(new PlainTextConstruct("This calendar contains the jobs " + name + " has volunteered to coordinate for.")); calendar.setTimeZone(new TimeZoneProperty("America/New_York")); calendar.setHidden(HiddenProperty.FALSE); // Insert the calendar URL postUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full"); CalendarEntry newCalendar = null; try { newCalendar = myService.insert(postUrl, calendar); } catch ( ServiceException e2 ) { // TODO Auto-generated catch block System.err.println( "Failed at inserting new calendar." ); e2.printStackTrace(); } catch ( IOException e1 ) { // Retry try { newCalendar = myService.insert(postUrl, calendar); } catch (ServiceException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } // Get the calender's url calUrl = newCalendar.getId(); int splitHere = calUrl.lastIndexOf("/") + 1; calUrl = calUrl.substring(splitHere); //Find events on the calendar with this user's name attached newFeedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full"); myQuery = new CalendarQuery(feedUrl); myQuery.setFullTextQuery(name); resultFeed = null; try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Failed at getting a query." ); e1.printStackTrace(); } catch (IOException e8) { // Retry try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } List<CalendarEventEntry> entries = (List<CalendarEventEntry>)resultFeed.getEntries(); //Add all of those events to the new calendar if (!entries.isEmpty()) { for (CalendarEventEntry singleEntry : entries) { //Get the event's details TextConstruct entryTitle = singleEntry.getTitle(); String entryContent = singleEntry.getPlainTextContent(); When entryTime = singleEntry.getTimes().get(0); DateTime entryStart = entryTime.getStartTime(); DateTime entryEnd = entryTime.getEndTime(); //Date entryStartDate = new Date(start.getValue()); Date entryEndDate = new Date(entryEnd.getValue()); //Determine timezone offset in minutes, depending on whether or not //Daylight Savings Time is in effect if (TZ.inDaylightTime(startDate)) { entryStart.setTzShift(-240); } else { entryStart.setTzShift(-300); } if (TZ.inDaylightTime(entryEndDate)) { entryEnd.setTzShift(-240); } else { entryEnd.setTzShift(-300); } //Create a new entry and add it URL newEntryUrl = new URL( "http://www.google.com/calendar/feeds/" + calUrl + "/private/full"); CalendarEventEntry myEntry = new CalendarEventEntry(); myEntry.setTitle(entryTitle); myEntry.setContent(new PlainTextConstruct(entryContent)); When eventTimes = new When(); eventTimes.setStartTime(entryStart); eventTimes.setEndTime(entryEnd); myEntry.addTime(eventTimes); // Send the request and receive the response: try { myService.insert(newEntryUrl, myEntry); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Error inserting new entry into CalendarService." ); e1.printStackTrace(); } catch ( IOException e1 ) { //Retry try { myService.insert(newEntryUrl, myEntry); } catch (ServiceException e2) { // TODO Auto-generated catch block System.err.println( "Error inserting new entry into CalendarService." ); e2.printStackTrace(); } } } } // Access the Access Control List (ACL) for the calendar Link link = newCalendar.getLink(AclNamespace.LINK_REL_ACCESS_CONTROL_LIST, Link.Type.ATOM); URL aclUrl = new URL( link.getHref() ); AclFeed aclFeed = null; try { aclFeed = myService.getFeed(aclUrl, AclFeed.class); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Failed at getting ACL Feed." ); e1.printStackTrace(); } catch (IOException e8) { // Retry try { aclFeed = myService.getFeed(aclUrl, AclFeed.class); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } // Set the default to "read-only" for all users AclEntry aclEntry = aclFeed.createEntry(); aclEntry.setScope(new AclScope(AclScope.Type.DEFAULT, null)); aclEntry.setRole(CalendarAclRole.READ); // Add it to the ACL try { myService.insert(aclUrl, aclEntry); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Error inserting new entries into ACL." ); e1.printStackTrace(); } catch ( IOException e1 ) { //Retry try { myService.insert(aclUrl, aclEntry); } catch ( ServiceException e2 ) { // TODO Auto-generated catch block System.err.println( "Error inserting new entries into ACL." ); e2.printStackTrace(); } } } //Assign calendar ID to the Volunteer object for the user in question. Volunteer volunteer = null; PersistenceManager persistenceManager = PMF.get().getPersistenceManager(); Transaction tx = persistenceManager.currentTransaction(); try { tx.begin(); Key key = KeyFactory.createKey(Volunteer.class.getSimpleName(), name); volunteer = persistenceManager.getObjectById(Volunteer.class, key); volunteer.setCalendarId( calUrl ); tx.commit(); } catch (Exception e1) { if (tx.isActive()) { tx.rollback(); } } } } } resp.sendRedirect("/calendar.jsp?name=" + name); } }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String date = req.getParameter("date"); String title = req.getParameter("title"); String name = req.getParameter("name"); //If no user in query string, prompt to log in. if (name == null || name.equalsIgnoreCase("null") || name.equals("")) { resp.sendRedirect("/loginredirect?url=" + req.getRequestURI() + "?" + req.getQueryString()); } //Otherwise proceed normally. else { URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full"); //&max-results=10"); CalendarQuery myQuery = new CalendarQuery(feedUrl); myQuery.setStringCustomParameter("orderby", "starttime"); myQuery.setStringCustomParameter("sortorder", "ascending"); myQuery.setStringCustomParameter("futureevents", "true"); myQuery.setStringCustomParameter("singleevents", "true"); //Get a date one day ahead of the event clicked on and make it the max date of the query String datePattern = "MM-dd-yyyy"; SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); DateTime searchMaxDate = null; long searchMaxTime = 0; try { searchMaxDate = new DateTime(dateFormat.parse(date)); searchMaxTime = searchMaxDate.getValue(); searchMaxTime += 86400000; //86400000 milliseconds = 1 day searchMaxDate.setValue(searchMaxTime); } catch (ParseException e6) { // TODO Auto-generated catch block e6.printStackTrace(); } if (searchMaxDate != null) { myQuery.setMaximumStartTime(searchMaxDate); } //Get a date one day before the event clicked on and make it the max date of the query DateTime searchMinDate = null; long searchMinTime = 0; try { searchMinDate = new DateTime(dateFormat.parse(date)); searchMinTime = searchMinDate.getValue(); searchMinTime -= 86400000; //86400000 milliseconds = 1 day searchMinDate.setValue(searchMinTime); } catch (ParseException e6) { // TODO Auto-generated catch block e6.printStackTrace(); } if (searchMinDate != null) { myQuery.setMinimumStartTime(searchMinDate); } CalendarService myService = new CalendarService("Volunteer-Coordinator-Calendar"); try { myService.setUserCredentials("[email protected]", "G0covenant"); } catch (AuthenticationException e) { // TODO Auto-generated catch block System.err.println( "Failed to authenticate service." ); e.printStackTrace(); } // Send the request and receive the response: CalendarEventFeed resultFeed = null; try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch (ServiceException e) { // TODO Auto-generated catch block System.err.println( "Failed to send query." ); e.printStackTrace(); } catch (IOException e) { // Retry try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } List<CalendarEventEntry> results = (List<CalendarEventEntry>)resultFeed.getEntries(); for (CalendarEventEntry entry : results) { // Get the start time for the event When time = entry.getTimes().get(0); DateTime start = time.getStartTime(); DateTime end = time.getEndTime(); PersistenceManager pManager = PMF.get().getPersistenceManager(); Key k = KeyFactory.createKey(Volunteer.class.getSimpleName(), name); Volunteer vol = pManager.getObjectById(Volunteer.class, k); String timeZone = vol.getTimeZone(); //Set time zone to be the time zone of whatever user is volunteering TimeZone TZ = TimeZone.getTimeZone( timeZone ); Date startDate = new Date(start.getValue()); Date endDate = new Date(end.getValue()); //Determine timezone offset in minutes, depending on whether or not //Daylight Savings Time is in effect if (TZ.inDaylightTime(startDate)) { start.setTzShift(-240); } else { start.setTzShift(-300); } if (TZ.inDaylightTime(endDate)) { end.setTzShift(-240); } else { end.setTzShift(-300); } // Convert to milliseconds to get a date object, which can be formatted easier. Date entryDate = new Date(start.getValue() + 1000 * (start.getTzShift() * 60)); String startDay = dateFormat.format(entryDate); String eventTitle = new String(entry.getTitle().getPlainText()); if (startDay.equals(date) && eventTitle.equals(title)) { //Updates the acceptedBy tag to show the username of the acceptor List<ExtendedProperty> propList = entry.getExtendedProperty(); boolean propFound = false; for (ExtendedProperty prop : propList) { if( prop.getName().equals( "acceptedBy" ) ) { propFound = true; prop.setValue( name ); } } if( !propFound ) { ExtendedProperty acceptedBy = new ExtendedProperty(); acceptedBy.setName( "acceptedBy" ); acceptedBy.setValue( name ); entry.addExtendedProperty( acceptedBy ); } URL editUrl = new URL(entry.getEditLink().getHref()); try { myService.update(editUrl, entry); } catch (ServiceException e) { // TODO Auto-generated catch block System.err.println( "Failed to successfully set content." ); e.printStackTrace(); } catch (IOException e) { // Retry try { myService.update(editUrl, entry); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } //Get the ID of this user's calendar from the datastore. String usrCalUrl = vol.getCalendarId(); URL newUrl = new URL("http://www.google.com/calendar/feeds/" + usrCalUrl + "/private/full"); CalendarEventEntry newEvent = null; // If the event is recurring, create a non-recurring clone of the event to add to the user's calendar if (entry.getOriginalEvent() != null) { newEvent = new CalendarEventEntry(); newEvent.setTitle(entry.getTitle()); // Title newEvent.setContent(entry.getContent()); // Description newEvent.addTime( entry.getTimes().get(0) ); // Date/Time for (ExtendedProperty prop : propList) { // Other details ExtendedProperty ep = new ExtendedProperty(); ep.setName( prop.getName() ); ep.setValue( prop.getValue() ); newEvent.addExtendedProperty( ep ); } } else { newEvent = entry; } //If insert is unsuccessful, we look for a way to replace the stored //calendar URL, up to and including making a new calendar. try { try { myService.insert(newUrl, newEvent); } catch (IOException ioe) { //Retry myService.insert(newUrl, newEvent); } } catch ( ServiceException e ) { System.err.println( "Failed to insert into calendar at " + usrCalUrl ); e.printStackTrace(); URL newFeedUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full"); CalendarFeed newResultFeed = null; try { newResultFeed = myService.getFeed(newFeedUrl, CalendarFeed.class); } catch ( ServiceException e3 ) { // TODO Auto-generated catch block System.err.println( "Failed to fetch feed of calendars." ); e3.printStackTrace(); } catch (IOException e4) { // Retry try { newResultFeed = myService.getFeed(newFeedUrl, CalendarFeed.class); } catch (ServiceException e5) { // TODO Auto-generated catch block e5.printStackTrace(); } } String calUrl = null; for( int i = 0; i < newResultFeed.getEntries().size(); i++ ) { CalendarEntry newEntry = newResultFeed.getEntries().get( i ); //String compare is not a great way to do it, //but I'm not sure there is another option. if( newEntry.getTitle().getPlainText().equals( name+"'s Jobs" ) ) { CalendarEntry calendar = newEntry; // Get the calender's url calUrl = calendar.getId(); int splitHere = calUrl.lastIndexOf("/") + 1; calUrl = calUrl.substring(splitHere); break; } } boolean calendarDeleted = false; //Check to see if we can access the calendar calUrl links to. //If we can't, it's assumed to have been deleted, and we proceed to make a new one. if( calUrl != null ) { String nullString = null; try { URL testUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full/" + usrCalUrl); myService.getEntry( testUrl, CalendarEntry.class, nullString ); } catch( Exception e1 ) { System.err.println( "Failed to access calendar at " + calUrl ); calendarDeleted = true; } } //No extant calendars for this user; make a new one. if( calUrl == null || calendarDeleted ) { CalendarEntry calendar = new CalendarEntry(); calendar.setTitle(new PlainTextConstruct(name + "'s Jobs")); calendar.setSummary(new PlainTextConstruct("This calendar contains the jobs " + name + " has volunteered to coordinate for.")); calendar.setTimeZone(new TimeZoneProperty("America/New_York")); calendar.setHidden(HiddenProperty.FALSE); // Insert the calendar URL postUrl = new URL("https://www.google.com/calendar/feeds/default/owncalendars/full"); CalendarEntry newCalendar = null; try { newCalendar = myService.insert(postUrl, calendar); } catch ( ServiceException e2 ) { // TODO Auto-generated catch block System.err.println( "Failed at inserting new calendar." ); e2.printStackTrace(); } catch ( IOException e1 ) { // Retry try { newCalendar = myService.insert(postUrl, calendar); } catch (ServiceException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } // Get the calender's url calUrl = newCalendar.getId(); int splitHere = calUrl.lastIndexOf("/") + 1; calUrl = calUrl.substring(splitHere); //Find events on the calendar with this user's name attached newFeedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full"); myQuery = new CalendarQuery(feedUrl); myQuery.setFullTextQuery(name); resultFeed = null; try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Failed at getting a query." ); e1.printStackTrace(); } catch (IOException e8) { // Retry try { resultFeed = myService.query(myQuery, CalendarEventFeed.class); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } List<CalendarEventEntry> entries = (List<CalendarEventEntry>)resultFeed.getEntries(); //Add all of those events to the new calendar if (!entries.isEmpty()) { for (CalendarEventEntry singleEntry : entries) { //Get the event's details TextConstruct entryTitle = singleEntry.getTitle(); String entryContent = singleEntry.getPlainTextContent(); When entryTime = singleEntry.getTimes().get(0); DateTime entryStart = entryTime.getStartTime(); DateTime entryEnd = entryTime.getEndTime(); //Date entryStartDate = new Date(start.getValue()); Date entryEndDate = new Date(entryEnd.getValue()); //Determine timezone offset in minutes, depending on whether or not //Daylight Savings Time is in effect if (TZ.inDaylightTime(startDate)) { entryStart.setTzShift(-240); } else { entryStart.setTzShift(-300); } if (TZ.inDaylightTime(entryEndDate)) { entryEnd.setTzShift(-240); } else { entryEnd.setTzShift(-300); } //Create a new entry and add it URL newEntryUrl = new URL( "http://www.google.com/calendar/feeds/" + calUrl + "/private/full"); CalendarEventEntry myEntry = new CalendarEventEntry(); myEntry.setTitle(entryTitle); myEntry.setContent(new PlainTextConstruct(entryContent)); When eventTimes = new When(); eventTimes.setStartTime(entryStart); eventTimes.setEndTime(entryEnd); myEntry.addTime(eventTimes); // Send the request and receive the response: try { myService.insert(newEntryUrl, myEntry); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Error inserting new entry into CalendarService." ); e1.printStackTrace(); } catch ( IOException e1 ) { //Retry try { myService.insert(newEntryUrl, myEntry); } catch (ServiceException e2) { // TODO Auto-generated catch block System.err.println( "Error inserting new entry into CalendarService." ); e2.printStackTrace(); } } } } // Access the Access Control List (ACL) for the calendar Link link = newCalendar.getLink(AclNamespace.LINK_REL_ACCESS_CONTROL_LIST, Link.Type.ATOM); URL aclUrl = new URL( link.getHref() ); AclFeed aclFeed = null; try { aclFeed = myService.getFeed(aclUrl, AclFeed.class); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Failed at getting ACL Feed." ); e1.printStackTrace(); } catch (IOException e8) { // Retry try { aclFeed = myService.getFeed(aclUrl, AclFeed.class); } catch (ServiceException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } // Set the default to "read-only" for all users AclEntry aclEntry = aclFeed.createEntry(); aclEntry.setScope(new AclScope(AclScope.Type.DEFAULT, null)); aclEntry.setRole(CalendarAclRole.READ); // Add it to the ACL try { myService.insert(aclUrl, aclEntry); } catch ( ServiceException e1 ) { // TODO Auto-generated catch block System.err.println( "Error inserting new entries into ACL." ); e1.printStackTrace(); } catch ( IOException e1 ) { //Retry try { myService.insert(aclUrl, aclEntry); } catch ( ServiceException e2 ) { // TODO Auto-generated catch block System.err.println( "Error inserting new entries into ACL." ); e2.printStackTrace(); } } } //Assign calendar ID to the Volunteer object for the user in question. Volunteer volunteer = null; PersistenceManager persistenceManager = PMF.get().getPersistenceManager(); Transaction tx = persistenceManager.currentTransaction(); try { tx.begin(); Key key = KeyFactory.createKey(Volunteer.class.getSimpleName(), name); volunteer = persistenceManager.getObjectById(Volunteer.class, key); volunteer.setCalendarId( calUrl ); tx.commit(); } catch (Exception e1) { if (tx.isActive()) { tx.rollback(); } } } } } resp.sendRedirect("/calendar.jsp?name=" + name); } }
diff --git a/src/java/org/lwjgl/opengl/MacOSXFrame.java b/src/java/org/lwjgl/opengl/MacOSXFrame.java index 348cc860..60224957 100644 --- a/src/java/org/lwjgl/opengl/MacOSXFrame.java +++ b/src/java/org/lwjgl/opengl/MacOSXFrame.java @@ -1,201 +1,202 @@ /* * Copyright (c) 2002-2004 LWJGL Project * 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 'LWJGL' 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.lwjgl.opengl; /** * This is the Mac OS X AWT Frame. It contains thread safe * methods to manipulateit from non-AWT threads * @author elias_naur */ import java.awt.BorderLayout; import java.awt.Frame; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import org.lwjgl.LWJGLException; final class MacOSXFrame extends Frame implements WindowListener, ComponentListener { private final MacOSXGLCanvas canvas; private boolean close_requested; /* States */ private Rectangle bounds; private boolean active; private boolean visible; private boolean minimized; private boolean should_warp_cursor; MacOSXFrame(DisplayMode mode, java.awt.DisplayMode requested_mode, boolean fullscreen, int x, int y) throws LWJGLException { setResizable(false); addWindowListener(this); addComponentListener(this); canvas = new MacOSXGLCanvas(); add(canvas, BorderLayout.CENTER); boolean undecorated = Boolean.getBoolean("org.lwjgl.opengl.Window.undecorated"); setUndecorated(fullscreen || undecorated); if ( fullscreen ) { getDevice().setFullScreenWindow(this); getDevice().setDisplayMode(requested_mode); java.awt.DisplayMode real_mode = getDevice().getDisplayMode(); /** For some strange reason, the display mode is sometimes silently capped even though the mode is reported as supported */ if ( requested_mode.getWidth() != real_mode.getWidth() || requested_mode.getHeight() != real_mode.getHeight() ) { getDevice().setFullScreenWindow(null); if (isDisplayable()) dispose(); throw new LWJGLException("AWT capped mode: requested mode = " + requested_mode.getWidth() + "x" + requested_mode.getHeight() + " but got " + real_mode.getWidth() + " " + real_mode.getHeight()); } } pack(); resize(x, y, mode.getWidth(), mode.getHeight()); setVisible(true); requestFocus(); canvas.requestFocus(); canvas.initializeCanvas(); + updateBounds(); } public void resize(int x, int y, int width, int height) { Insets insets = getInsets(); setBounds(x, y, width + insets.left + insets.right, height + insets.top + insets.bottom); } public Rectangle syncGetBounds() { synchronized ( this ) { return bounds; } } public void componentShown(ComponentEvent e) { } public void componentHidden(ComponentEvent e) { } private void updateBounds() { synchronized ( this ) { bounds = getBounds(); } } public void componentResized(ComponentEvent e) { updateBounds(); } public void componentMoved(ComponentEvent e) { updateBounds(); } public static GraphicsDevice getDevice() { GraphicsEnvironment g_env = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice device = g_env.getDefaultScreenDevice(); return device; } public void windowIconified(WindowEvent e) { synchronized ( this ) { minimized = true; } } public void windowDeiconified(WindowEvent e) { synchronized ( this ) { minimized = false; } } public void windowOpened(WindowEvent e) { } public void windowClosed(WindowEvent e) { } public void windowClosing(WindowEvent e) { synchronized ( this ) { close_requested = true; } } public void windowDeactivated(WindowEvent e) { synchronized ( this ) { active = false; } } public void windowActivated(WindowEvent e) { synchronized ( this ) { active = true; should_warp_cursor = true; } } public boolean syncIsCloseRequested() { boolean result; synchronized ( this ) { result = close_requested; close_requested = false; } return result; } public boolean syncIsVisible() { synchronized ( this ) { return !minimized; } } public boolean syncIsActive() { synchronized ( this ) { return active; } } public MacOSXGLCanvas getCanvas() { return canvas; } public boolean syncShouldWarpCursor() { boolean result; synchronized ( this ) { result = should_warp_cursor; should_warp_cursor = false; } return result; } }
true
true
MacOSXFrame(DisplayMode mode, java.awt.DisplayMode requested_mode, boolean fullscreen, int x, int y) throws LWJGLException { setResizable(false); addWindowListener(this); addComponentListener(this); canvas = new MacOSXGLCanvas(); add(canvas, BorderLayout.CENTER); boolean undecorated = Boolean.getBoolean("org.lwjgl.opengl.Window.undecorated"); setUndecorated(fullscreen || undecorated); if ( fullscreen ) { getDevice().setFullScreenWindow(this); getDevice().setDisplayMode(requested_mode); java.awt.DisplayMode real_mode = getDevice().getDisplayMode(); /** For some strange reason, the display mode is sometimes silently capped even though the mode is reported as supported */ if ( requested_mode.getWidth() != real_mode.getWidth() || requested_mode.getHeight() != real_mode.getHeight() ) { getDevice().setFullScreenWindow(null); if (isDisplayable()) dispose(); throw new LWJGLException("AWT capped mode: requested mode = " + requested_mode.getWidth() + "x" + requested_mode.getHeight() + " but got " + real_mode.getWidth() + " " + real_mode.getHeight()); } } pack(); resize(x, y, mode.getWidth(), mode.getHeight()); setVisible(true); requestFocus(); canvas.requestFocus(); canvas.initializeCanvas(); }
MacOSXFrame(DisplayMode mode, java.awt.DisplayMode requested_mode, boolean fullscreen, int x, int y) throws LWJGLException { setResizable(false); addWindowListener(this); addComponentListener(this); canvas = new MacOSXGLCanvas(); add(canvas, BorderLayout.CENTER); boolean undecorated = Boolean.getBoolean("org.lwjgl.opengl.Window.undecorated"); setUndecorated(fullscreen || undecorated); if ( fullscreen ) { getDevice().setFullScreenWindow(this); getDevice().setDisplayMode(requested_mode); java.awt.DisplayMode real_mode = getDevice().getDisplayMode(); /** For some strange reason, the display mode is sometimes silently capped even though the mode is reported as supported */ if ( requested_mode.getWidth() != real_mode.getWidth() || requested_mode.getHeight() != real_mode.getHeight() ) { getDevice().setFullScreenWindow(null); if (isDisplayable()) dispose(); throw new LWJGLException("AWT capped mode: requested mode = " + requested_mode.getWidth() + "x" + requested_mode.getHeight() + " but got " + real_mode.getWidth() + " " + real_mode.getHeight()); } } pack(); resize(x, y, mode.getWidth(), mode.getHeight()); setVisible(true); requestFocus(); canvas.requestFocus(); canvas.initializeCanvas(); updateBounds(); }
diff --git a/crypto/test/src/org/bouncycastle/asn1/test/X509NameTest.java b/crypto/test/src/org/bouncycastle/asn1/test/X509NameTest.java index 60e5862c..c8947479 100644 --- a/crypto/test/src/org/bouncycastle/asn1/test/X509NameTest.java +++ b/crypto/test/src/org/bouncycastle/asn1/test/X509NameTest.java @@ -1,328 +1,328 @@ package org.bouncycastle.asn1.test; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1OutputStream; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.ASN1Set; import org.bouncycastle.asn1.DEREncodable; import org.bouncycastle.asn1.DERGeneralizedTime; import org.bouncycastle.asn1.DERIA5String; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DERPrintableString; import org.bouncycastle.asn1.DERUTF8String; import org.bouncycastle.asn1.x509.X509DefaultEntryConverter; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Hashtable; import java.util.Vector; public class X509NameTest extends SimpleTest { // TODO add rfc compliance test for default encoder. String[] subjects = { "C=AU,ST=Victoria,L=South Melbourne,O=Connect 4 Pty Ltd,OU=Webserver Team,CN=www2.connect4.com.au,[email protected]", "C=AU,ST=Victoria,L=South Melbourne,O=Connect 4 Pty Ltd,OU=Certificate Authority,CN=Connect 4 CA,[email protected]", "C=AU,ST=QLD,CN=SSLeay/rsa test cert", "C=US,O=National Aeronautics and Space Administration,SN=16+CN=Steve Schoch", "[email protected],C=US,OU=Hewlett Packard Company (ISSL),CN=Paul A. Cooke", "O=Sun Microsystems Inc,CN=store.sun.com", "unstructuredAddress=192.168.1.33,unstructuredName=pixfirewall.ciscopix.com,CN=pixfirewall.ciscopix.com" }; public String getName() { return "X509Name"; } private static X509Name fromBytes( byte[] bytes) throws IOException { return X509Name.getInstance(new ASN1InputStream(new ByteArrayInputStream(bytes)).readObject()); } private DEREncodable createEntryValue(DERObjectIdentifier oid, String value) { Hashtable attrs = new Hashtable(); attrs.put(oid, value); X509Name name = new X509Name(attrs); ASN1Sequence seq = (ASN1Sequence)name.getDERObject(); ASN1Set set = (ASN1Set)seq.getObjectAt(0); seq = (ASN1Sequence)set.getObjectAt(0); return seq.getObjectAt(1); } private void testEncodingPrintableString(DERObjectIdentifier oid, String value) { DEREncodable converted = createEntryValue(oid, value); if (!(converted instanceof DERPrintableString)) { fail("encoding for " + oid + " not printable string"); } } private void testEncodingIA5String(DERObjectIdentifier oid, String value) { DEREncodable converted = createEntryValue(oid, value); if (!(converted instanceof DERIA5String)) { fail("encoding for " + oid + " not IA5String"); } } private void testEncodingGeneralizedTime(DERObjectIdentifier oid, String value) { DEREncodable converted = createEntryValue(oid, value); if (!(converted instanceof DERGeneralizedTime)) { fail("encoding for " + oid + " not GeneralizedTime"); } } public void performTest() throws Exception { testEncodingPrintableString(X509Name.C, "AU"); testEncodingPrintableString(X509Name.SERIALNUMBER, "123456"); testEncodingIA5String(X509Name.EmailAddress, "[email protected]"); testEncodingIA5String(X509Name.DC, "test"); testEncodingGeneralizedTime(X509Name.DATE_OF_BIRTH, "20020122122220Z"); // // composite // Hashtable attrs = new Hashtable(); attrs.put(X509Name.C, "AU"); attrs.put(X509Name.O, "The Legion of the Bouncy Castle"); attrs.put(X509Name.L, "Melbourne"); attrs.put(X509Name.ST, "Victoria"); attrs.put(X509Name.E, "[email protected]"); X509Name name1 = new X509Name(attrs); if (!name1.equals(name1)) { fail("Failed same object test"); } X509Name name2 = new X509Name(attrs); if (!name1.equals(name2)) { fail("Failed same name test"); } Vector ord1 = new Vector(); ord1.addElement(X509Name.C); ord1.addElement(X509Name.O); ord1.addElement(X509Name.L); ord1.addElement(X509Name.ST); ord1.addElement(X509Name.E); Vector ord2 = new Vector(); ord2.addElement(X509Name.E); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (!name1.equals(name2)) { fail("Failed reverse name test"); } ord2 = new Vector(); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (name1.equals(name2)) { fail("Failed different name test"); } ord2 = new Vector(); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (name1.equals(name2)) { fail("Failed subset name test"); } // // composite test // byte[] enc = Hex.decode("305e310b300906035504061302415531283026060355040a0c1f546865204c6567696f6e206f662074686520426f756e637920436173746c653125301006035504070c094d656c626f75726e653011060355040b0c0a4173636f742056616c65"); ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(enc)); X509Name n = X509Name.getInstance(aIn.readObject()); if (!n.toString().equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne+OU=Ascot Vale")) { fail("Failed composite to string test"); } n = new X509Name("C=AU, O=The Legion of the Bouncy Castle, L=Melbourne + OU=Ascot Vale"); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(n); byte[] enc2 = bOut.toByteArray(); if (!Arrays.areEqual(enc, enc2)) { fail("Failed composite string to encoding test"); } // // getValues test // Vector v1 = n.getValues(X509Name.O); - if (v1.size() != 1 && v1.elementAt(0).equals("The Legion of the Bouncy Castle")) + if (v1.size() != 1 || !v1.elementAt(0).equals("The Legion of the Bouncy Castle")) { fail("O test failed"); } Vector v2 = n.getValues(X509Name.L); - if (v2.size() != 1 && v2.elementAt(0).equals("Melbourne")) + if (v2.size() != 1 || !v2.elementAt(0).equals("Melbourne")) { fail("L test failed"); } // // general subjects test // for (int i = 0; i != subjects.length; i++) { X509Name name = new X509Name(subjects[i]); bOut = new ByteArrayOutputStream(); aOut = new ASN1OutputStream(bOut); aOut.writeObject(name); aIn = new ASN1InputStream(new ByteArrayInputStream(bOut.toByteArray())); name = X509Name.getInstance(aIn.readObject()); if (!name.toString().equals(subjects[i])) { fail("failed regeneration test " + i); } } // // sort test // X509Name unsorted = new X509Name("SN=BBB + CN=AA"); if (!fromBytes(unsorted.getEncoded()).toString().equals("CN=AA+SN=BBB")) { fail("failed sort test 1"); } unsorted = new X509Name("CN=AA + SN=BBB"); if (!fromBytes(unsorted.getEncoded()).toString().equals("CN=AA+SN=BBB")) { fail("failed sort test 2"); } unsorted = new X509Name("SN=B + CN=AA"); if (!fromBytes(unsorted.getEncoded()).toString().equals("SN=B+CN=AA")) { fail("failed sort test 3"); } unsorted = new X509Name("CN=AA + SN=B"); if (!fromBytes(unsorted.getEncoded()).toString().equals("SN=B+CN=AA")) { fail("failed sort test 4"); } // // this is contrived but it checks sorting of sets with equal elements // unsorted = new X509Name("CN=AA + CN=AA + CN=AA"); // // tagging test - only works if CHOICE implemented // /* ASN1TaggedObject tag = new DERTaggedObject(false, 1, new X509Name("CN=AA")); if (!tag.isExplicit()) { fail("failed to explicitly tag CHOICE object"); } X509Name name = X509Name.getInstance(tag, false); if (!name.equals(new X509Name("CN=AA"))) { fail("failed to recover tagged name"); } */ DERUTF8String testString = new DERUTF8String("The Legion of the Bouncy Castle"); byte[] encodedBytes = testString.getEncoded(); byte[] hexEncodedBytes = Hex.encode(encodedBytes); String hexEncodedString = "#" + new String(hexEncodedBytes); DERUTF8String converted = (DERUTF8String) new X509DefaultEntryConverter().getConvertedValue( X509Name.L , hexEncodedString); if (!converted.equals(testString)) { fail("failed X509DefaultEntryConverter test"); } } public static void main( String[] args) { runTest(new X509NameTest()); } }
false
true
public void performTest() throws Exception { testEncodingPrintableString(X509Name.C, "AU"); testEncodingPrintableString(X509Name.SERIALNUMBER, "123456"); testEncodingIA5String(X509Name.EmailAddress, "[email protected]"); testEncodingIA5String(X509Name.DC, "test"); testEncodingGeneralizedTime(X509Name.DATE_OF_BIRTH, "20020122122220Z"); // // composite // Hashtable attrs = new Hashtable(); attrs.put(X509Name.C, "AU"); attrs.put(X509Name.O, "The Legion of the Bouncy Castle"); attrs.put(X509Name.L, "Melbourne"); attrs.put(X509Name.ST, "Victoria"); attrs.put(X509Name.E, "[email protected]"); X509Name name1 = new X509Name(attrs); if (!name1.equals(name1)) { fail("Failed same object test"); } X509Name name2 = new X509Name(attrs); if (!name1.equals(name2)) { fail("Failed same name test"); } Vector ord1 = new Vector(); ord1.addElement(X509Name.C); ord1.addElement(X509Name.O); ord1.addElement(X509Name.L); ord1.addElement(X509Name.ST); ord1.addElement(X509Name.E); Vector ord2 = new Vector(); ord2.addElement(X509Name.E); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (!name1.equals(name2)) { fail("Failed reverse name test"); } ord2 = new Vector(); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (name1.equals(name2)) { fail("Failed different name test"); } ord2 = new Vector(); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (name1.equals(name2)) { fail("Failed subset name test"); } // // composite test // byte[] enc = Hex.decode("305e310b300906035504061302415531283026060355040a0c1f546865204c6567696f6e206f662074686520426f756e637920436173746c653125301006035504070c094d656c626f75726e653011060355040b0c0a4173636f742056616c65"); ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(enc)); X509Name n = X509Name.getInstance(aIn.readObject()); if (!n.toString().equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne+OU=Ascot Vale")) { fail("Failed composite to string test"); } n = new X509Name("C=AU, O=The Legion of the Bouncy Castle, L=Melbourne + OU=Ascot Vale"); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(n); byte[] enc2 = bOut.toByteArray(); if (!Arrays.areEqual(enc, enc2)) { fail("Failed composite string to encoding test"); } // // getValues test // Vector v1 = n.getValues(X509Name.O); if (v1.size() != 1 && v1.elementAt(0).equals("The Legion of the Bouncy Castle")) { fail("O test failed"); } Vector v2 = n.getValues(X509Name.L); if (v2.size() != 1 && v2.elementAt(0).equals("Melbourne")) { fail("L test failed"); } // // general subjects test // for (int i = 0; i != subjects.length; i++) { X509Name name = new X509Name(subjects[i]); bOut = new ByteArrayOutputStream(); aOut = new ASN1OutputStream(bOut); aOut.writeObject(name); aIn = new ASN1InputStream(new ByteArrayInputStream(bOut.toByteArray())); name = X509Name.getInstance(aIn.readObject()); if (!name.toString().equals(subjects[i])) { fail("failed regeneration test " + i); } } // // sort test // X509Name unsorted = new X509Name("SN=BBB + CN=AA"); if (!fromBytes(unsorted.getEncoded()).toString().equals("CN=AA+SN=BBB")) { fail("failed sort test 1"); } unsorted = new X509Name("CN=AA + SN=BBB"); if (!fromBytes(unsorted.getEncoded()).toString().equals("CN=AA+SN=BBB")) { fail("failed sort test 2"); } unsorted = new X509Name("SN=B + CN=AA"); if (!fromBytes(unsorted.getEncoded()).toString().equals("SN=B+CN=AA")) { fail("failed sort test 3"); } unsorted = new X509Name("CN=AA + SN=B"); if (!fromBytes(unsorted.getEncoded()).toString().equals("SN=B+CN=AA")) { fail("failed sort test 4"); } // // this is contrived but it checks sorting of sets with equal elements // unsorted = new X509Name("CN=AA + CN=AA + CN=AA"); // // tagging test - only works if CHOICE implemented // /* ASN1TaggedObject tag = new DERTaggedObject(false, 1, new X509Name("CN=AA")); if (!tag.isExplicit()) { fail("failed to explicitly tag CHOICE object"); } X509Name name = X509Name.getInstance(tag, false); if (!name.equals(new X509Name("CN=AA"))) { fail("failed to recover tagged name"); } */ DERUTF8String testString = new DERUTF8String("The Legion of the Bouncy Castle"); byte[] encodedBytes = testString.getEncoded(); byte[] hexEncodedBytes = Hex.encode(encodedBytes); String hexEncodedString = "#" + new String(hexEncodedBytes); DERUTF8String converted = (DERUTF8String) new X509DefaultEntryConverter().getConvertedValue( X509Name.L , hexEncodedString); if (!converted.equals(testString)) { fail("failed X509DefaultEntryConverter test"); } }
public void performTest() throws Exception { testEncodingPrintableString(X509Name.C, "AU"); testEncodingPrintableString(X509Name.SERIALNUMBER, "123456"); testEncodingIA5String(X509Name.EmailAddress, "[email protected]"); testEncodingIA5String(X509Name.DC, "test"); testEncodingGeneralizedTime(X509Name.DATE_OF_BIRTH, "20020122122220Z"); // // composite // Hashtable attrs = new Hashtable(); attrs.put(X509Name.C, "AU"); attrs.put(X509Name.O, "The Legion of the Bouncy Castle"); attrs.put(X509Name.L, "Melbourne"); attrs.put(X509Name.ST, "Victoria"); attrs.put(X509Name.E, "[email protected]"); X509Name name1 = new X509Name(attrs); if (!name1.equals(name1)) { fail("Failed same object test"); } X509Name name2 = new X509Name(attrs); if (!name1.equals(name2)) { fail("Failed same name test"); } Vector ord1 = new Vector(); ord1.addElement(X509Name.C); ord1.addElement(X509Name.O); ord1.addElement(X509Name.L); ord1.addElement(X509Name.ST); ord1.addElement(X509Name.E); Vector ord2 = new Vector(); ord2.addElement(X509Name.E); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (!name1.equals(name2)) { fail("Failed reverse name test"); } ord2 = new Vector(); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (name1.equals(name2)) { fail("Failed different name test"); } ord2 = new Vector(); ord2.addElement(X509Name.ST); ord2.addElement(X509Name.L); ord2.addElement(X509Name.O); ord2.addElement(X509Name.C); name1 = new X509Name(ord1, attrs); name2 = new X509Name(ord2, attrs); if (name1.equals(name2)) { fail("Failed subset name test"); } // // composite test // byte[] enc = Hex.decode("305e310b300906035504061302415531283026060355040a0c1f546865204c6567696f6e206f662074686520426f756e637920436173746c653125301006035504070c094d656c626f75726e653011060355040b0c0a4173636f742056616c65"); ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(enc)); X509Name n = X509Name.getInstance(aIn.readObject()); if (!n.toString().equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne+OU=Ascot Vale")) { fail("Failed composite to string test"); } n = new X509Name("C=AU, O=The Legion of the Bouncy Castle, L=Melbourne + OU=Ascot Vale"); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream aOut = new ASN1OutputStream(bOut); aOut.writeObject(n); byte[] enc2 = bOut.toByteArray(); if (!Arrays.areEqual(enc, enc2)) { fail("Failed composite string to encoding test"); } // // getValues test // Vector v1 = n.getValues(X509Name.O); if (v1.size() != 1 || !v1.elementAt(0).equals("The Legion of the Bouncy Castle")) { fail("O test failed"); } Vector v2 = n.getValues(X509Name.L); if (v2.size() != 1 || !v2.elementAt(0).equals("Melbourne")) { fail("L test failed"); } // // general subjects test // for (int i = 0; i != subjects.length; i++) { X509Name name = new X509Name(subjects[i]); bOut = new ByteArrayOutputStream(); aOut = new ASN1OutputStream(bOut); aOut.writeObject(name); aIn = new ASN1InputStream(new ByteArrayInputStream(bOut.toByteArray())); name = X509Name.getInstance(aIn.readObject()); if (!name.toString().equals(subjects[i])) { fail("failed regeneration test " + i); } } // // sort test // X509Name unsorted = new X509Name("SN=BBB + CN=AA"); if (!fromBytes(unsorted.getEncoded()).toString().equals("CN=AA+SN=BBB")) { fail("failed sort test 1"); } unsorted = new X509Name("CN=AA + SN=BBB"); if (!fromBytes(unsorted.getEncoded()).toString().equals("CN=AA+SN=BBB")) { fail("failed sort test 2"); } unsorted = new X509Name("SN=B + CN=AA"); if (!fromBytes(unsorted.getEncoded()).toString().equals("SN=B+CN=AA")) { fail("failed sort test 3"); } unsorted = new X509Name("CN=AA + SN=B"); if (!fromBytes(unsorted.getEncoded()).toString().equals("SN=B+CN=AA")) { fail("failed sort test 4"); } // // this is contrived but it checks sorting of sets with equal elements // unsorted = new X509Name("CN=AA + CN=AA + CN=AA"); // // tagging test - only works if CHOICE implemented // /* ASN1TaggedObject tag = new DERTaggedObject(false, 1, new X509Name("CN=AA")); if (!tag.isExplicit()) { fail("failed to explicitly tag CHOICE object"); } X509Name name = X509Name.getInstance(tag, false); if (!name.equals(new X509Name("CN=AA"))) { fail("failed to recover tagged name"); } */ DERUTF8String testString = new DERUTF8String("The Legion of the Bouncy Castle"); byte[] encodedBytes = testString.getEncoded(); byte[] hexEncodedBytes = Hex.encode(encodedBytes); String hexEncodedString = "#" + new String(hexEncodedBytes); DERUTF8String converted = (DERUTF8String) new X509DefaultEntryConverter().getConvertedValue( X509Name.L , hexEncodedString); if (!converted.equals(testString)) { fail("failed X509DefaultEntryConverter test"); } }
diff --git a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/search/BugzillaSearchPage.java b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/search/BugzillaSearchPage.java index 7fbe60bb6..e391b86ad 100644 --- a/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/search/BugzillaSearchPage.java +++ b/org.eclipse.mylyn.bugzilla.ui/src/org/eclipse/mylyn/internal/bugzilla/ui/search/BugzillaSearchPage.java @@ -1,1814 +1,1814 @@ /******************************************************************************* * Copyright (c) 2003, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.internal.bugzilla.ui.search; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.window.Window; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaCorePlugin; import org.eclipse.mylyn.internal.bugzilla.core.BugzillaRepositoryQuery; import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants; import org.eclipse.mylyn.internal.bugzilla.ui.BugzillaUiPlugin; import org.eclipse.mylyn.internal.bugzilla.ui.editor.KeywordsDialog; import org.eclipse.mylyn.internal.tasks.ui.util.WebBrowserDialog; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylyn.tasks.core.RepositoryStatus; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.core.TaskRepositoryManager; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.tasks.ui.search.AbstractRepositoryQueryPage; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.help.WorkbenchHelpSystem; import org.eclipse.ui.progress.IProgressService; /** * Bugzilla search page * * @author Mik Kersten (hardening of prototype) */ @SuppressWarnings("restriction") public class BugzillaSearchPage extends AbstractRepositoryQueryPage implements Listener { private static final int LABEL_WIDTH = 58; private static final String NUM_DAYS_POSITIVE = "Number of days must be a positive integer. "; private static final String TITLE_BUGZILLA_QUERY = "Bugzilla Query"; private static final int HEIGHT_ATTRIBUTE_COMBO = 70; // protected Combo repositoryCombo = null; private static ArrayList<BugzillaSearchData> previousSummaryPatterns = new ArrayList<BugzillaSearchData>(20); private static ArrayList<BugzillaSearchData> previousEmailPatterns = new ArrayList<BugzillaSearchData>(20); private static ArrayList<BugzillaSearchData> previousEmailPatterns2 = new ArrayList<BugzillaSearchData>(20); private static ArrayList<BugzillaSearchData> previousCommentPatterns = new ArrayList<BugzillaSearchData>(20); private static ArrayList<BugzillaSearchData> previousKeywords = new ArrayList<BugzillaSearchData>(20); private boolean firstTime = true; private IDialogSettings fDialogSettings; private static final String[] patternOperationText = { "all words", "any word", "regexp", "notregexp" }; private static final String[] patternOperationValues = { "allwordssubstr", "anywordssubstr", "regexp", "notregexp" }; private static final String[] emailOperationText = { "substring", "exact", "regexp", "notregexp" }; private static final String[] emailOperationValues = { "substring", "exact", "regexp", "notregexp" }; private static final String[] keywordOperationText = { "all", "any", "none" }; private static final String[] keywordOperationValues = { "allwords", "anywords", "nowords" }; private static final String[] emailRoleValues = { "emailassigned_to1", "emailreporter1", "emailcc1", "emaillongdesc1" }; private static final String[] emailRoleValues2 = { "emailassigned_to2", "emailreporter2", "emailcc2", "emaillongdesc2" }; private BugzillaRepositoryQuery originalQuery = null; protected boolean restoring = false; private boolean restoreQueryOptions = true; protected Combo summaryPattern; protected Combo summaryOperation; protected List product; protected List os; protected List hardware; protected List priority; protected List severity; protected List resolution; protected List status; protected Combo commentOperation; protected Combo commentPattern; protected List component; protected List version; protected List target; protected Combo emailOperation; protected Combo emailOperation2; protected Combo emailPattern; protected Combo emailPattern2; protected Button[] emailButtons; protected Button[] emailButtons2; private Combo keywords; private Combo keywordsOperation; protected Text daysText; // /** File containing saved queries */ // protected static SavedQueryFile input; // /** "Remember query" button */ // protected Button saveButton; // /** "Saved queries..." button */ // protected Button loadButton; // /** Run a remembered query */ // protected boolean rememberedQuery = false; /** Index of the saved query to run */ protected int selIndex; // --------------- Configuration handling -------------- // Dialog store taskId constants protected final static String PAGE_NAME = "BugzillaSearchPage"; //$NON-NLS-1$ private static final String STORE_PRODUCT_ID = PAGE_NAME + ".PRODUCT"; private static final String STORE_COMPONENT_ID = PAGE_NAME + ".COMPONENT"; private static final String STORE_VERSION_ID = PAGE_NAME + ".VERSION"; private static final String STORE_MSTONE_ID = PAGE_NAME + ".MILESTONE"; private static final String STORE_STATUS_ID = PAGE_NAME + ".STATUS"; private static final String STORE_RESOLUTION_ID = PAGE_NAME + ".RESOLUTION"; private static final String STORE_SEVERITY_ID = PAGE_NAME + ".SEVERITY"; private static final String STORE_PRIORITY_ID = PAGE_NAME + ".PRIORITY"; private static final String STORE_HARDWARE_ID = PAGE_NAME + ".HARDWARE"; private static final String STORE_OS_ID = PAGE_NAME + ".OS"; private static final String STORE_SUMMARYMATCH_ID = PAGE_NAME + ".SUMMARYMATCH"; private static final String STORE_COMMENTMATCH_ID = PAGE_NAME + ".COMMENTMATCH"; private static final String STORE_EMAILMATCH_ID = PAGE_NAME + ".EMAILMATCH"; private static final String STORE_EMAIL2MATCH_ID = PAGE_NAME + ".EMAIL2MATCH"; private static final String STORE_EMAILBUTTON_ID = PAGE_NAME + ".EMAILATTR"; private static final String STORE_EMAIL2BUTTON_ID = PAGE_NAME + ".EMAIL2ATTR"; private static final String STORE_SUMMARYTEXT_ID = PAGE_NAME + ".SUMMARYTEXT"; private static final String STORE_COMMENTTEXT_ID = PAGE_NAME + ".COMMENTTEXT"; private static final String STORE_EMAILADDRESS_ID = PAGE_NAME + ".EMAILADDRESS"; private static final String STORE_EMAIL2ADDRESS_ID = PAGE_NAME + ".EMAIL2ADDRESS"; private static final String STORE_KEYWORDS_ID = PAGE_NAME + ".KEYWORDS"; private static final String STORE_KEYWORDSMATCH_ID = PAGE_NAME + ".KEYWORDSMATCH"; // private static final String STORE_REPO_ID = PAGE_NAME + ".REPO"; private SelectionAdapter updateActionSelectionAdapter = new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (isControlCreated()) { setPageComplete(isPageComplete()); } } }; private final class ModifyListenerImplementation implements ModifyListener { public void modifyText(ModifyEvent e) { if (isControlCreated()) { setPageComplete(isPageComplete()); } } } @Override public void setPageComplete(boolean complete) { super.setPageComplete(complete); if (scontainer != null) { scontainer.setPerformActionEnabled(complete); } } private static class BugzillaSearchData { /** Pattern to match on */ String pattern; /** Pattern matching criterion */ int operation; BugzillaSearchData(String pattern, int operation) { this.pattern = pattern; this.operation = operation; } } public BugzillaSearchPage() { super(TITLE_BUGZILLA_QUERY); // setTitle(TITLE); // setDescription(DESCRIPTION); // setPageComplete(false); } public BugzillaSearchPage(TaskRepository repository) { super(TITLE_BUGZILLA_QUERY); this.repository = repository; // setTitle(TITLE); // setDescription(DESCRIPTION); // setImageDescriptor(TaskListImages.BANNER_REPOSITORY); // setPageComplete(false); } public BugzillaSearchPage(TaskRepository repository, BugzillaRepositoryQuery origQuery) { super(TITLE_BUGZILLA_QUERY, origQuery.getSummary()); originalQuery = origQuery; this.repository = repository; setDescription("Select the Bugzilla query parameters. Use the Update Attributes button to retrieve " + "updated values from the repository."); // setTitle(TITLE); // setDescription(DESCRIPTION); // setPageComplete(false); } public void createControl(Composite parent) { readConfiguration(); Composite control = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(1, false); layout.marginHeight = 0; control.setLayout(layout); control.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL)); // if (scontainer == null) { // Not presenting in search pane so want query title // super.createControl(control); // Label lblName = new Label(control, SWT.NONE); // final GridData gridData = new GridData(); // lblName.setLayoutData(gridData); // lblName.setText("Query Title:"); // // title = new Text(control, SWT.BORDER); // title.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); // title.addModifyListener(new ModifyListener() { // public void modifyText(ModifyEvent e) { // setPageComplete(isPageComplete()); // } // }); // } // else { // // if (repository == null) { // // search pane so add repository selection // createRepositoryGroup(control); // } createOptionsGroup(control); createSearchGroup(control); // createSaveQuery(control); // createMaxHits(control); // input = new SavedQueryFile(BugzillaPlugin.getDefault().getStateLocation().toString(), "/queries"); // createUpdate(control); // if (originalQuery != null) { // try { // updateDefaults(originalQuery.getQueryUrl(), String.valueOf(originalQuery.getMaxHits())); // } catch (UnsupportedEncodingException e) { // // ignore // } // } setControl(control); WorkbenchHelpSystem.getInstance().setHelp(control, BugzillaUiPlugin.SEARCH_PAGE_CONTEXT); } protected void createOptionsGroup(Composite control) { GridLayout sashFormLayout = new GridLayout(); sashFormLayout.numColumns = 4; sashFormLayout.marginHeight = 5; sashFormLayout.marginWidth = 5; sashFormLayout.horizontalSpacing = 5; final Composite composite = new Composite(control, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); final GridLayout gridLayout = new GridLayout(); gridLayout.marginBottom = 8; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; gridLayout.numColumns = 4; composite.setLayout(gridLayout); if (!inSearchContainer()) { final Label queryTitleLabel = new Label(composite, SWT.NONE); queryTitleLabel.setText("&Query Title:"); Text queryTitle = new Text(composite, SWT.BORDER); queryTitle.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); if (originalQuery != null) { queryTitle.setText(originalQuery.getSummary()); } queryTitle.addModifyListener(new ModifyListenerImplementation()); title = queryTitle; title.setFocus(); } // Info text Label labelSummary = new Label(composite, SWT.LEFT); labelSummary.setText("&Summary:"); labelSummary.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelSummary.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Pattern combo summaryPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); summaryPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); summaryPattern.addModifyListener(new ModifyListenerImplementation()); summaryPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(summaryPattern, summaryOperation, previousSummaryPatterns); } }); summaryOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); summaryOperation.setItems(patternOperationText); summaryOperation.setText(patternOperationText[0]); summaryOperation.select(0); // Info text Label labelComment = new Label(composite, SWT.LEFT); labelComment.setText("&Comment:"); //labelComment.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Comment pattern combo commentPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); commentPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1)); commentPattern.addModifyListener(new ModifyListenerImplementation()); commentPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(commentPattern, commentOperation, previousCommentPatterns); } }); commentOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); commentOperation.setItems(patternOperationText); commentOperation.setText(patternOperationText[0]); commentOperation.select(0); Label labelEmail = new Label(composite, SWT.LEFT); labelEmail.setText("&Email:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern.addModifyListener(new ModifyListenerImplementation()); emailPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern, emailOperation, previousEmailPatterns); } }); Composite emailComposite = new Composite(composite, SWT.NONE); emailComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout = new GridLayout(); emailLayout.marginWidth = 0; emailLayout.marginHeight = 0; emailLayout.horizontalSpacing = 2; emailLayout.numColumns = 4; emailComposite.setLayout(emailLayout); Button button0 = new Button(emailComposite, SWT.CHECK); button0.setText("owner"); Button button1 = new Button(emailComposite, SWT.CHECK); button1.setText("reporter"); Button button2 = new Button(emailComposite, SWT.CHECK); button2.setText("cc"); Button button3 = new Button(emailComposite, SWT.CHECK); button3.setText("commenter"); emailButtons = new Button[] { button0, button1, button2, button3 }; // operation combo emailOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation.setItems(emailOperationText); emailOperation.setText(emailOperationText[0]); emailOperation.select(0); // Email2 Label labelEmail2 = new Label(composite, SWT.LEFT); - labelEmail2.setText("&Email:"); + labelEmail2.setText("Email &2:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern2 = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern2.addModifyListener(new ModifyListenerImplementation()); emailPattern2.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern2, emailOperation2, previousEmailPatterns2); } }); Composite emailComposite2 = new Composite(composite, SWT.NONE); emailComposite2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout2 = new GridLayout(); emailLayout2.marginWidth = 0; emailLayout2.marginHeight = 0; emailLayout2.horizontalSpacing = 2; emailLayout2.numColumns = 4; emailComposite2.setLayout(emailLayout2); Button e2button0 = new Button(emailComposite2, SWT.CHECK); e2button0.setText("owner"); Button e2button1 = new Button(emailComposite2, SWT.CHECK); e2button1.setText("reporter"); Button e2button2 = new Button(emailComposite2, SWT.CHECK); e2button2.setText("cc"); Button e2button3 = new Button(emailComposite2, SWT.CHECK); e2button3.setText("commenter"); emailButtons2 = new Button[] { e2button0, e2button1, e2button2, e2button3 }; // operation combo emailOperation2 = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation2.setItems(emailOperationText); emailOperation2.setText(emailOperationText[0]); emailOperation2.select(0); ///// Label labelKeywords = new Label(composite, SWT.NONE); labelKeywords.setText("&Keywords:"); labelKeywords.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelKeywords.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Composite keywordsComposite = new Composite(composite, SWT.NONE); keywordsComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1)); GridLayout keywordsLayout = new GridLayout(); keywordsLayout.marginWidth = 0; keywordsLayout.marginHeight = 0; keywordsLayout.numColumns = 3; keywordsComposite.setLayout(keywordsLayout); keywordsOperation = new Combo(keywordsComposite, SWT.READ_ONLY); keywordsOperation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsOperation.setItems(keywordOperationText); keywordsOperation.setText(keywordOperationText[0]); keywordsOperation.select(0); keywords = new Combo(keywordsComposite, SWT.NONE); keywords.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); keywords.addModifyListener(new ModifyListenerImplementation()); keywords.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(keywords, keywordsOperation, previousKeywords); } }); Button keywordsSelectButton = new Button(keywordsComposite, SWT.NONE); keywordsSelectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { KeywordsDialog dialog = new KeywordsDialog(getShell(), keywords.getText(), // Arrays.asList(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_KEYWORDS, // null, repository.getUrl()))); if (dialog.open() == Window.OK) { keywords.setText(dialog.getSelectedKeywordsString()); } } }); keywordsSelectButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsSelectButton.setText("Select..."); SashForm sashForm = new SashForm(control, SWT.VERTICAL); sashForm.setLayout(sashFormLayout); final GridData gd_sashForm = new GridData(SWT.FILL, SWT.FILL, true, true); gd_sashForm.widthHint = 500; sashForm.setLayoutData(gd_sashForm); GridLayout topLayout = new GridLayout(); topLayout.numColumns = 4; SashForm topForm = new SashForm(sashForm, SWT.NONE); GridData topLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); topLayoutData.widthHint = 500; topForm.setLayoutData(topLayoutData); topForm.setLayout(topLayout); GridLayout productLayout = new GridLayout(); productLayout.marginWidth = 0; productLayout.marginHeight = 0; productLayout.horizontalSpacing = 0; Composite productComposite = new Composite(topForm, SWT.NONE); productComposite.setLayout(productLayout); Label productLabel = new Label(productComposite, SWT.LEFT); productLabel.setText("&Product:"); GridData productLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); productLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; product = new List(productComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); product.setLayoutData(productLayoutData); product.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (product.getSelectionIndex() != -1) { String[] selectedProducts = product.getSelection(); updateAttributesFromRepository(repository.getUrl(), selectedProducts, false, false); } else { updateAttributesFromRepository(repository.getUrl(), null, false, false); } if (restoring) { restoring = false; restoreWidgetValues(); } setPageComplete(isPageComplete()); } }); GridLayout componentLayout = new GridLayout(); componentLayout.marginWidth = 0; componentLayout.marginHeight = 0; componentLayout.horizontalSpacing = 0; Composite componentComposite = new Composite(topForm, SWT.NONE); componentComposite.setLayout(componentLayout); Label componentLabel = new Label(componentComposite, SWT.LEFT); componentLabel.setText("Compo&nent:"); component = new List(componentComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData componentLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); componentLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; component.setLayoutData(componentLayoutData); component.addSelectionListener(updateActionSelectionAdapter); Composite versionComposite = new Composite(topForm, SWT.NONE); GridLayout versionLayout = new GridLayout(); versionLayout.marginWidth = 0; versionLayout.marginHeight = 0; versionLayout.horizontalSpacing = 0; versionComposite.setLayout(versionLayout); Label versionLabel = new Label(versionComposite, SWT.LEFT); versionLabel.setText("Vers&ion:"); version = new List(versionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData versionLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); versionLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; version.setLayoutData(versionLayoutData); version.addSelectionListener(updateActionSelectionAdapter); Composite milestoneComposite = new Composite(topForm, SWT.NONE); GridLayout milestoneLayout = new GridLayout(); milestoneLayout.marginWidth = 0; milestoneLayout.marginHeight = 0; milestoneLayout.horizontalSpacing = 0; milestoneComposite.setLayout(milestoneLayout); Label milestoneLabel = new Label(milestoneComposite, SWT.LEFT); milestoneLabel.setText("&Milestone:"); target = new List(milestoneComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData targetLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); targetLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; target.setLayoutData(targetLayoutData); target.addSelectionListener(updateActionSelectionAdapter); SashForm bottomForm = new SashForm(sashForm, SWT.NONE); GridLayout bottomLayout = new GridLayout(); bottomLayout.numColumns = 6; bottomForm.setLayout(bottomLayout); GridData bottomLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1); bottomLayoutData.heightHint = 119; bottomLayoutData.widthHint = 400; bottomForm.setLayoutData(bottomLayoutData); Composite statusComposite = new Composite(bottomForm, SWT.NONE); GridLayout statusLayout = new GridLayout(); statusLayout.marginTop = 7; statusLayout.marginWidth = 0; statusLayout.horizontalSpacing = 0; statusLayout.marginHeight = 0; statusComposite.setLayout(statusLayout); Label statusLabel = new Label(statusComposite, SWT.LEFT); statusLabel.setText("Stat&us:"); status = new List(statusComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_status = new GridData(SWT.FILL, SWT.FILL, true, true); gd_status.heightHint = 60; status.setLayoutData(gd_status); status.addSelectionListener(updateActionSelectionAdapter); Composite resolutionComposite = new Composite(bottomForm, SWT.NONE); GridLayout resolutionLayout = new GridLayout(); resolutionLayout.marginTop = 7; resolutionLayout.marginWidth = 0; resolutionLayout.marginHeight = 0; resolutionLayout.horizontalSpacing = 0; resolutionComposite.setLayout(resolutionLayout); Label resolutionLabel = new Label(resolutionComposite, SWT.LEFT); resolutionLabel.setText("&Resolution:"); resolution = new List(resolutionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_resolution = new GridData(SWT.FILL, SWT.FILL, true, true); gd_resolution.heightHint = 60; resolution.setLayoutData(gd_resolution); resolution.addSelectionListener(updateActionSelectionAdapter); Composite priorityComposite = new Composite(bottomForm, SWT.NONE); GridLayout priorityLayout = new GridLayout(); priorityLayout.marginTop = 7; priorityLayout.marginWidth = 0; priorityLayout.marginHeight = 0; priorityLayout.horizontalSpacing = 0; priorityComposite.setLayout(priorityLayout); Label priorityLabel = new Label(priorityComposite, SWT.LEFT); priorityLabel.setText("Priori&ty:"); priority = new List(priorityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_priority = new GridData(SWT.FILL, SWT.FILL, true, true); gd_priority.heightHint = 60; priority.setLayoutData(gd_priority); priority.addSelectionListener(updateActionSelectionAdapter); Composite severityComposite = new Composite(bottomForm, SWT.NONE); GridLayout severityLayout = new GridLayout(); severityLayout.marginTop = 7; severityLayout.marginWidth = 0; severityLayout.marginHeight = 0; severityLayout.horizontalSpacing = 0; severityComposite.setLayout(severityLayout); Label severityLabel = new Label(severityComposite, SWT.LEFT); severityLabel.setText("Se&verity:"); severity = new List(severityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_severity = new GridData(SWT.FILL, SWT.FILL, true, true); gd_severity.heightHint = 60; severity.setLayoutData(gd_severity); severity.addSelectionListener(updateActionSelectionAdapter); Composite hardwareComposite = new Composite(bottomForm, SWT.NONE); GridLayout hardwareLayout = new GridLayout(); hardwareLayout.marginTop = 7; hardwareLayout.marginWidth = 0; hardwareLayout.marginHeight = 0; hardwareLayout.horizontalSpacing = 0; hardwareComposite.setLayout(hardwareLayout); Label hardwareLabel = new Label(hardwareComposite, SWT.LEFT); hardwareLabel.setText("Hard&ware:"); hardware = new List(hardwareComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_hardware = new GridData(SWT.FILL, SWT.FILL, true, true); gd_hardware.heightHint = 60; hardware.setLayoutData(gd_hardware); hardware.addSelectionListener(updateActionSelectionAdapter); Composite osComposite = new Composite(bottomForm, SWT.NONE); GridLayout osLayout = new GridLayout(); osLayout.marginTop = 7; osLayout.marginWidth = 0; osLayout.marginHeight = 0; osLayout.horizontalSpacing = 0; osComposite.setLayout(osLayout); Label osLabel = new Label(osComposite, SWT.LEFT); osLabel.setText("&Operating System:"); os = new List(osComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_os = new GridData(SWT.FILL, SWT.FILL, true, true); gd_os.heightHint = 60; os.setLayoutData(gd_os); os.addSelectionListener(updateActionSelectionAdapter); bottomForm.setWeights(new int[] { 88, 90, 50, 77, 88, 85 }); } private void createSearchGroup(Composite control) { Composite composite = new Composite(control, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); GridLayout gridLayout = new GridLayout(); gridLayout.marginTop = 7; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; gridLayout.numColumns = 2; composite.setLayout(gridLayout); Label changedInTheLabel = new Label(composite, SWT.LEFT); changedInTheLabel.setLayoutData(new GridData()); changedInTheLabel.setText("Ch&anged in:"); Composite updateComposite = new Composite(composite, SWT.NONE); updateComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); GridLayout updateLayout = new GridLayout(3, false); updateLayout.marginWidth = 0; updateLayout.horizontalSpacing = 0; updateLayout.marginHeight = 0; updateComposite.setLayout(updateLayout); daysText = new Text(updateComposite, SWT.BORDER); daysText.setLayoutData(new GridData(40, SWT.DEFAULT)); daysText.setTextLimit(5); daysText.addListener(SWT.Modify, this); Label label = new Label(updateComposite, SWT.LEFT); label.setText(" days."); Button updateButton = new Button(updateComposite, SWT.PUSH); updateButton.setText("Up&date Attributes from Repository"); updateButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false)); updateButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (repository != null) { updateAttributesFromRepository(repository.getUrl(), null, true, true); } else { MessageDialog.openInformation(Display.getCurrent().getActiveShell(), IBugzillaConstants.TITLE_MESSAGE_DIALOG, TaskRepositoryManager.MESSAGE_NO_REPOSITORY); } } }); } /** * Creates the buttons for remembering a query and accessing previously saved queries. */ protected Control createSaveQuery(Composite control) { GridLayout layout; GridData gd; Group group = new Group(control, SWT.NONE); layout = new GridLayout(3, false); group.setLayout(layout); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); gd = new GridData(GridData.BEGINNING | GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); gd.horizontalSpan = 2; group.setLayoutData(gd); // loadButton = new Button(group, SWT.PUSH | SWT.LEFT); // loadButton.setText("Saved Queries..."); // final BugzillaSearchPage bsp = this; // loadButton.addSelectionListener(new SelectionAdapter() { // // @Override // public void widgetSelected(SelectionEvent event) { // GetQueryDialog qd = new GetQueryDialog(getShell(), "Saved Queries", // input); // if (qd.open() == InputDialog.OK) { // selIndex = qd.getSelected(); // if (selIndex != -1) { // rememberedQuery = true; // performAction(); // bsp.getShell().close(); // } // } // } // }); // loadButton.setEnabled(true); // loadButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); // // saveButton = new Button(group, SWT.PUSH | SWT.LEFT); // saveButton.setText("Remember..."); // saveButton.addSelectionListener(new SelectionAdapter() { // // @Override // public void widgetSelected(SelectionEvent event) { // SaveQueryDialog qd = new SaveQueryDialog(getShell(), "Remember Query"); // if (qd.open() == InputDialog.OK) { // String qName = qd.getText(); // if (qName != null && qName.compareTo("") != 0) { // try { // input.add(getQueryParameters().toString(), qName, summaryPattern.getText()); // } catch (UnsupportedEncodingException e) { // /* // * Do nothing. Every implementation of the Java // * platform is required to support the standard // * charset "UTF-8" // */ // } // } // } // } // }); // saveButton.setEnabled(true); // saveButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING)); return group; } // public static SavedQueryFile getInput() { // return input; // } private void handleWidgetSelected(Combo widget, Combo operation, ArrayList<BugzillaSearchData> history) { if (widget.getSelectionIndex() < 0) return; int index = history.size() - 1 - widget.getSelectionIndex(); BugzillaSearchData patternData = history.get(index); if (patternData == null || !widget.getText().equals(patternData.pattern)) return; widget.setText(patternData.pattern); operation.setText(operation.getItem(patternData.operation)); } // TODO: avoid overriding? public boolean performAction() { if (restoreQueryOptions) { saveState(); } getPatternData(summaryPattern, summaryOperation, previousSummaryPatterns); getPatternData(commentPattern, commentOperation, previousCommentPatterns); getPatternData(emailPattern, emailOperation, previousEmailPatterns); getPatternData(emailPattern2, emailOperation2, previousEmailPatterns2); getPatternData(keywords, keywordsOperation, previousKeywords); String summaryText = summaryPattern.getText(); BugzillaUiPlugin.getDefault().getPreferenceStore().setValue(IBugzillaConstants.MOST_RECENT_QUERY, summaryText); return super.performAction(); } @Override public void setVisible(boolean visible) { if (visible && summaryPattern != null) { if (firstTime) { if (repository == null) { repository = TasksUiPlugin.getRepositoryManager().getDefaultRepository( BugzillaCorePlugin.REPOSITORY_KIND); } // Set<TaskRepository> repositories = TasksUiPlugin.getRepositoryManager().getRepositories(BugzillaCorePlugin.REPOSITORY_KIND); // String[] repositoryUrls = new String[repositories.size()]; // int i = 0; // int indexToSelect = 0; // for (Iterator<TaskRepository> iter = repositories.iterator(); iter.hasNext();) { // TaskRepository currRepsitory = iter.next(); // // if (i == 0 && repository == null) { // // repository = currRepsitory; // // indexToSelect = 0; // // } // if (repository != null && repository.equals(currRepsitory)) { // indexToSelect = i; // } // repositoryUrls[i] = currRepsitory.getUrl(); // i++; // } // IDialogSettings settings = getDialogSettings(); // if (repositoryCombo != null) { // repositoryCombo.setItems(repositoryUrls); // if (repositoryUrls.length == 0) { // MessageDialog.openInformation(Display.getCurrent().getActiveShell(), IBugzillaConstants.TITLE_MESSAGE_DIALOG, // TaskRepositoryManager.MESSAGE_NO_REPOSITORY); // } else { // String selectRepo = settings.get(STORE_REPO_ID); // if (selectRepo != null && repositoryCombo.indexOf(selectRepo) > -1) { // repositoryCombo.setText(selectRepo); // repository = TasksUiPlugin.getRepositoryManager().getRepository( // BugzillaCorePlugin.REPOSITORY_KIND, repositoryCombo.getText()); // if (repository == null) { // repository = TasksUiPlugin.getRepositoryManager().getDefaultRepository( BugzillaCorePlugin.REPOSITORY_KIND); // } // } else { // repositoryCombo.select(indexToSelect); // } // updateAttributesFromRepository(repositoryCombo.getText(), null, false); // } // } firstTime = false; // Set item and text here to prevent page from resizing for (String searchPattern : getPreviousPatterns(previousSummaryPatterns)) { summaryPattern.add(searchPattern); } // summaryPattern.setItems(getPreviousPatterns(previousSummaryPatterns)); for (String comment : getPreviousPatterns(previousCommentPatterns)) { commentPattern.add(comment); } // commentPattern.setItems(getPreviousPatterns(previousCommentPatterns)); for (String email : getPreviousPatterns(previousEmailPatterns)) { emailPattern.add(email); } for (String email : getPreviousPatterns(previousEmailPatterns2)) { emailPattern2.add(email); } // emailPattern.setItems(getPreviousPatterns(previousEmailPatterns)); for (String keyword : getPreviousPatterns(previousKeywords)) { keywords.add(keyword); } // TODO: update status, resolution, severity etc if possible... if (repository != null) { updateAttributesFromRepository(repository.getUrl(), null, false, false); if (product.getItemCount() == 0) { updateAttributesFromRepository(repository.getUrl(), null, true, false); } } if (originalQuery != null) { try { updateDefaults(originalQuery.getUrl()); } catch (UnsupportedEncodingException e) { // ignore } } } /* * hack: we have to select the correct product, then update the * attributes so the component/version/milestone lists have the * proper values, then we can restore all the widget selections. */ if (repository != null) { IDialogSettings settings = getDialogSettings(); String repoId = "." + repository.getUrl(); if (getWizard() == null && restoreQueryOptions && settings.getArray(STORE_PRODUCT_ID + repoId) != null && product != null) { product.setSelection(nonNullArray(settings, STORE_PRODUCT_ID + repoId)); if (product.getSelection().length > 0) { updateAttributesFromRepository(repository.getUrl(), product.getSelection(), false, false); } restoreWidgetValues(); } } setPageComplete(isPageComplete()); if (getWizard() == null) { // TODO: wierd check summaryPattern.setFocus(); } } super.setVisible(visible); } /** * Returns <code>true</code> if at least some parameter is given to query on. */ private boolean canQuery() { if (isControlCreated()) { return product.getSelectionCount() > 0 || component.getSelectionCount() > 0 || version.getSelectionCount() > 0 || target.getSelectionCount() > 0 || status.getSelectionCount() > 0 || resolution.getSelectionCount() > 0 || severity.getSelectionCount() > 0 || priority.getSelectionCount() > 0 || hardware.getSelectionCount() > 0 || os.getSelectionCount() > 0 || summaryPattern.getText().length() > 0 || commentPattern.getText().length() > 0 || emailPattern.getText().length() > 0 || emailPattern2.getText().length() > 0 || keywords.getText().length() > 0; } else { return false; } } @Override public boolean isPageComplete() { return getWizard() == null ? canQuery() : canQuery() && super.isPageComplete(); } /** * Return search pattern data and update search history list. An existing entry will be updated or a new one * created. */ private BugzillaSearchData getPatternData(Combo widget, Combo operation, ArrayList<BugzillaSearchData> previousSearchQueryData) { String pattern = widget.getText(); if (pattern == null || pattern.trim().equals("")) { return null; } BugzillaSearchData match = null; int i = previousSearchQueryData.size() - 1; while (i >= 0) { match = previousSearchQueryData.get(i); if (pattern.equals(match.pattern)) { break; } i--; } if (i >= 0 && match != null) { match.operation = operation.getSelectionIndex(); // remove - will be added last (see below) previousSearchQueryData.remove(match); } else { match = new BugzillaSearchData(widget.getText(), operation.getSelectionIndex()); } previousSearchQueryData.add(match); return match; } /** * Returns an array of previous summary patterns */ private String[] getPreviousPatterns(ArrayList<BugzillaSearchData> patternHistory) { int size = patternHistory.size(); String[] patterns = new String[size]; for (int i = 0; i < size; i++) patterns[i] = (patternHistory.get(size - 1 - i)).pattern; return patterns; } public String getSearchURL(TaskRepository repository) { try { // if (rememberedQuery) { // return getQueryURL(repository, new StringBuffer(input.getQueryParameters(selIndex))); // } else { return getQueryURL(repository, getQueryParameters()); // } } catch (UnsupportedEncodingException e) { // ignore } return ""; } protected String getQueryURL(TaskRepository repository, StringBuffer params) { StringBuffer url = new StringBuffer(getQueryURLStart(repository).toString()); url.append(params); // HACK make sure that the searches come back sorted by priority. This // should be a search option though url.append("&order=Importance"); // url.append(BugzillaRepositoryUtil.contentTypeRDF); return url.toString(); } /** * Creates the bugzilla query URL start. * * Example: https://bugs.eclipse.org/bugs/buglist.cgi? */ private StringBuffer getQueryURLStart(TaskRepository repository) { StringBuffer sb = new StringBuffer(repository.getUrl()); if (sb.charAt(sb.length() - 1) != '/') { sb.append('/'); } sb.append("buglist.cgi?"); return sb; } /** * Goes through the query form and builds up the query parameters. * * Example: short_desc_type=substring&amp;short_desc=bla&amp; ... TODO: The encoding here should match * TaskRepository.getCharacterEncoding() * * @throws UnsupportedEncodingException */ protected StringBuffer getQueryParameters() throws UnsupportedEncodingException { StringBuffer sb = new StringBuffer(); sb.append("short_desc_type="); sb.append(patternOperationValues[summaryOperation.getSelectionIndex()]); sb.append("&short_desc="); sb.append(URLEncoder.encode(summaryPattern.getText(), repository.getCharacterEncoding())); int[] selected = product.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&product="); sb.append(URLEncoder.encode(product.getItem(selected[i]), repository.getCharacterEncoding())); } selected = component.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&component="); sb.append(URLEncoder.encode(component.getItem(selected[i]), repository.getCharacterEncoding())); } selected = version.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&version="); sb.append(URLEncoder.encode(version.getItem(selected[i]), repository.getCharacterEncoding())); } selected = target.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&target_milestone="); sb.append(URLEncoder.encode(target.getItem(selected[i]), repository.getCharacterEncoding())); } sb.append("&long_desc_type="); sb.append(patternOperationValues[commentOperation.getSelectionIndex()]); sb.append("&long_desc="); sb.append(URLEncoder.encode(commentPattern.getText(), repository.getCharacterEncoding())); selected = status.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&bug_status="); sb.append(URLEncoder.encode(status.getItem(selected[i]), repository.getCharacterEncoding())); } selected = resolution.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&resolution="); sb.append(URLEncoder.encode(resolution.getItem(selected[i]), repository.getCharacterEncoding())); } selected = severity.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&bug_severity="); sb.append(URLEncoder.encode(severity.getItem(selected[i]), repository.getCharacterEncoding())); } selected = priority.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&priority="); sb.append(URLEncoder.encode(priority.getItem(selected[i]), repository.getCharacterEncoding())); } selected = hardware.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&ref_platform="); sb.append(URLEncoder.encode(hardware.getItem(selected[i]), repository.getCharacterEncoding())); } selected = os.getSelectionIndices(); for (int i = 0; i < selected.length; i++) { sb.append("&op_sys="); sb.append(URLEncoder.encode(os.getItem(selected[i]), repository.getCharacterEncoding())); } if (emailPattern.getText() != null && !emailPattern.getText().trim().equals("")) { boolean selectionMade = false; for (Button button : emailButtons) { if (button.getSelection()) { selectionMade = true; break; } } if (selectionMade) { for (int i = 0; i < emailButtons.length; i++) { if (emailButtons[i].getSelection()) { sb.append("&"); sb.append(emailRoleValues[i]); sb.append("=1"); } } sb.append("&emailtype1="); sb.append(emailOperationValues[emailOperation.getSelectionIndex()]); sb.append("&email1="); sb.append(URLEncoder.encode(emailPattern.getText(), repository.getCharacterEncoding())); } } if (emailPattern2.getText() != null && !emailPattern2.getText().trim().equals("")) { boolean selectionMade = false; for (Button button : emailButtons2) { if (button.getSelection()) { selectionMade = true; break; } } if (selectionMade) { for (int i = 0; i < emailButtons2.length; i++) { if (emailButtons2[i].getSelection()) { sb.append("&"); sb.append(emailRoleValues2[i]); sb.append("=1"); } } sb.append("&emailtype2="); sb.append(emailOperationValues[emailOperation2.getSelectionIndex()]); sb.append("&email2="); sb.append(URLEncoder.encode(emailPattern2.getText(), repository.getCharacterEncoding())); } } if (daysText.getText() != null && !daysText.getText().equals("")) { try { Integer.parseInt(daysText.getText()); sb.append("&changedin="); sb.append(URLEncoder.encode(daysText.getText(), repository.getCharacterEncoding())); } catch (NumberFormatException ignored) { // this means that the days is not a number, so don't worry } } if (keywords.getText() != null && !keywords.getText().trim().equals("")) { sb.append("&keywords_type="); sb.append(keywordOperationValues[keywordsOperation.getSelectionIndex()]); sb.append("&keywords="); sb.append(URLEncoder.encode(keywords.getText().replace(',', ' '), repository.getCharacterEncoding())); } return sb; } public IDialogSettings getDialogSettings() { IDialogSettings settings = BugzillaUiPlugin.getDefault().getDialogSettings(); fDialogSettings = settings.getSection(PAGE_NAME); if (fDialogSettings == null) fDialogSettings = settings.addNewSection(PAGE_NAME); return fDialogSettings; } /** * Initializes itself from the stored page settings. */ private void readConfiguration() { getDialogSettings(); } private void updateAttributesFromRepository(final String repositoryUrl, String[] selectedProducts, boolean updateAttributes, final boolean userFoced) { // no info, do update but not forced, if still no data force // if user initiated, force update if (updateAttributes) { final AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getRepositoryConnector( repository.getConnectorKind()); IRunnableWithProgress updateRunnable = new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor == null) { monitor = new NullProgressMonitor(); } try { monitor.beginTask("Updating search options...", IProgressMonitor.UNKNOWN); if (userFoced) { connector.updateAttributes(repository, monitor); } BugzillaUiPlugin.updateQueryOptions(repository, monitor); String[] productsList = BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_PRODUCT, null, repositoryUrl); if (productsList == null || productsList.length == 0) { connector.updateAttributes(repository, monitor); BugzillaUiPlugin.updateQueryOptions(repository, monitor); } } catch (final Exception e) { throw new InvocationTargetException(e); /*catch (final CoreException ce) { StatusHandler.displayStatus("Update failed", ce.getStatus()); if (ce.getCause() != null) { StatusHandler.fail(ce.getCause(), ce.getCause().getMessage(), false); }*/ } finally { monitor.done(); } } }; try { // TODO: make cancelable (bug 143011) if (getContainer() != null) { getContainer().run(true, false, updateRunnable); } else { IProgressService service = PlatformUI.getWorkbench().getProgressService(); service.busyCursorWhile(updateRunnable); } } catch (InvocationTargetException e) { Shell shell = null; if (getWizard() != null && getWizard().getContainer() != null) { shell = getWizard().getContainer().getShell(); } if (shell == null && getControl() != null) { shell = getControl().getShell(); } if (e.getCause() instanceof CoreException) { CoreException cause = ((CoreException) e.getCause()); if (cause.getStatus() instanceof RepositoryStatus && ((RepositoryStatus) cause.getStatus()).isHtmlMessage()) { // TOOD: use StatusManager // this.setControlsEnabled(false); // scontainer.setPerformActionEnabled(false); if (shell != null) { shell.setEnabled(false); } WebBrowserDialog dialog = new WebBrowserDialog(shell, "Error updating search options", null, cause.getStatus().getMessage(), NONE, new String[] { IDialogConstants.OK_LABEL }, 0, ((RepositoryStatus) cause.getStatus()).getHtmlMessage()); dialog.setBlockOnOpen(true); dialog.open(); if (shell != null) { shell.setEnabled(true); } return; // this.setPageComplete(this.isPageComplete()); // this.setControlsEnabled(true); } else { StatusHandler.log(new Status(IStatus.ERROR, BugzillaUiPlugin.PLUGIN_ID, cause.getMessage(), cause)); } } MessageDialog.openError(shell, "Error updating search options", "Error was: " + e.getCause().getMessage()); return; } catch (InterruptedException e) { return; } } if (selectedProducts == null) { String[] productsList = BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_PRODUCT, null, repositoryUrl); Arrays.sort(productsList, String.CASE_INSENSITIVE_ORDER); product.setItems(productsList); } String[] componentsList = BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_COMPONENT, selectedProducts, repositoryUrl); Arrays.sort(componentsList, String.CASE_INSENSITIVE_ORDER); component.setItems(componentsList); version.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_VERSION, selectedProducts, repositoryUrl)); target.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_TARGET, selectedProducts, repositoryUrl)); if (selectedProducts == null) { status.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_STATUS, selectedProducts, repositoryUrl)); // status.setSelection(BugzillaRepositoryUtil.getQueryOptions(IBugzillaConstants.VALUSE_STATUS_PRESELECTED, // repositoryUrl)); resolution.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_RESOLUTION, selectedProducts, repositoryUrl)); severity.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_SEVERITY, selectedProducts, repositoryUrl)); priority.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_PRIORITY, selectedProducts, repositoryUrl)); hardware.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_HARDWARE, selectedProducts, repositoryUrl)); os.setItems(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_OS, selectedProducts, repositoryUrl)); } } public TaskRepository getRepository() { return repository; } public void setRepository(TaskRepository repository) { this.repository = repository; } public boolean canFlipToNextPage() { // if (getErrorMessage() != null) // return false; // // return true; return false; } public void handleEvent(Event event) { String message = null; if (event.widget == daysText) { String days = daysText.getText(); if (days.length() > 0) { try { if (Integer.parseInt(days) < 0) { message = NUM_DAYS_POSITIVE + days + " is invalid."; } } catch (NumberFormatException ex) { message = NUM_DAYS_POSITIVE + days + " is invalid."; } } } setPageComplete(message == null); setErrorMessage(message); if (getWizard() != null) { getWizard().getContainer().updateButtons(); } } /** * TODO: get rid of this? */ public void updateDefaults(String startingUrl) throws UnsupportedEncodingException { // String serverName = startingUrl.substring(0, // startingUrl.indexOf("?")); startingUrl = startingUrl.substring(startingUrl.indexOf("?") + 1); String[] options = startingUrl.split("&"); for (String option : options) { String key = option.substring(0, option.indexOf("=")); String value = URLDecoder.decode(option.substring(option.indexOf("=") + 1), repository.getCharacterEncoding()); if (key == null) continue; if (key.equals("short_desc")) { summaryPattern.setText(value); } else if (key.equals("short_desc_type")) { if (value.equals("allwordssubstr")) value = "all words"; else if (value.equals("anywordssubstr")) value = "any word"; int index = 0; for (String item : summaryOperation.getItems()) { if (item.compareTo(value) == 0) break; index++; } if (index < summaryOperation.getItemCount()) { summaryOperation.select(index); } } else if (key.equals("product")) { String[] sel = product.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; product.setSelection(selList.toArray(sel)); updateAttributesFromRepository(repository.getUrl(), selList.toArray(sel), false, false); } else if (key.equals("component")) { String[] sel = component.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; component.setSelection(selList.toArray(sel)); } else if (key.equals("version")) { String[] sel = version.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; version.setSelection(selList.toArray(sel)); } else if (key.equals("target_milestone")) { // XXX String[] sel = target.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; target.setSelection(selList.toArray(sel)); } else if (key.equals("version")) { String[] sel = version.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; version.setSelection(selList.toArray(sel)); } else if (key.equals("long_desc_type")) { if (value.equals("allwordssubstr")) value = "all words"; else if (value.equals("anywordssubstr")) value = "any word"; int index = 0; for (String item : commentOperation.getItems()) { if (item.compareTo(value) == 0) break; index++; } if (index < commentOperation.getItemCount()) { commentOperation.select(index); } } else if (key.equals("long_desc")) { commentPattern.setText(value); } else if (key.equals("bug_status")) { String[] sel = status.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; status.setSelection(selList.toArray(sel)); } else if (key.equals("resolution")) { String[] sel = resolution.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; resolution.setSelection(selList.toArray(sel)); } else if (key.equals("bug_severity")) { String[] sel = severity.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; severity.setSelection(selList.toArray(sel)); } else if (key.equals("priority")) { String[] sel = priority.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; priority.setSelection(selList.toArray(sel)); } else if (key.equals("ref_platform")) { String[] sel = hardware.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; hardware.setSelection(selList.toArray(sel)); } else if (key.equals("op_sys")) { String[] sel = os.getSelection(); java.util.List<String> selList = Arrays.asList(sel); selList = new ArrayList<String>(selList); selList.add(value); sel = new String[selList.size()]; os.setSelection(selList.toArray(sel)); } else if (key.equals("emailassigned_to1")) { // HACK: email // buttons // assumed to be // in same // position if (value.equals("1")) emailButtons[0].setSelection(true); else emailButtons[0].setSelection(false); } else if (key.equals("emailreporter1")) { // HACK: email // buttons assumed // to be in same // position if (value.equals("1")) emailButtons[1].setSelection(true); else emailButtons[1].setSelection(false); } else if (key.equals("emailcc1")) { // HACK: email buttons // assumed to be in same // position if (value.equals("1")) emailButtons[2].setSelection(true); else emailButtons[2].setSelection(false); } else if (key.equals("emaillongdesc1")) { // HACK: email // buttons assumed // to be in same // position if (value.equals("1")) emailButtons[3].setSelection(true); else emailButtons[3].setSelection(false); } else if (key.equals("emailtype1")) { int index = 0; for (String item : emailOperation.getItems()) { if (item.compareTo(value) == 0) break; index++; } if (index < emailOperation.getItemCount()) { emailOperation.select(index); } } else if (key.equals("email1")) { emailPattern.setText(value); } else if (key.equals("emailassigned_to2")) { // HACK: email // buttons // assumed to be // in same // position if (value.equals("1")) emailButtons2[0].setSelection(true); else emailButtons2[0].setSelection(false); } else if (key.equals("emailreporter2")) { // HACK: email // buttons assumed // to be in same // position if (value.equals("1")) emailButtons2[1].setSelection(true); else emailButtons2[1].setSelection(false); } else if (key.equals("emailcc2")) { // HACK: email buttons // assumed to be in same // position if (value.equals("1")) emailButtons2[2].setSelection(true); else emailButtons2[2].setSelection(false); } else if (key.equals("emaillongdesc2")) { // HACK: email // buttons assumed // to be in same // position if (value.equals("1")) emailButtons2[3].setSelection(true); else emailButtons2[3].setSelection(false); } else if (key.equals("emailtype2")) { int index = 0; for (String item : emailOperation2.getItems()) { if (item.compareTo(value) == 0) break; index++; } if (index < emailOperation2.getItemCount()) { emailOperation2.select(index); } } else if (key.equals("email2")) { emailPattern2.setText(value); } else if (key.equals("changedin")) { daysText.setText(value); } else if (key.equals("keywords")) { keywords.setText(value.replace(' ', ',')); } else if (key.equals("keywords_type")) { int index = 0; for (String item : keywordOperationValues) { if (item.equals(value)) { keywordsOperation.select(index); break; } index++; } } } } @Override public BugzillaRepositoryQuery getQuery() { if (originalQuery == null) { try { originalQuery = new BugzillaRepositoryQuery(repository.getUrl(), getQueryURL(repository, getQueryParameters()), getQueryTitle()); } catch (UnsupportedEncodingException e) { return null; } } else { try { originalQuery.setUrl(getQueryURL(repository, getQueryParameters())); // originalQuery.setMaxHits(Integer.parseInt(getMaxHits())); originalQuery.setHandleIdentifier(getQueryTitle()); } catch (UnsupportedEncodingException e) { return null; } } return originalQuery; } private String[] nonNullArray(IDialogSettings settings, String id) { String[] value = settings.getArray(id); if (value == null) { return new String[] {}; } return value; } private void restoreWidgetValues() { try { IDialogSettings settings = getDialogSettings(); String repoId = "." + repository.getUrl(); if (!restoreQueryOptions || settings.getArray(STORE_PRODUCT_ID + repoId) == null || product == null) { return; } // set widgets to stored values product.setSelection(nonNullArray(settings, STORE_PRODUCT_ID + repoId)); component.setSelection(nonNullArray(settings, STORE_COMPONENT_ID + repoId)); version.setSelection(nonNullArray(settings, STORE_VERSION_ID + repoId)); target.setSelection(nonNullArray(settings, STORE_MSTONE_ID + repoId)); status.setSelection(nonNullArray(settings, STORE_STATUS_ID + repoId)); resolution.setSelection(nonNullArray(settings, STORE_RESOLUTION_ID + repoId)); severity.setSelection(nonNullArray(settings, STORE_SEVERITY_ID + repoId)); priority.setSelection(nonNullArray(settings, STORE_PRIORITY_ID + repoId)); hardware.setSelection(nonNullArray(settings, STORE_HARDWARE_ID + repoId)); os.setSelection(nonNullArray(settings, STORE_OS_ID + repoId)); summaryOperation.select(settings.getInt(STORE_SUMMARYMATCH_ID + repoId)); commentOperation.select(settings.getInt(STORE_COMMENTMATCH_ID + repoId)); emailOperation.select(settings.getInt(STORE_EMAILMATCH_ID + repoId)); for (int i = 0; i < emailButtons.length; i++) { emailButtons[i].setSelection(settings.getBoolean(STORE_EMAILBUTTON_ID + i + repoId)); } summaryPattern.setText(settings.get(STORE_SUMMARYTEXT_ID + repoId)); commentPattern.setText(settings.get(STORE_COMMENTTEXT_ID + repoId)); emailPattern.setText(settings.get(STORE_EMAILADDRESS_ID + repoId)); try { emailOperation2.select(settings.getInt(STORE_EMAIL2MATCH_ID + repoId)); } catch (Exception e) { //ignore } for (int i = 0; i < emailButtons2.length; i++) { emailButtons2[i].setSelection(settings.getBoolean(STORE_EMAIL2BUTTON_ID + i + repoId)); } emailPattern2.setText(settings.get(STORE_EMAIL2ADDRESS_ID + repoId)); if (settings.get(STORE_KEYWORDS_ID + repoId) != null) { keywords.setText(settings.get(STORE_KEYWORDS_ID + repoId)); keywordsOperation.select(settings.getInt(STORE_KEYWORDSMATCH_ID + repoId)); } } catch (IllegalArgumentException e) { //ignore } } public void saveState() { String repoId = "." + repository.getUrl(); IDialogSettings settings = getDialogSettings(); settings.put(STORE_PRODUCT_ID + repoId, product.getSelection()); settings.put(STORE_COMPONENT_ID + repoId, component.getSelection()); settings.put(STORE_VERSION_ID + repoId, version.getSelection()); settings.put(STORE_MSTONE_ID + repoId, target.getSelection()); settings.put(STORE_STATUS_ID + repoId, status.getSelection()); settings.put(STORE_RESOLUTION_ID + repoId, resolution.getSelection()); settings.put(STORE_SEVERITY_ID + repoId, severity.getSelection()); settings.put(STORE_PRIORITY_ID + repoId, priority.getSelection()); settings.put(STORE_HARDWARE_ID + repoId, hardware.getSelection()); settings.put(STORE_OS_ID + repoId, os.getSelection()); settings.put(STORE_SUMMARYMATCH_ID + repoId, summaryOperation.getSelectionIndex()); settings.put(STORE_COMMENTMATCH_ID + repoId, commentOperation.getSelectionIndex()); settings.put(STORE_EMAILMATCH_ID + repoId, emailOperation.getSelectionIndex()); for (int i = 0; i < emailButtons.length; i++) { settings.put(STORE_EMAILBUTTON_ID + i + repoId, emailButtons[i].getSelection()); } settings.put(STORE_SUMMARYTEXT_ID + repoId, summaryPattern.getText()); settings.put(STORE_COMMENTTEXT_ID + repoId, commentPattern.getText()); settings.put(STORE_EMAILADDRESS_ID + repoId, emailPattern.getText()); settings.put(STORE_EMAIL2ADDRESS_ID + repoId, emailPattern2.getText()); settings.put(STORE_EMAIL2MATCH_ID + repoId, emailOperation2.getSelectionIndex()); for (int i = 0; i < emailButtons2.length; i++) { settings.put(STORE_EMAIL2BUTTON_ID + i + repoId, emailButtons2[i].getSelection()); } settings.put(STORE_KEYWORDS_ID + repoId, keywords.getText()); settings.put(STORE_KEYWORDSMATCH_ID + repoId, keywordsOperation.getSelectionIndex()); // settings.put(STORE_REPO_ID, repositoryCombo.getText()); } /* Testing hook to see if any products are present */ public int getProductCount() throws Exception { return product.getItemCount(); } public boolean isRestoreQueryOptions() { return restoreQueryOptions; } public void setRestoreQueryOptions(boolean restoreQueryOptions) { this.restoreQueryOptions = restoreQueryOptions; } }
true
true
protected void createOptionsGroup(Composite control) { GridLayout sashFormLayout = new GridLayout(); sashFormLayout.numColumns = 4; sashFormLayout.marginHeight = 5; sashFormLayout.marginWidth = 5; sashFormLayout.horizontalSpacing = 5; final Composite composite = new Composite(control, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); final GridLayout gridLayout = new GridLayout(); gridLayout.marginBottom = 8; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; gridLayout.numColumns = 4; composite.setLayout(gridLayout); if (!inSearchContainer()) { final Label queryTitleLabel = new Label(composite, SWT.NONE); queryTitleLabel.setText("&Query Title:"); Text queryTitle = new Text(composite, SWT.BORDER); queryTitle.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); if (originalQuery != null) { queryTitle.setText(originalQuery.getSummary()); } queryTitle.addModifyListener(new ModifyListenerImplementation()); title = queryTitle; title.setFocus(); } // Info text Label labelSummary = new Label(composite, SWT.LEFT); labelSummary.setText("&Summary:"); labelSummary.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelSummary.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Pattern combo summaryPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); summaryPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); summaryPattern.addModifyListener(new ModifyListenerImplementation()); summaryPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(summaryPattern, summaryOperation, previousSummaryPatterns); } }); summaryOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); summaryOperation.setItems(patternOperationText); summaryOperation.setText(patternOperationText[0]); summaryOperation.select(0); // Info text Label labelComment = new Label(composite, SWT.LEFT); labelComment.setText("&Comment:"); //labelComment.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Comment pattern combo commentPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); commentPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1)); commentPattern.addModifyListener(new ModifyListenerImplementation()); commentPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(commentPattern, commentOperation, previousCommentPatterns); } }); commentOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); commentOperation.setItems(patternOperationText); commentOperation.setText(patternOperationText[0]); commentOperation.select(0); Label labelEmail = new Label(composite, SWT.LEFT); labelEmail.setText("&Email:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern.addModifyListener(new ModifyListenerImplementation()); emailPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern, emailOperation, previousEmailPatterns); } }); Composite emailComposite = new Composite(composite, SWT.NONE); emailComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout = new GridLayout(); emailLayout.marginWidth = 0; emailLayout.marginHeight = 0; emailLayout.horizontalSpacing = 2; emailLayout.numColumns = 4; emailComposite.setLayout(emailLayout); Button button0 = new Button(emailComposite, SWT.CHECK); button0.setText("owner"); Button button1 = new Button(emailComposite, SWT.CHECK); button1.setText("reporter"); Button button2 = new Button(emailComposite, SWT.CHECK); button2.setText("cc"); Button button3 = new Button(emailComposite, SWT.CHECK); button3.setText("commenter"); emailButtons = new Button[] { button0, button1, button2, button3 }; // operation combo emailOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation.setItems(emailOperationText); emailOperation.setText(emailOperationText[0]); emailOperation.select(0); // Email2 Label labelEmail2 = new Label(composite, SWT.LEFT); labelEmail2.setText("&Email:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern2 = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern2.addModifyListener(new ModifyListenerImplementation()); emailPattern2.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern2, emailOperation2, previousEmailPatterns2); } }); Composite emailComposite2 = new Composite(composite, SWT.NONE); emailComposite2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout2 = new GridLayout(); emailLayout2.marginWidth = 0; emailLayout2.marginHeight = 0; emailLayout2.horizontalSpacing = 2; emailLayout2.numColumns = 4; emailComposite2.setLayout(emailLayout2); Button e2button0 = new Button(emailComposite2, SWT.CHECK); e2button0.setText("owner"); Button e2button1 = new Button(emailComposite2, SWT.CHECK); e2button1.setText("reporter"); Button e2button2 = new Button(emailComposite2, SWT.CHECK); e2button2.setText("cc"); Button e2button3 = new Button(emailComposite2, SWT.CHECK); e2button3.setText("commenter"); emailButtons2 = new Button[] { e2button0, e2button1, e2button2, e2button3 }; // operation combo emailOperation2 = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation2.setItems(emailOperationText); emailOperation2.setText(emailOperationText[0]); emailOperation2.select(0); ///// Label labelKeywords = new Label(composite, SWT.NONE); labelKeywords.setText("&Keywords:"); labelKeywords.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelKeywords.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Composite keywordsComposite = new Composite(composite, SWT.NONE); keywordsComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1)); GridLayout keywordsLayout = new GridLayout(); keywordsLayout.marginWidth = 0; keywordsLayout.marginHeight = 0; keywordsLayout.numColumns = 3; keywordsComposite.setLayout(keywordsLayout); keywordsOperation = new Combo(keywordsComposite, SWT.READ_ONLY); keywordsOperation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsOperation.setItems(keywordOperationText); keywordsOperation.setText(keywordOperationText[0]); keywordsOperation.select(0); keywords = new Combo(keywordsComposite, SWT.NONE); keywords.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); keywords.addModifyListener(new ModifyListenerImplementation()); keywords.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(keywords, keywordsOperation, previousKeywords); } }); Button keywordsSelectButton = new Button(keywordsComposite, SWT.NONE); keywordsSelectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { KeywordsDialog dialog = new KeywordsDialog(getShell(), keywords.getText(), // Arrays.asList(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_KEYWORDS, // null, repository.getUrl()))); if (dialog.open() == Window.OK) { keywords.setText(dialog.getSelectedKeywordsString()); } } }); keywordsSelectButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsSelectButton.setText("Select..."); SashForm sashForm = new SashForm(control, SWT.VERTICAL); sashForm.setLayout(sashFormLayout); final GridData gd_sashForm = new GridData(SWT.FILL, SWT.FILL, true, true); gd_sashForm.widthHint = 500; sashForm.setLayoutData(gd_sashForm); GridLayout topLayout = new GridLayout(); topLayout.numColumns = 4; SashForm topForm = new SashForm(sashForm, SWT.NONE); GridData topLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); topLayoutData.widthHint = 500; topForm.setLayoutData(topLayoutData); topForm.setLayout(topLayout); GridLayout productLayout = new GridLayout(); productLayout.marginWidth = 0; productLayout.marginHeight = 0; productLayout.horizontalSpacing = 0; Composite productComposite = new Composite(topForm, SWT.NONE); productComposite.setLayout(productLayout); Label productLabel = new Label(productComposite, SWT.LEFT); productLabel.setText("&Product:"); GridData productLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); productLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; product = new List(productComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); product.setLayoutData(productLayoutData); product.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (product.getSelectionIndex() != -1) { String[] selectedProducts = product.getSelection(); updateAttributesFromRepository(repository.getUrl(), selectedProducts, false, false); } else { updateAttributesFromRepository(repository.getUrl(), null, false, false); } if (restoring) { restoring = false; restoreWidgetValues(); } setPageComplete(isPageComplete()); } }); GridLayout componentLayout = new GridLayout(); componentLayout.marginWidth = 0; componentLayout.marginHeight = 0; componentLayout.horizontalSpacing = 0; Composite componentComposite = new Composite(topForm, SWT.NONE); componentComposite.setLayout(componentLayout); Label componentLabel = new Label(componentComposite, SWT.LEFT); componentLabel.setText("Compo&nent:"); component = new List(componentComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData componentLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); componentLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; component.setLayoutData(componentLayoutData); component.addSelectionListener(updateActionSelectionAdapter); Composite versionComposite = new Composite(topForm, SWT.NONE); GridLayout versionLayout = new GridLayout(); versionLayout.marginWidth = 0; versionLayout.marginHeight = 0; versionLayout.horizontalSpacing = 0; versionComposite.setLayout(versionLayout); Label versionLabel = new Label(versionComposite, SWT.LEFT); versionLabel.setText("Vers&ion:"); version = new List(versionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData versionLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); versionLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; version.setLayoutData(versionLayoutData); version.addSelectionListener(updateActionSelectionAdapter); Composite milestoneComposite = new Composite(topForm, SWT.NONE); GridLayout milestoneLayout = new GridLayout(); milestoneLayout.marginWidth = 0; milestoneLayout.marginHeight = 0; milestoneLayout.horizontalSpacing = 0; milestoneComposite.setLayout(milestoneLayout); Label milestoneLabel = new Label(milestoneComposite, SWT.LEFT); milestoneLabel.setText("&Milestone:"); target = new List(milestoneComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData targetLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); targetLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; target.setLayoutData(targetLayoutData); target.addSelectionListener(updateActionSelectionAdapter); SashForm bottomForm = new SashForm(sashForm, SWT.NONE); GridLayout bottomLayout = new GridLayout(); bottomLayout.numColumns = 6; bottomForm.setLayout(bottomLayout); GridData bottomLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1); bottomLayoutData.heightHint = 119; bottomLayoutData.widthHint = 400; bottomForm.setLayoutData(bottomLayoutData); Composite statusComposite = new Composite(bottomForm, SWT.NONE); GridLayout statusLayout = new GridLayout(); statusLayout.marginTop = 7; statusLayout.marginWidth = 0; statusLayout.horizontalSpacing = 0; statusLayout.marginHeight = 0; statusComposite.setLayout(statusLayout); Label statusLabel = new Label(statusComposite, SWT.LEFT); statusLabel.setText("Stat&us:"); status = new List(statusComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_status = new GridData(SWT.FILL, SWT.FILL, true, true); gd_status.heightHint = 60; status.setLayoutData(gd_status); status.addSelectionListener(updateActionSelectionAdapter); Composite resolutionComposite = new Composite(bottomForm, SWT.NONE); GridLayout resolutionLayout = new GridLayout(); resolutionLayout.marginTop = 7; resolutionLayout.marginWidth = 0; resolutionLayout.marginHeight = 0; resolutionLayout.horizontalSpacing = 0; resolutionComposite.setLayout(resolutionLayout); Label resolutionLabel = new Label(resolutionComposite, SWT.LEFT); resolutionLabel.setText("&Resolution:"); resolution = new List(resolutionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_resolution = new GridData(SWT.FILL, SWT.FILL, true, true); gd_resolution.heightHint = 60; resolution.setLayoutData(gd_resolution); resolution.addSelectionListener(updateActionSelectionAdapter); Composite priorityComposite = new Composite(bottomForm, SWT.NONE); GridLayout priorityLayout = new GridLayout(); priorityLayout.marginTop = 7; priorityLayout.marginWidth = 0; priorityLayout.marginHeight = 0; priorityLayout.horizontalSpacing = 0; priorityComposite.setLayout(priorityLayout); Label priorityLabel = new Label(priorityComposite, SWT.LEFT); priorityLabel.setText("Priori&ty:"); priority = new List(priorityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_priority = new GridData(SWT.FILL, SWT.FILL, true, true); gd_priority.heightHint = 60; priority.setLayoutData(gd_priority); priority.addSelectionListener(updateActionSelectionAdapter); Composite severityComposite = new Composite(bottomForm, SWT.NONE); GridLayout severityLayout = new GridLayout(); severityLayout.marginTop = 7; severityLayout.marginWidth = 0; severityLayout.marginHeight = 0; severityLayout.horizontalSpacing = 0; severityComposite.setLayout(severityLayout); Label severityLabel = new Label(severityComposite, SWT.LEFT); severityLabel.setText("Se&verity:"); severity = new List(severityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_severity = new GridData(SWT.FILL, SWT.FILL, true, true); gd_severity.heightHint = 60; severity.setLayoutData(gd_severity); severity.addSelectionListener(updateActionSelectionAdapter); Composite hardwareComposite = new Composite(bottomForm, SWT.NONE); GridLayout hardwareLayout = new GridLayout(); hardwareLayout.marginTop = 7; hardwareLayout.marginWidth = 0; hardwareLayout.marginHeight = 0; hardwareLayout.horizontalSpacing = 0; hardwareComposite.setLayout(hardwareLayout); Label hardwareLabel = new Label(hardwareComposite, SWT.LEFT); hardwareLabel.setText("Hard&ware:"); hardware = new List(hardwareComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_hardware = new GridData(SWT.FILL, SWT.FILL, true, true); gd_hardware.heightHint = 60; hardware.setLayoutData(gd_hardware); hardware.addSelectionListener(updateActionSelectionAdapter); Composite osComposite = new Composite(bottomForm, SWT.NONE); GridLayout osLayout = new GridLayout(); osLayout.marginTop = 7; osLayout.marginWidth = 0; osLayout.marginHeight = 0; osLayout.horizontalSpacing = 0; osComposite.setLayout(osLayout); Label osLabel = new Label(osComposite, SWT.LEFT); osLabel.setText("&Operating System:"); os = new List(osComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_os = new GridData(SWT.FILL, SWT.FILL, true, true); gd_os.heightHint = 60; os.setLayoutData(gd_os); os.addSelectionListener(updateActionSelectionAdapter); bottomForm.setWeights(new int[] { 88, 90, 50, 77, 88, 85 }); }
protected void createOptionsGroup(Composite control) { GridLayout sashFormLayout = new GridLayout(); sashFormLayout.numColumns = 4; sashFormLayout.marginHeight = 5; sashFormLayout.marginWidth = 5; sashFormLayout.horizontalSpacing = 5; final Composite composite = new Composite(control, SWT.NONE); composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); final GridLayout gridLayout = new GridLayout(); gridLayout.marginBottom = 8; gridLayout.marginHeight = 0; gridLayout.marginWidth = 0; gridLayout.numColumns = 4; composite.setLayout(gridLayout); if (!inSearchContainer()) { final Label queryTitleLabel = new Label(composite, SWT.NONE); queryTitleLabel.setText("&Query Title:"); Text queryTitle = new Text(composite, SWT.BORDER); queryTitle.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 3, 1)); if (originalQuery != null) { queryTitle.setText(originalQuery.getSummary()); } queryTitle.addModifyListener(new ModifyListenerImplementation()); title = queryTitle; title.setFocus(); } // Info text Label labelSummary = new Label(composite, SWT.LEFT); labelSummary.setText("&Summary:"); labelSummary.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelSummary.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Pattern combo summaryPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); summaryPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); summaryPattern.addModifyListener(new ModifyListenerImplementation()); summaryPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(summaryPattern, summaryOperation, previousSummaryPatterns); } }); summaryOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); summaryOperation.setItems(patternOperationText); summaryOperation.setText(patternOperationText[0]); summaryOperation.select(0); // Info text Label labelComment = new Label(composite, SWT.LEFT); labelComment.setText("&Comment:"); //labelComment.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // Comment pattern combo commentPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); commentPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1)); commentPattern.addModifyListener(new ModifyListenerImplementation()); commentPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(commentPattern, commentOperation, previousCommentPatterns); } }); commentOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); commentOperation.setItems(patternOperationText); commentOperation.setText(patternOperationText[0]); commentOperation.select(0); Label labelEmail = new Label(composite, SWT.LEFT); labelEmail.setText("&Email:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern.addModifyListener(new ModifyListenerImplementation()); emailPattern.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern, emailOperation, previousEmailPatterns); } }); Composite emailComposite = new Composite(composite, SWT.NONE); emailComposite.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout = new GridLayout(); emailLayout.marginWidth = 0; emailLayout.marginHeight = 0; emailLayout.horizontalSpacing = 2; emailLayout.numColumns = 4; emailComposite.setLayout(emailLayout); Button button0 = new Button(emailComposite, SWT.CHECK); button0.setText("owner"); Button button1 = new Button(emailComposite, SWT.CHECK); button1.setText("reporter"); Button button2 = new Button(emailComposite, SWT.CHECK); button2.setText("cc"); Button button3 = new Button(emailComposite, SWT.CHECK); button3.setText("commenter"); emailButtons = new Button[] { button0, button1, button2, button3 }; // operation combo emailOperation = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation.setItems(emailOperationText); emailOperation.setText(emailOperationText[0]); emailOperation.select(0); // Email2 Label labelEmail2 = new Label(composite, SWT.LEFT); labelEmail2.setText("Email &2:"); //labelEmail.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); // pattern combo emailPattern2 = new Combo(composite, SWT.SINGLE | SWT.BORDER); emailPattern2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); emailPattern2.addModifyListener(new ModifyListenerImplementation()); emailPattern2.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(emailPattern2, emailOperation2, previousEmailPatterns2); } }); Composite emailComposite2 = new Composite(composite, SWT.NONE); emailComposite2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1)); GridLayout emailLayout2 = new GridLayout(); emailLayout2.marginWidth = 0; emailLayout2.marginHeight = 0; emailLayout2.horizontalSpacing = 2; emailLayout2.numColumns = 4; emailComposite2.setLayout(emailLayout2); Button e2button0 = new Button(emailComposite2, SWT.CHECK); e2button0.setText("owner"); Button e2button1 = new Button(emailComposite2, SWT.CHECK); e2button1.setText("reporter"); Button e2button2 = new Button(emailComposite2, SWT.CHECK); e2button2.setText("cc"); Button e2button3 = new Button(emailComposite2, SWT.CHECK); e2button3.setText("commenter"); emailButtons2 = new Button[] { e2button0, e2button1, e2button2, e2button3 }; // operation combo emailOperation2 = new Combo(composite, SWT.SINGLE | SWT.READ_ONLY | SWT.BORDER); emailOperation2.setItems(emailOperationText); emailOperation2.setText(emailOperationText[0]); emailOperation2.select(0); ///// Label labelKeywords = new Label(composite, SWT.NONE); labelKeywords.setText("&Keywords:"); labelKeywords.setLayoutData(new GridData(LABEL_WIDTH, SWT.DEFAULT)); //labelKeywords.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_END)); Composite keywordsComposite = new Composite(composite, SWT.NONE); keywordsComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1)); GridLayout keywordsLayout = new GridLayout(); keywordsLayout.marginWidth = 0; keywordsLayout.marginHeight = 0; keywordsLayout.numColumns = 3; keywordsComposite.setLayout(keywordsLayout); keywordsOperation = new Combo(keywordsComposite, SWT.READ_ONLY); keywordsOperation.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsOperation.setItems(keywordOperationText); keywordsOperation.setText(keywordOperationText[0]); keywordsOperation.select(0); keywords = new Combo(keywordsComposite, SWT.NONE); keywords.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false)); keywords.addModifyListener(new ModifyListenerImplementation()); keywords.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { handleWidgetSelected(keywords, keywordsOperation, previousKeywords); } }); Button keywordsSelectButton = new Button(keywordsComposite, SWT.NONE); keywordsSelectButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { KeywordsDialog dialog = new KeywordsDialog(getShell(), keywords.getText(), // Arrays.asList(BugzillaUiPlugin.getQueryOptions(IBugzillaConstants.VALUES_KEYWORDS, // null, repository.getUrl()))); if (dialog.open() == Window.OK) { keywords.setText(dialog.getSelectedKeywordsString()); } } }); keywordsSelectButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false)); keywordsSelectButton.setText("Select..."); SashForm sashForm = new SashForm(control, SWT.VERTICAL); sashForm.setLayout(sashFormLayout); final GridData gd_sashForm = new GridData(SWT.FILL, SWT.FILL, true, true); gd_sashForm.widthHint = 500; sashForm.setLayoutData(gd_sashForm); GridLayout topLayout = new GridLayout(); topLayout.numColumns = 4; SashForm topForm = new SashForm(sashForm, SWT.NONE); GridData topLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1); topLayoutData.widthHint = 500; topForm.setLayoutData(topLayoutData); topForm.setLayout(topLayout); GridLayout productLayout = new GridLayout(); productLayout.marginWidth = 0; productLayout.marginHeight = 0; productLayout.horizontalSpacing = 0; Composite productComposite = new Composite(topForm, SWT.NONE); productComposite.setLayout(productLayout); Label productLabel = new Label(productComposite, SWT.LEFT); productLabel.setText("&Product:"); GridData productLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); productLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; product = new List(productComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); product.setLayoutData(productLayoutData); product.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (product.getSelectionIndex() != -1) { String[] selectedProducts = product.getSelection(); updateAttributesFromRepository(repository.getUrl(), selectedProducts, false, false); } else { updateAttributesFromRepository(repository.getUrl(), null, false, false); } if (restoring) { restoring = false; restoreWidgetValues(); } setPageComplete(isPageComplete()); } }); GridLayout componentLayout = new GridLayout(); componentLayout.marginWidth = 0; componentLayout.marginHeight = 0; componentLayout.horizontalSpacing = 0; Composite componentComposite = new Composite(topForm, SWT.NONE); componentComposite.setLayout(componentLayout); Label componentLabel = new Label(componentComposite, SWT.LEFT); componentLabel.setText("Compo&nent:"); component = new List(componentComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData componentLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); componentLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; component.setLayoutData(componentLayoutData); component.addSelectionListener(updateActionSelectionAdapter); Composite versionComposite = new Composite(topForm, SWT.NONE); GridLayout versionLayout = new GridLayout(); versionLayout.marginWidth = 0; versionLayout.marginHeight = 0; versionLayout.horizontalSpacing = 0; versionComposite.setLayout(versionLayout); Label versionLabel = new Label(versionComposite, SWT.LEFT); versionLabel.setText("Vers&ion:"); version = new List(versionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData versionLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); versionLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; version.setLayoutData(versionLayoutData); version.addSelectionListener(updateActionSelectionAdapter); Composite milestoneComposite = new Composite(topForm, SWT.NONE); GridLayout milestoneLayout = new GridLayout(); milestoneLayout.marginWidth = 0; milestoneLayout.marginHeight = 0; milestoneLayout.horizontalSpacing = 0; milestoneComposite.setLayout(milestoneLayout); Label milestoneLabel = new Label(milestoneComposite, SWT.LEFT); milestoneLabel.setText("&Milestone:"); target = new List(milestoneComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridData targetLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true); targetLayoutData.heightHint = HEIGHT_ATTRIBUTE_COMBO; target.setLayoutData(targetLayoutData); target.addSelectionListener(updateActionSelectionAdapter); SashForm bottomForm = new SashForm(sashForm, SWT.NONE); GridLayout bottomLayout = new GridLayout(); bottomLayout.numColumns = 6; bottomForm.setLayout(bottomLayout); GridData bottomLayoutData = new GridData(SWT.FILL, SWT.FILL, true, true, 4, 1); bottomLayoutData.heightHint = 119; bottomLayoutData.widthHint = 400; bottomForm.setLayoutData(bottomLayoutData); Composite statusComposite = new Composite(bottomForm, SWT.NONE); GridLayout statusLayout = new GridLayout(); statusLayout.marginTop = 7; statusLayout.marginWidth = 0; statusLayout.horizontalSpacing = 0; statusLayout.marginHeight = 0; statusComposite.setLayout(statusLayout); Label statusLabel = new Label(statusComposite, SWT.LEFT); statusLabel.setText("Stat&us:"); status = new List(statusComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_status = new GridData(SWT.FILL, SWT.FILL, true, true); gd_status.heightHint = 60; status.setLayoutData(gd_status); status.addSelectionListener(updateActionSelectionAdapter); Composite resolutionComposite = new Composite(bottomForm, SWT.NONE); GridLayout resolutionLayout = new GridLayout(); resolutionLayout.marginTop = 7; resolutionLayout.marginWidth = 0; resolutionLayout.marginHeight = 0; resolutionLayout.horizontalSpacing = 0; resolutionComposite.setLayout(resolutionLayout); Label resolutionLabel = new Label(resolutionComposite, SWT.LEFT); resolutionLabel.setText("&Resolution:"); resolution = new List(resolutionComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_resolution = new GridData(SWT.FILL, SWT.FILL, true, true); gd_resolution.heightHint = 60; resolution.setLayoutData(gd_resolution); resolution.addSelectionListener(updateActionSelectionAdapter); Composite priorityComposite = new Composite(bottomForm, SWT.NONE); GridLayout priorityLayout = new GridLayout(); priorityLayout.marginTop = 7; priorityLayout.marginWidth = 0; priorityLayout.marginHeight = 0; priorityLayout.horizontalSpacing = 0; priorityComposite.setLayout(priorityLayout); Label priorityLabel = new Label(priorityComposite, SWT.LEFT); priorityLabel.setText("Priori&ty:"); priority = new List(priorityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_priority = new GridData(SWT.FILL, SWT.FILL, true, true); gd_priority.heightHint = 60; priority.setLayoutData(gd_priority); priority.addSelectionListener(updateActionSelectionAdapter); Composite severityComposite = new Composite(bottomForm, SWT.NONE); GridLayout severityLayout = new GridLayout(); severityLayout.marginTop = 7; severityLayout.marginWidth = 0; severityLayout.marginHeight = 0; severityLayout.horizontalSpacing = 0; severityComposite.setLayout(severityLayout); Label severityLabel = new Label(severityComposite, SWT.LEFT); severityLabel.setText("Se&verity:"); severity = new List(severityComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_severity = new GridData(SWT.FILL, SWT.FILL, true, true); gd_severity.heightHint = 60; severity.setLayoutData(gd_severity); severity.addSelectionListener(updateActionSelectionAdapter); Composite hardwareComposite = new Composite(bottomForm, SWT.NONE); GridLayout hardwareLayout = new GridLayout(); hardwareLayout.marginTop = 7; hardwareLayout.marginWidth = 0; hardwareLayout.marginHeight = 0; hardwareLayout.horizontalSpacing = 0; hardwareComposite.setLayout(hardwareLayout); Label hardwareLabel = new Label(hardwareComposite, SWT.LEFT); hardwareLabel.setText("Hard&ware:"); hardware = new List(hardwareComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_hardware = new GridData(SWT.FILL, SWT.FILL, true, true); gd_hardware.heightHint = 60; hardware.setLayoutData(gd_hardware); hardware.addSelectionListener(updateActionSelectionAdapter); Composite osComposite = new Composite(bottomForm, SWT.NONE); GridLayout osLayout = new GridLayout(); osLayout.marginTop = 7; osLayout.marginWidth = 0; osLayout.marginHeight = 0; osLayout.horizontalSpacing = 0; osComposite.setLayout(osLayout); Label osLabel = new Label(osComposite, SWT.LEFT); osLabel.setText("&Operating System:"); os = new List(osComposite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); final GridData gd_os = new GridData(SWT.FILL, SWT.FILL, true, true); gd_os.heightHint = 60; os.setLayoutData(gd_os); os.addSelectionListener(updateActionSelectionAdapter); bottomForm.setWeights(new int[] { 88, 90, 50, 77, 88, 85 }); }
diff --git a/src/com/android/exchange/service/EasAutoDiscover.java b/src/com/android/exchange/service/EasAutoDiscover.java index 4f7558ef..0713b0db 100644 --- a/src/com/android/exchange/service/EasAutoDiscover.java +++ b/src/com/android/exchange/service/EasAutoDiscover.java @@ -1,405 +1,405 @@ package com.android.exchange.service; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.util.Xml; import com.android.emailcommon.mail.MessagingException; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.HostAuth; import com.android.emailcommon.service.EmailServiceProxy; import com.android.exchange.Eas; import com.android.exchange.EasResponse; import com.android.mail.utils.LogUtils; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlSerializer; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; /** * Performs Autodiscover for Exchange servers. This feature tries to find all the configuration * options needed based on just a username and password. */ public class EasAutoDiscover extends EasServerConnection { private static final String TAG = Eas.LOG_TAG; private static final String AUTO_DISCOVER_SCHEMA_PREFIX = "http://schemas.microsoft.com/exchange/autodiscover/mobilesync/"; private static final String AUTO_DISCOVER_PAGE = "/autodiscover/autodiscover.xml"; // Set of string constants for parsing the autodiscover response. // TODO: Merge this into Tags.java? It's not quite the same but conceptually belongs there. private static final String ELEMENT_NAME_SERVER = "Server"; private static final String ELEMENT_NAME_TYPE = "Type"; private static final String ELEMENT_NAME_MOBILE_SYNC = "MobileSync"; private static final String ELEMENT_NAME_URL = "Url"; private static final String ELEMENT_NAME_SETTINGS = "Settings"; private static final String ELEMENT_NAME_ACTION = "Action"; private static final String ELEMENT_NAME_ERROR = "Error"; private static final String ELEMENT_NAME_REDIRECT = "Redirect"; private static final String ELEMENT_NAME_USER = "User"; private static final String ELEMENT_NAME_EMAIL_ADDRESS = "EMailAddress"; private static final String ELEMENT_NAME_DISPLAY_NAME = "DisplayName"; private static final String ELEMENT_NAME_RESPONSE = "Response"; private static final String ELEMENT_NAME_AUTODISCOVER = "Autodiscover"; public EasAutoDiscover(final Context context, final String username, final String password) { super(context, new Account(), new HostAuth()); mHostAuth.mLogin = username; mHostAuth.mPassword = password; mHostAuth.mFlags = HostAuth.FLAG_AUTHENTICATE | HostAuth.FLAG_SSL; mHostAuth.mPort = 443; } /** * Do all the work of autodiscovery. * @return A {@link Bundle} with the host information if autodiscovery succeeded. If we failed * due to an authentication failure, we return a {@link Bundle} with no host info but with * an appropriate error code. Otherwise, we return null. */ public Bundle doAutodiscover() { final String domain = getDomain(); if (domain == null) { return null; } final StringEntity entity = buildRequestEntity(); if (entity == null) { return null; } try { final HttpPost post = makePost("https://" + domain + AUTO_DISCOVER_PAGE, entity, "text/xml", false); final EasResponse resp = getResponse(post, domain); if (resp == null) { return null; } try { // resp is either an authentication error, or a good response. final int code = resp.getStatus(); if (code == HttpStatus.SC_UNAUTHORIZED) { - final Bundle bundle = new Bundle(1); - bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, - MessagingException.AUTODISCOVER_AUTHENTICATION_FAILED); - return bundle; + // We actually don't know if this is because it's an actual EAS auth error, + // or just HTTP 401 (e.g. you're just hitting some random server). + // Let's just dump them out of autodiscover in this case. + return null; } else { final HostAuth hostAuth = parseAutodiscover(resp); if (hostAuth != null) { // Fill in the rest of the HostAuth // We use the user name and password that were successful during // the autodiscover process hostAuth.mLogin = mHostAuth.mLogin; hostAuth.mPassword = mHostAuth.mPassword; // Note: there is no way we can auto-discover the proper client // SSL certificate to use, if one is needed. hostAuth.mPort = 443; hostAuth.mProtocol = Eas.PROTOCOL; hostAuth.mFlags = HostAuth.FLAG_SSL | HostAuth.FLAG_AUTHENTICATE; final Bundle bundle = new Bundle(2); bundle.putParcelable(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_HOST_AUTH, hostAuth); bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.NO_ERROR); return bundle; } } } finally { resp.close(); } } catch (final IllegalArgumentException e) { // This happens when the domain is malformatted. // TODO: Fix sanitizing of the domain -- we try to in UI but apparently not correctly. LogUtils.e(TAG, "ISE with domain: %s", domain); } return null; } /** * Get the domain of our account. * @return The domain of the email address. */ private String getDomain() { final int amp = mHostAuth.mLogin.indexOf('@'); if (amp < 0) { return null; } return mHostAuth.mLogin.substring(amp + 1); } /** * Create the payload of the request. * @return A {@link StringEntity} for the request XML. */ private StringEntity buildRequestEntity() { try { final XmlSerializer s = Xml.newSerializer(); final ByteArrayOutputStream os = new ByteArrayOutputStream(1024); s.setOutput(os, "UTF-8"); s.startDocument("UTF-8", false); s.startTag(null, "Autodiscover"); s.attribute(null, "xmlns", AUTO_DISCOVER_SCHEMA_PREFIX + "requestschema/2006"); s.startTag(null, "Request"); s.startTag(null, "EMailAddress").text(mHostAuth.mLogin).endTag(null, "EMailAddress"); s.startTag(null, "AcceptableResponseSchema"); s.text(AUTO_DISCOVER_SCHEMA_PREFIX + "responseschema/2006"); s.endTag(null, "AcceptableResponseSchema"); s.endTag(null, "Request"); s.endTag(null, "Autodiscover"); s.endDocument(); return new StringEntity(os.toString()); } catch (final IOException e) { // For all exception types, we can simply punt on autodiscover. } catch (final IllegalArgumentException e) { } catch (final IllegalStateException e) { } return null; } /** * Perform all requests necessary and get the server response. If the post fails or is * redirected, we alter the post and retry. * @param post The initial {@link HttpPost} for this request. * @param domain The domain for our account. * @return If this request succeeded or has an unrecoverable authentication error, an * {@link EasResponse} with the details. For other errors, we return null. */ private EasResponse getResponse(final HttpPost post, final String domain) { EasResponse resp = doPost(post, true); if (resp == null) { LogUtils.d(TAG, "Error in autodiscover, trying aternate address"); post.setURI(URI.create("https://autodiscover." + domain + AUTO_DISCOVER_PAGE)); resp = doPost(post, true); } return resp; } /** * Perform one attempt to get autodiscover information. Redirection and some authentication * errors are handled by recursively calls with modified host information. * @param post The {@link HttpPost} for this request. * @param canRetry Whether we can retry after an authentication failure. * @return If this request succeeded or has an unrecoverable authentication error, an * {@link EasResponse} with the details. For other errors, we return null. */ private EasResponse doPost(final HttpPost post, final boolean canRetry) { final EasResponse resp; try { resp = executePost(post); } catch (final IOException e) { return null; } final int code = resp.getStatus(); if (resp.isRedirectError()) { final String loc = resp.getRedirectAddress(); if (loc != null && loc.startsWith("http")) { LogUtils.d(TAG, "Posting autodiscover to redirect: " + loc); redirectHostAuth(loc); post.setURI(URI.create(loc)); return doPost(post, canRetry); } return null; } if (code == HttpStatus.SC_UNAUTHORIZED) { if (canRetry && mHostAuth.mLogin.contains("@")) { // Try again using the bare user name final int atSignIndex = mHostAuth.mLogin.indexOf('@'); mHostAuth.mLogin = mHostAuth.mLogin.substring(0, atSignIndex); LogUtils.d(TAG, "401 received; trying username: %s", mHostAuth.mLogin); resetAuthorization(post); return doPost(post, false); } } else if (code != HttpStatus.SC_OK) { // We'll try the next address if this doesn't work LogUtils.d(TAG, "Bad response code when posting autodiscover: %d", code); return null; } return resp; } /** * Parse the Server element of the server response. * @param parser The {@link XmlPullParser}. * @param hostAuth The {@link HostAuth} to populate with the results of parsing. * @throws XmlPullParserException * @throws IOException */ private static void parseServer(final XmlPullParser parser, final HostAuth hostAuth) throws XmlPullParserException, IOException { boolean mobileSync = false; while (true) { final int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals(ELEMENT_NAME_SERVER)) { break; } else if (type == XmlPullParser.START_TAG) { final String name = parser.getName(); if (name.equals(ELEMENT_NAME_TYPE)) { if (parser.nextText().equals(ELEMENT_NAME_MOBILE_SYNC)) { mobileSync = true; } } else if (mobileSync && name.equals(ELEMENT_NAME_URL)) { final String url = parser.nextText(); if (url != null) { LogUtils.d(TAG, "Autodiscover URL: %s", url); hostAuth.mAddress = Uri.parse(url).getHost(); } } } } } /** * Parse the Settings element of the server response. * @param parser The {@link XmlPullParser}. * @param hostAuth The {@link HostAuth} to populate with the results of parsing. * @throws XmlPullParserException * @throws IOException */ private static void parseSettings(final XmlPullParser parser, final HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { final int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals(ELEMENT_NAME_SETTINGS)) { break; } else if (type == XmlPullParser.START_TAG) { final String name = parser.getName(); if (name.equals(ELEMENT_NAME_SERVER)) { parseServer(parser, hostAuth); } } } } /** * Parse the Action element of the server response. * @param parser The {@link XmlPullParser}. * @param hostAuth The {@link HostAuth} to populate with the results of parsing. * @throws XmlPullParserException * @throws IOException */ private static void parseAction(final XmlPullParser parser, final HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { final int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals(ELEMENT_NAME_ACTION)) { break; } else if (type == XmlPullParser.START_TAG) { final String name = parser.getName(); if (name.equals(ELEMENT_NAME_ERROR)) { // Should parse the error } else if (name.equals(ELEMENT_NAME_REDIRECT)) { LogUtils.d(TAG, "Redirect: " + parser.nextText()); } else if (name.equals(ELEMENT_NAME_SETTINGS)) { parseSettings(parser, hostAuth); } } } } /** * Parse the User element of the server response. * @param parser The {@link XmlPullParser}. * @param hostAuth The {@link HostAuth} to populate with the results of parsing. * @throws XmlPullParserException * @throws IOException */ private static void parseUser(final XmlPullParser parser, final HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals(ELEMENT_NAME_USER)) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals(ELEMENT_NAME_EMAIL_ADDRESS)) { final String addr = parser.nextText(); LogUtils.d(TAG, "Autodiscover, email: %s", addr); } else if (name.equals(ELEMENT_NAME_DISPLAY_NAME)) { final String dn = parser.nextText(); LogUtils.d(TAG, "Autodiscover, user: %s", dn); } } } } /** * Parse the Response element of the server response. * @param parser The {@link XmlPullParser}. * @param hostAuth The {@link HostAuth} to populate with the results of parsing. * @throws XmlPullParserException * @throws IOException */ private static void parseResponse(final XmlPullParser parser, final HostAuth hostAuth) throws XmlPullParserException, IOException { while (true) { final int type = parser.next(); if (type == XmlPullParser.END_TAG && parser.getName().equals(ELEMENT_NAME_RESPONSE)) { break; } else if (type == XmlPullParser.START_TAG) { final String name = parser.getName(); if (name.equals(ELEMENT_NAME_USER)) { parseUser(parser, hostAuth); } else if (name.equals(ELEMENT_NAME_ACTION)) { parseAction(parser, hostAuth); } } } } /** * Parse the server response for the final {@link HostAuth}. * @param resp The {@link EasResponse} from the server. * @return The final {@link HostAuth} for this server. */ private static HostAuth parseAutodiscover(final EasResponse resp) { // The response to Autodiscover is regular XML (not WBXML) try { final XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser(); parser.setInput(resp.getInputStream(), "UTF-8"); if (parser.getEventType() != XmlPullParser.START_DOCUMENT) { return null; } if (parser.next() != XmlPullParser.START_TAG) { return null; } if (!parser.getName().equals(ELEMENT_NAME_AUTODISCOVER)) { return null; } final HostAuth hostAuth = new HostAuth(); while (true) { final int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName() .equals(ELEMENT_NAME_AUTODISCOVER)) { break; } else if (type == XmlPullParser.START_TAG && parser.getName() .equals(ELEMENT_NAME_RESPONSE)) { parseResponse(parser, hostAuth); // Valid responses will set the address. if (hostAuth.mAddress != null) { return hostAuth; } } } } catch (final XmlPullParserException e) { // Parse error. } catch (final IOException e) { // Error reading parser. } return null; } }
true
true
public Bundle doAutodiscover() { final String domain = getDomain(); if (domain == null) { return null; } final StringEntity entity = buildRequestEntity(); if (entity == null) { return null; } try { final HttpPost post = makePost("https://" + domain + AUTO_DISCOVER_PAGE, entity, "text/xml", false); final EasResponse resp = getResponse(post, domain); if (resp == null) { return null; } try { // resp is either an authentication error, or a good response. final int code = resp.getStatus(); if (code == HttpStatus.SC_UNAUTHORIZED) { final Bundle bundle = new Bundle(1); bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.AUTODISCOVER_AUTHENTICATION_FAILED); return bundle; } else { final HostAuth hostAuth = parseAutodiscover(resp); if (hostAuth != null) { // Fill in the rest of the HostAuth // We use the user name and password that were successful during // the autodiscover process hostAuth.mLogin = mHostAuth.mLogin; hostAuth.mPassword = mHostAuth.mPassword; // Note: there is no way we can auto-discover the proper client // SSL certificate to use, if one is needed. hostAuth.mPort = 443; hostAuth.mProtocol = Eas.PROTOCOL; hostAuth.mFlags = HostAuth.FLAG_SSL | HostAuth.FLAG_AUTHENTICATE; final Bundle bundle = new Bundle(2); bundle.putParcelable(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_HOST_AUTH, hostAuth); bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.NO_ERROR); return bundle; } } } finally { resp.close(); } } catch (final IllegalArgumentException e) { // This happens when the domain is malformatted. // TODO: Fix sanitizing of the domain -- we try to in UI but apparently not correctly. LogUtils.e(TAG, "ISE with domain: %s", domain); } return null; }
public Bundle doAutodiscover() { final String domain = getDomain(); if (domain == null) { return null; } final StringEntity entity = buildRequestEntity(); if (entity == null) { return null; } try { final HttpPost post = makePost("https://" + domain + AUTO_DISCOVER_PAGE, entity, "text/xml", false); final EasResponse resp = getResponse(post, domain); if (resp == null) { return null; } try { // resp is either an authentication error, or a good response. final int code = resp.getStatus(); if (code == HttpStatus.SC_UNAUTHORIZED) { // We actually don't know if this is because it's an actual EAS auth error, // or just HTTP 401 (e.g. you're just hitting some random server). // Let's just dump them out of autodiscover in this case. return null; } else { final HostAuth hostAuth = parseAutodiscover(resp); if (hostAuth != null) { // Fill in the rest of the HostAuth // We use the user name and password that were successful during // the autodiscover process hostAuth.mLogin = mHostAuth.mLogin; hostAuth.mPassword = mHostAuth.mPassword; // Note: there is no way we can auto-discover the proper client // SSL certificate to use, if one is needed. hostAuth.mPort = 443; hostAuth.mProtocol = Eas.PROTOCOL; hostAuth.mFlags = HostAuth.FLAG_SSL | HostAuth.FLAG_AUTHENTICATE; final Bundle bundle = new Bundle(2); bundle.putParcelable(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_HOST_AUTH, hostAuth); bundle.putInt(EmailServiceProxy.AUTO_DISCOVER_BUNDLE_ERROR_CODE, MessagingException.NO_ERROR); return bundle; } } } finally { resp.close(); } } catch (final IllegalArgumentException e) { // This happens when the domain is malformatted. // TODO: Fix sanitizing of the domain -- we try to in UI but apparently not correctly. LogUtils.e(TAG, "ISE with domain: %s", domain); } return null; }
diff --git a/src/snookerTables/Settings.java b/src/snookerTables/Settings.java index 2b7a0f8..aff3538 100644 --- a/src/snookerTables/Settings.java +++ b/src/snookerTables/Settings.java @@ -1,116 +1,116 @@ package snookerTables; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SpringLayout; import javax.swing.WindowConstants; public class Settings extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = 1L; JTextField tables, price; Main main; public Settings(Main main) { this.setVisible(true); //set frame visible this.setSize(new Dimension(260, 320)); //set size of frame this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); //set close action this.main = main; this.setLayout(new BorderLayout()); JLabel title = new JLabel("Settings", JLabel.CENTER); this.add(title, BorderLayout.NORTH); JPanel centerBox = new JPanel(); SpringLayout layout = new SpringLayout(); centerBox.setLayout(layout); // JPanel tableSetts = new JPanel(); // centerBox.add(tableSetts); JLabel numOfTables = new JLabel("Number of Tables: "); // centerBox.add(numOfTables); // centerBox.add(tables); // JPanel priceSetts = new JPanel(); // centerBox.add(priceSetts); JLabel pricePH = new JLabel("Adjust all price per hours: "); centerBox.add(pricePH); price = new JTextField(4); centerBox.add(price); - layout.putConstraint(SpringLayout.NORTH, numOfTables, 5, - SpringLayout.NORTH, centerBox); - layout.putConstraint(SpringLayout.NORTH, tables, 5, SpringLayout.NORTH, - centerBox); - layout.putConstraint(SpringLayout.WEST, numOfTables, 5, - SpringLayout.WEST, centerBox); - layout.putConstraint(SpringLayout.WEST, tables, 5, SpringLayout.EAST, - numOfTables); +// layout.putConstraint(SpringLayout.NORTH, numOfTables, 5, +// SpringLayout.NORTH, centerBox); +// layout.putConstraint(SpringLayout.NORTH, tables, 5, SpringLayout.NORTH, +// centerBox); +// layout.putConstraint(SpringLayout.WEST, numOfTables, 5, +// SpringLayout.WEST, centerBox); +// layout.putConstraint(SpringLayout.WEST, tables, 5, SpringLayout.EAST, +// numOfTables); layout.putConstraint(SpringLayout.NORTH, pricePH, 5, SpringLayout.SOUTH, numOfTables); layout.putConstraint(SpringLayout.WEST, pricePH, 5, SpringLayout.WEST, centerBox); layout.putConstraint(SpringLayout.NORTH, price, 5, SpringLayout.SOUTH, numOfTables); layout.putConstraint(SpringLayout.WEST, price, 5, SpringLayout.EAST, pricePH); layout.putConstraint(SpringLayout.EAST, centerBox, 5, SpringLayout.EAST, price); layout.putConstraint(SpringLayout.SOUTH, centerBox, 5, SpringLayout.SOUTH, price); this.add(centerBox); this.setResizable(false); JPanel bottomBar = new JPanel(); this.add(bottomBar, BorderLayout.SOUTH); JButton apply = new JButton("Apply"); apply.setActionCommand("apply"); apply.addActionListener(this); bottomBar.add(apply); JButton close = new JButton("Close"); close.setActionCommand("close"); close.addActionListener(this); bottomBar.add(close); this.pack(); } @Override public void actionPerformed(ActionEvent e) { if ("close".equals(e.getActionCommand())) { this.dispose(); } if ("apply".equals(e.getActionCommand())) { boolean success = true; if (!price.getText().equals("")) { try { main.setSnookerAllPrices(Double.parseDouble(price.getText())); } catch (NumberFormatException ex) { success = false; JOptionPane.showMessageDialog(this, "Price has to be a number."); } } if (success == true) { this.dispose(); } } } }
true
true
public Settings(Main main) { this.setVisible(true); //set frame visible this.setSize(new Dimension(260, 320)); //set size of frame this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); //set close action this.main = main; this.setLayout(new BorderLayout()); JLabel title = new JLabel("Settings", JLabel.CENTER); this.add(title, BorderLayout.NORTH); JPanel centerBox = new JPanel(); SpringLayout layout = new SpringLayout(); centerBox.setLayout(layout); // JPanel tableSetts = new JPanel(); // centerBox.add(tableSetts); JLabel numOfTables = new JLabel("Number of Tables: "); // centerBox.add(numOfTables); // centerBox.add(tables); // JPanel priceSetts = new JPanel(); // centerBox.add(priceSetts); JLabel pricePH = new JLabel("Adjust all price per hours: "); centerBox.add(pricePH); price = new JTextField(4); centerBox.add(price); layout.putConstraint(SpringLayout.NORTH, numOfTables, 5, SpringLayout.NORTH, centerBox); layout.putConstraint(SpringLayout.NORTH, tables, 5, SpringLayout.NORTH, centerBox); layout.putConstraint(SpringLayout.WEST, numOfTables, 5, SpringLayout.WEST, centerBox); layout.putConstraint(SpringLayout.WEST, tables, 5, SpringLayout.EAST, numOfTables); layout.putConstraint(SpringLayout.NORTH, pricePH, 5, SpringLayout.SOUTH, numOfTables); layout.putConstraint(SpringLayout.WEST, pricePH, 5, SpringLayout.WEST, centerBox); layout.putConstraint(SpringLayout.NORTH, price, 5, SpringLayout.SOUTH, numOfTables); layout.putConstraint(SpringLayout.WEST, price, 5, SpringLayout.EAST, pricePH); layout.putConstraint(SpringLayout.EAST, centerBox, 5, SpringLayout.EAST, price); layout.putConstraint(SpringLayout.SOUTH, centerBox, 5, SpringLayout.SOUTH, price); this.add(centerBox); this.setResizable(false); JPanel bottomBar = new JPanel(); this.add(bottomBar, BorderLayout.SOUTH); JButton apply = new JButton("Apply"); apply.setActionCommand("apply"); apply.addActionListener(this); bottomBar.add(apply); JButton close = new JButton("Close"); close.setActionCommand("close"); close.addActionListener(this); bottomBar.add(close); this.pack(); }
public Settings(Main main) { this.setVisible(true); //set frame visible this.setSize(new Dimension(260, 320)); //set size of frame this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); //set close action this.main = main; this.setLayout(new BorderLayout()); JLabel title = new JLabel("Settings", JLabel.CENTER); this.add(title, BorderLayout.NORTH); JPanel centerBox = new JPanel(); SpringLayout layout = new SpringLayout(); centerBox.setLayout(layout); // JPanel tableSetts = new JPanel(); // centerBox.add(tableSetts); JLabel numOfTables = new JLabel("Number of Tables: "); // centerBox.add(numOfTables); // centerBox.add(tables); // JPanel priceSetts = new JPanel(); // centerBox.add(priceSetts); JLabel pricePH = new JLabel("Adjust all price per hours: "); centerBox.add(pricePH); price = new JTextField(4); centerBox.add(price); // layout.putConstraint(SpringLayout.NORTH, numOfTables, 5, // SpringLayout.NORTH, centerBox); // layout.putConstraint(SpringLayout.NORTH, tables, 5, SpringLayout.NORTH, // centerBox); // layout.putConstraint(SpringLayout.WEST, numOfTables, 5, // SpringLayout.WEST, centerBox); // layout.putConstraint(SpringLayout.WEST, tables, 5, SpringLayout.EAST, // numOfTables); layout.putConstraint(SpringLayout.NORTH, pricePH, 5, SpringLayout.SOUTH, numOfTables); layout.putConstraint(SpringLayout.WEST, pricePH, 5, SpringLayout.WEST, centerBox); layout.putConstraint(SpringLayout.NORTH, price, 5, SpringLayout.SOUTH, numOfTables); layout.putConstraint(SpringLayout.WEST, price, 5, SpringLayout.EAST, pricePH); layout.putConstraint(SpringLayout.EAST, centerBox, 5, SpringLayout.EAST, price); layout.putConstraint(SpringLayout.SOUTH, centerBox, 5, SpringLayout.SOUTH, price); this.add(centerBox); this.setResizable(false); JPanel bottomBar = new JPanel(); this.add(bottomBar, BorderLayout.SOUTH); JButton apply = new JButton("Apply"); apply.setActionCommand("apply"); apply.addActionListener(this); bottomBar.add(apply); JButton close = new JButton("Close"); close.setActionCommand("close"); close.addActionListener(this); bottomBar.add(close); this.pack(); }
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pService.java b/wifi/java/android/net/wifi/p2p/WifiP2pService.java index 68a082a4..1b15cf35 100644 --- a/wifi/java/android/net/wifi/p2p/WifiP2pService.java +++ b/wifi/java/android/net/wifi/p2p/WifiP2pService.java @@ -1,2860 +1,2864 @@ /* * Copyright (C) 2011 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 android.net.wifi.p2p; import android.app.AlertDialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; 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; import android.content.res.Configuration; import android.content.res.Resources; import android.net.IConnectivityManager; import android.net.ConnectivityManager; import android.net.DhcpResults; import android.net.DhcpStateMachine; import android.net.InterfaceConfiguration; import android.net.LinkAddress; import android.net.LinkProperties; import android.net.NetworkInfo; import android.net.NetworkUtils; import android.net.wifi.WifiManager; import android.net.wifi.WifiMonitor; import android.net.wifi.WifiNative; import android.net.wifi.WifiStateMachine; import android.net.wifi.WpsInfo; import android.net.wifi.p2p.WifiP2pGroupList.GroupDeleteListener; import android.net.wifi.p2p.nsd.WifiP2pServiceInfo; import android.net.wifi.p2p.nsd.WifiP2pServiceRequest; import android.net.wifi.p2p.nsd.WifiP2pServiceResponse; import android.os.Binder; import android.os.IBinder; import android.os.INetworkManagementService; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.os.Messenger; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemProperties; import android.os.UserHandle; import android.provider.Settings; import android.text.TextUtils; import android.util.Slog; import android.util.SparseArray; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.EditText; import android.widget.TextView; import com.android.internal.R; import com.android.internal.telephony.TelephonyIntents; import com.android.internal.util.AsyncChannel; import com.android.internal.util.Protocol; import com.android.internal.util.State; import com.android.internal.util.StateMachine; import java.io.FileDescriptor; import java.io.PrintWriter; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; /** * WifiP2pService includes a state machine to perform Wi-Fi p2p operations. Applications * communicate with this service to issue device discovery and connectivity requests * through the WifiP2pManager interface. The state machine communicates with the wifi * driver through wpa_supplicant and handles the event responses through WifiMonitor. * * Note that the term Wifi when used without a p2p suffix refers to the client mode * of Wifi operation * @hide */ public class WifiP2pService extends IWifiP2pManager.Stub { private static final String TAG = "WifiP2pService"; private static final boolean DBG = false; private static final String NETWORKTYPE = "WIFI_P2P"; private Context mContext; private String mInterface; private Notification mNotification; INetworkManagementService mNwService; private DhcpStateMachine mDhcpStateMachine; private P2pStateMachine mP2pStateMachine; private AsyncChannel mReplyChannel = new AsyncChannel(); private AsyncChannel mWifiChannel; private static final Boolean JOIN_GROUP = true; private static final Boolean FORM_GROUP = false; private static final Boolean RELOAD = true; private static final Boolean NO_RELOAD = false; /* Two minutes comes from the wpa_supplicant setting */ private static final int GROUP_CREATING_WAIT_TIME_MS = 120 * 1000; private static int mGroupCreatingTimeoutIndex = 0; private static final int DISABLE_P2P_WAIT_TIME_MS = 5 * 1000; private static int mDisableP2pTimeoutIndex = 0; /* Set a two minute discover timeout to avoid STA scans from being blocked */ private static final int DISCOVER_TIMEOUT_S = 120; /* Idle time after a peer is gone when the group is torn down */ private static final int GROUP_IDLE_TIME_S = 10; private static final int BASE = Protocol.BASE_WIFI_P2P_SERVICE; /* Delayed message to timeout group creation */ public static final int GROUP_CREATING_TIMED_OUT = BASE + 1; /* User accepted a peer request */ private static final int PEER_CONNECTION_USER_ACCEPT = BASE + 2; /* User rejected a peer request */ private static final int PEER_CONNECTION_USER_REJECT = BASE + 3; /* User wants to disconnect wifi in favour of p2p */ private static final int DROP_WIFI_USER_ACCEPT = BASE + 4; /* User wants to keep his wifi connection and drop p2p */ private static final int DROP_WIFI_USER_REJECT = BASE + 5; /* Delayed message to timeout p2p disable */ public static final int DISABLE_P2P_TIMED_OUT = BASE + 6; /* Commands to the WifiStateMachine */ public static final int P2P_CONNECTION_CHANGED = BASE + 11; /* These commands are used to temporarily disconnect wifi when we detect * a frequency conflict which would make it impossible to have with p2p * and wifi active at the same time. * * If the user chooses to disable wifi temporarily, we keep wifi disconnected * until the p2p connection is done and terminated at which point we will * bring back wifi up * * DISCONNECT_WIFI_REQUEST * msg.arg1 = 1 enables temporary disconnect and 0 disables it. */ public static final int DISCONNECT_WIFI_REQUEST = BASE + 12; public static final int DISCONNECT_WIFI_RESPONSE = BASE + 13; public static final int SET_MIRACAST_MODE = BASE + 14; // During dhcp (and perhaps other times) we can't afford to drop packets // but Discovery will switch our channel enough we will. // msg.arg1 = ENABLED for blocking, DISABLED for resumed. // msg.arg2 = msg to send when blocked // msg.obj = StateMachine to send to when blocked public static final int BLOCK_DISCOVERY = BASE + 15; public static final int ENABLED = 1; public static final int DISABLED = 0; private final boolean mP2pSupported; private WifiP2pDevice mThisDevice = new WifiP2pDevice(); /* When a group has been explicitly created by an app, we persist the group * even after all clients have been disconnected until an explicit remove * is invoked */ private boolean mAutonomousGroup; /* Invitation to join an existing p2p group */ private boolean mJoinExistingGroup; /* Track whether we are in p2p discovery. This is used to avoid sending duplicate * broadcasts */ private boolean mDiscoveryStarted; /* Track whether servcice/peer discovery is blocked in favor of other wifi actions * (notably dhcp) */ private boolean mDiscoveryBlocked; /* * remember if we were in a scan when it had to be stopped */ private boolean mDiscoveryPostponed = false; private NetworkInfo mNetworkInfo; private boolean mTempoarilyDisconnectedWifi = false; /* The transaction Id of service discovery request */ private byte mServiceTransactionId = 0; /* Service discovery request ID of wpa_supplicant. * null means it's not set yet. */ private String mServiceDiscReqId; /* clients(application) information list. */ private HashMap<Messenger, ClientInfo> mClientInfoList = new HashMap<Messenger, ClientInfo>(); /* Is chosen as a unique range to avoid conflict with the range defined in Tethering.java */ private static final String[] DHCP_RANGE = {"192.168.49.2", "192.168.49.254"}; private static final String SERVER_ADDRESS = "192.168.49.1"; /** * Error code definition. * see the Table.8 in the WiFi Direct specification for the detail. */ public static enum P2pStatus { /* Success. */ SUCCESS, /* The target device is currently unavailable. */ INFORMATION_IS_CURRENTLY_UNAVAILABLE, /* Protocol error. */ INCOMPATIBLE_PARAMETERS, /* The target device reached the limit of the number of the connectable device. * For example, device limit or group limit is set. */ LIMIT_REACHED, /* Protocol error. */ INVALID_PARAMETER, /* Unable to accommodate request. */ UNABLE_TO_ACCOMMODATE_REQUEST, /* Previous protocol error, or disruptive behavior. */ PREVIOUS_PROTOCOL_ERROR, /* There is no common channels the both devices can use. */ NO_COMMON_CHANNEL, /* Unknown p2p group. For example, Device A tries to invoke the previous persistent group, * but device B has removed the specified credential already. */ UNKNOWN_P2P_GROUP, /* Both p2p devices indicated an intent of 15 in group owner negotiation. */ BOTH_GO_INTENT_15, /* Incompatible provisioning method. */ INCOMPATIBLE_PROVISIONING_METHOD, /* Rejected by user */ REJECTED_BY_USER, /* Unknown error */ UNKNOWN; public static P2pStatus valueOf(int error) { switch(error) { case 0 : return SUCCESS; case 1: return INFORMATION_IS_CURRENTLY_UNAVAILABLE; case 2: return INCOMPATIBLE_PARAMETERS; case 3: return LIMIT_REACHED; case 4: return INVALID_PARAMETER; case 5: return UNABLE_TO_ACCOMMODATE_REQUEST; case 6: return PREVIOUS_PROTOCOL_ERROR; case 7: return NO_COMMON_CHANNEL; case 8: return UNKNOWN_P2P_GROUP; case 9: return BOTH_GO_INTENT_15; case 10: return INCOMPATIBLE_PROVISIONING_METHOD; case 11: return REJECTED_BY_USER; default: return UNKNOWN; } } } public WifiP2pService(Context context) { mContext = context; //STOPSHIP: get this from native side mInterface = "p2p0"; mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI_P2P, 0, NETWORKTYPE, ""); mP2pSupported = mContext.getPackageManager().hasSystemFeature( PackageManager.FEATURE_WIFI_DIRECT); mThisDevice.primaryDeviceType = mContext.getResources().getString( com.android.internal.R.string.config_wifi_p2p_device_type); mP2pStateMachine = new P2pStateMachine(TAG, mP2pSupported); mP2pStateMachine.start(); } public void connectivityServiceReady() { IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE); mNwService = INetworkManagementService.Stub.asInterface(b); } private void enforceAccessPermission() { mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_WIFI_STATE, "WifiP2pService"); } private void enforceChangePermission() { mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CHANGE_WIFI_STATE, "WifiP2pService"); } private void enforceConnectivityInternalPermission() { mContext.enforceCallingOrSelfPermission( android.Manifest.permission.CONNECTIVITY_INTERNAL, "WifiP2pService"); } /** * Get a reference to handler. This is used by a client to establish * an AsyncChannel communication with WifiP2pService */ public Messenger getMessenger() { enforceAccessPermission(); enforceChangePermission(); return new Messenger(mP2pStateMachine.getHandler()); } /** This is used to provide information to drivers to optimize performance depending * on the current mode of operation. * 0 - disabled * 1 - source operation * 2 - sink operation * * As an example, the driver could reduce the channel dwell time during scanning * when acting as a source or sink to minimize impact on miracast. */ public void setMiracastMode(int mode) { enforceConnectivityInternalPermission(); mP2pStateMachine.sendMessage(SET_MIRACAST_MODE, mode); } @Override protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED) { pw.println("Permission Denial: can't dump WifiP2pService from from pid=" + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()); return; } mP2pStateMachine.dump(fd, pw, args); pw.println("mAutonomousGroup " + mAutonomousGroup); pw.println("mJoinExistingGroup " + mJoinExistingGroup); pw.println("mDiscoveryStarted " + mDiscoveryStarted); pw.println("mNetworkInfo " + mNetworkInfo); pw.println("mTempoarilyDisconnectedWifi " + mTempoarilyDisconnectedWifi); pw.println("mServiceDiscReqId " + mServiceDiscReqId); pw.println(); } /** * Handles interaction with WifiStateMachine */ private class P2pStateMachine extends StateMachine { private DefaultState mDefaultState = new DefaultState(); private P2pNotSupportedState mP2pNotSupportedState = new P2pNotSupportedState(); private P2pDisablingState mP2pDisablingState = new P2pDisablingState(); private P2pDisabledState mP2pDisabledState = new P2pDisabledState(); private P2pEnablingState mP2pEnablingState = new P2pEnablingState(); private P2pEnabledState mP2pEnabledState = new P2pEnabledState(); // Inactive is when p2p is enabled with no connectivity private InactiveState mInactiveState = new InactiveState(); private GroupCreatingState mGroupCreatingState = new GroupCreatingState(); private UserAuthorizingInviteRequestState mUserAuthorizingInviteRequestState = new UserAuthorizingInviteRequestState(); private UserAuthorizingNegotiationRequestState mUserAuthorizingNegotiationRequestState = new UserAuthorizingNegotiationRequestState(); private ProvisionDiscoveryState mProvisionDiscoveryState = new ProvisionDiscoveryState(); private GroupNegotiationState mGroupNegotiationState = new GroupNegotiationState(); private FrequencyConflictState mFrequencyConflictState =new FrequencyConflictState(); private GroupCreatedState mGroupCreatedState = new GroupCreatedState(); private UserAuthorizingJoinState mUserAuthorizingJoinState = new UserAuthorizingJoinState(); private OngoingGroupRemovalState mOngoingGroupRemovalState = new OngoingGroupRemovalState(); private WifiNative mWifiNative = new WifiNative(mInterface); private WifiMonitor mWifiMonitor = new WifiMonitor(this, mWifiNative); private final WifiP2pDeviceList mPeers = new WifiP2pDeviceList(); /* During a connection, supplicant can tell us that a device was lost. From a supplicant's * perspective, the discovery stops during connection and it purges device since it does * not get latest updates about the device without being in discovery state. * * From the framework perspective, the device is still there since we are connecting or * connected to it. so we keep these devices in a separate list, so that they are removed * when connection is cancelled or lost */ private final WifiP2pDeviceList mPeersLostDuringConnection = new WifiP2pDeviceList(); private final WifiP2pGroupList mGroups = new WifiP2pGroupList(null, new GroupDeleteListener() { @Override public void onDeleteGroup(int netId) { if (DBG) logd("called onDeleteGroup() netId=" + netId); mWifiNative.removeNetwork(netId); mWifiNative.saveConfig(); sendP2pPersistentGroupsChangedBroadcast(); } }); private final WifiP2pInfo mWifiP2pInfo = new WifiP2pInfo(); private WifiP2pGroup mGroup; // Saved WifiP2pConfig for an ongoing peer connection. This will never be null. // The deviceAddress will be an empty string when the device is inactive // or if it is connected without any ongoing join request private WifiP2pConfig mSavedPeerConfig = new WifiP2pConfig(); // Saved WifiP2pGroup from invitation request private WifiP2pGroup mSavedP2pGroup; P2pStateMachine(String name, boolean p2pSupported) { super(name); addState(mDefaultState); addState(mP2pNotSupportedState, mDefaultState); addState(mP2pDisablingState, mDefaultState); addState(mP2pDisabledState, mDefaultState); addState(mP2pEnablingState, mDefaultState); addState(mP2pEnabledState, mDefaultState); addState(mInactiveState, mP2pEnabledState); addState(mGroupCreatingState, mP2pEnabledState); addState(mUserAuthorizingInviteRequestState, mGroupCreatingState); addState(mUserAuthorizingNegotiationRequestState, mGroupCreatingState); addState(mProvisionDiscoveryState, mGroupCreatingState); addState(mGroupNegotiationState, mGroupCreatingState); addState(mFrequencyConflictState, mGroupCreatingState); addState(mGroupCreatedState, mP2pEnabledState); addState(mUserAuthorizingJoinState, mGroupCreatedState); addState(mOngoingGroupRemovalState, mGroupCreatedState); if (p2pSupported) { setInitialState(mP2pDisabledState); } else { setInitialState(mP2pNotSupportedState); } setLogRecSize(50); setLogOnlyTransitions(true); } class DefaultState extends State { @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { if (DBG) logd("Full connection with WifiStateMachine established"); mWifiChannel = (AsyncChannel) message.obj; } else { loge("Full connection failure, error = " + message.arg1); mWifiChannel = null; } break; case AsyncChannel.CMD_CHANNEL_DISCONNECTED: if (message.arg1 == AsyncChannel.STATUS_SEND_UNSUCCESSFUL) { loge("Send failed, client connection lost"); } else { loge("Client connection lost with reason: " + message.arg1); } mWifiChannel = null; break; case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION: AsyncChannel ac = new AsyncChannel(); ac.connect(mContext, getHandler(), message.replyTo); break; case BLOCK_DISCOVERY: mDiscoveryBlocked = (message.arg1 == ENABLED ? true : false); // always reset this - we went to a state that doesn't support discovery so // it would have stopped regardless mDiscoveryPostponed = false; if (mDiscoveryBlocked) { try { StateMachine m = (StateMachine)message.obj; m.sendMessage(message.arg2); } catch (Exception e) { loge("unable to send BLOCK_DISCOVERY response: " + e); } } break; case WifiP2pManager.DISCOVER_PEERS: replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.STOP_DISCOVERY: replyToMessage(message, WifiP2pManager.STOP_DISCOVERY_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.DISCOVER_SERVICES: replyToMessage(message, WifiP2pManager.DISCOVER_SERVICES_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.CONNECT: replyToMessage(message, WifiP2pManager.CONNECT_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.CANCEL_CONNECT: replyToMessage(message, WifiP2pManager.CANCEL_CONNECT_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.CREATE_GROUP: replyToMessage(message, WifiP2pManager.CREATE_GROUP_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.REMOVE_GROUP: replyToMessage(message, WifiP2pManager.REMOVE_GROUP_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.ADD_LOCAL_SERVICE: replyToMessage(message, WifiP2pManager.ADD_LOCAL_SERVICE_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.REMOVE_LOCAL_SERVICE: replyToMessage(message, WifiP2pManager.REMOVE_LOCAL_SERVICE_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.CLEAR_LOCAL_SERVICES: replyToMessage(message, WifiP2pManager.CLEAR_LOCAL_SERVICES_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.ADD_SERVICE_REQUEST: replyToMessage(message, WifiP2pManager.ADD_SERVICE_REQUEST_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.REMOVE_SERVICE_REQUEST: replyToMessage(message, WifiP2pManager.REMOVE_SERVICE_REQUEST_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.CLEAR_SERVICE_REQUESTS: replyToMessage(message, WifiP2pManager.CLEAR_SERVICE_REQUESTS_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.SET_DEVICE_NAME: replyToMessage(message, WifiP2pManager.SET_DEVICE_NAME_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.DELETE_PERSISTENT_GROUP: replyToMessage(message, WifiP2pManager.DELETE_PERSISTENT_GROUP, WifiP2pManager.BUSY); break; case WifiP2pManager.SET_WFD_INFO: replyToMessage(message, WifiP2pManager.SET_WFD_INFO_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.REQUEST_PEERS: replyToMessage(message, WifiP2pManager.RESPONSE_PEERS, new WifiP2pDeviceList(mPeers)); break; case WifiP2pManager.REQUEST_CONNECTION_INFO: replyToMessage(message, WifiP2pManager.RESPONSE_CONNECTION_INFO, new WifiP2pInfo(mWifiP2pInfo)); break; case WifiP2pManager.REQUEST_GROUP_INFO: replyToMessage(message, WifiP2pManager.RESPONSE_GROUP_INFO, mGroup != null ? new WifiP2pGroup(mGroup) : null); break; case WifiP2pManager.REQUEST_PERSISTENT_GROUP_INFO: replyToMessage(message, WifiP2pManager.RESPONSE_PERSISTENT_GROUP_INFO, new WifiP2pGroupList(mGroups, null)); break; case WifiP2pManager.START_WPS: replyToMessage(message, WifiP2pManager.START_WPS_FAILED, WifiP2pManager.BUSY); break; // Ignore case WifiMonitor.P2P_INVITATION_RESULT_EVENT: case WifiMonitor.SCAN_RESULTS_EVENT: case WifiMonitor.SUP_CONNECTION_EVENT: case WifiMonitor.SUP_DISCONNECTION_EVENT: case WifiMonitor.NETWORK_CONNECTION_EVENT: case WifiMonitor.NETWORK_DISCONNECTION_EVENT: case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: case WifiMonitor.WPS_SUCCESS_EVENT: case WifiMonitor.WPS_FAIL_EVENT: case WifiMonitor.WPS_OVERLAP_EVENT: case WifiMonitor.WPS_TIMEOUT_EVENT: case WifiMonitor.P2P_GROUP_REMOVED_EVENT: case WifiMonitor.P2P_DEVICE_FOUND_EVENT: case WifiMonitor.P2P_DEVICE_LOST_EVENT: case WifiMonitor.P2P_FIND_STOPPED_EVENT: case WifiMonitor.P2P_SERV_DISC_RESP_EVENT: case PEER_CONNECTION_USER_ACCEPT: case PEER_CONNECTION_USER_REJECT: case DISCONNECT_WIFI_RESPONSE: case DROP_WIFI_USER_ACCEPT: case DROP_WIFI_USER_REJECT: case GROUP_CREATING_TIMED_OUT: case DISABLE_P2P_TIMED_OUT: case DhcpStateMachine.CMD_PRE_DHCP_ACTION: case DhcpStateMachine.CMD_POST_DHCP_ACTION: case DhcpStateMachine.CMD_ON_QUIT: case WifiMonitor.P2P_PROV_DISC_FAILURE_EVENT: case SET_MIRACAST_MODE: break; case WifiStateMachine.CMD_ENABLE_P2P: // Enable is lazy and has no response break; case WifiStateMachine.CMD_DISABLE_P2P_REQ: // If we end up handling in default, p2p is not enabled mWifiChannel.sendMessage(WifiStateMachine.CMD_DISABLE_P2P_RSP); break; /* unexpected group created, remove */ case WifiMonitor.P2P_GROUP_STARTED_EVENT: mGroup = (WifiP2pGroup) message.obj; loge("Unexpected group creation, remove " + mGroup); mWifiNative.p2pGroupRemove(mGroup.getInterface()); break; // A group formation failure is always followed by // a group removed event. Flushing things at group formation // failure causes supplicant issues. Ignore right now. case WifiMonitor.P2P_GROUP_FORMATION_FAILURE_EVENT: break; default: loge("Unhandled message " + message); return NOT_HANDLED; } return HANDLED; } } class P2pNotSupportedState extends State { @Override public boolean processMessage(Message message) { switch (message.what) { case WifiP2pManager.DISCOVER_PEERS: replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.STOP_DISCOVERY: replyToMessage(message, WifiP2pManager.STOP_DISCOVERY_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.DISCOVER_SERVICES: replyToMessage(message, WifiP2pManager.DISCOVER_SERVICES_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.CONNECT: replyToMessage(message, WifiP2pManager.CONNECT_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.CANCEL_CONNECT: replyToMessage(message, WifiP2pManager.CANCEL_CONNECT_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.CREATE_GROUP: replyToMessage(message, WifiP2pManager.CREATE_GROUP_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.REMOVE_GROUP: replyToMessage(message, WifiP2pManager.REMOVE_GROUP_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.ADD_LOCAL_SERVICE: replyToMessage(message, WifiP2pManager.ADD_LOCAL_SERVICE_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.REMOVE_LOCAL_SERVICE: replyToMessage(message, WifiP2pManager.REMOVE_LOCAL_SERVICE_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.CLEAR_LOCAL_SERVICES: replyToMessage(message, WifiP2pManager.CLEAR_LOCAL_SERVICES_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.ADD_SERVICE_REQUEST: replyToMessage(message, WifiP2pManager.ADD_SERVICE_REQUEST_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.REMOVE_SERVICE_REQUEST: replyToMessage(message, WifiP2pManager.REMOVE_SERVICE_REQUEST_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.CLEAR_SERVICE_REQUESTS: replyToMessage(message, WifiP2pManager.CLEAR_SERVICE_REQUESTS_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.SET_DEVICE_NAME: replyToMessage(message, WifiP2pManager.SET_DEVICE_NAME_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.DELETE_PERSISTENT_GROUP: replyToMessage(message, WifiP2pManager.DELETE_PERSISTENT_GROUP, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.SET_WFD_INFO: replyToMessage(message, WifiP2pManager.SET_WFD_INFO_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; case WifiP2pManager.START_WPS: replyToMessage(message, WifiP2pManager.START_WPS_FAILED, WifiP2pManager.P2P_UNSUPPORTED); break; default: return NOT_HANDLED; } return HANDLED; } } class P2pDisablingState extends State { @Override public void enter() { if (DBG) logd(getName()); sendMessageDelayed(obtainMessage(DISABLE_P2P_TIMED_OUT, ++mDisableP2pTimeoutIndex, 0), DISABLE_P2P_WAIT_TIME_MS); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { case WifiMonitor.SUP_DISCONNECTION_EVENT: if (DBG) logd("p2p socket connection lost"); transitionTo(mP2pDisabledState); break; case WifiStateMachine.CMD_ENABLE_P2P: case WifiStateMachine.CMD_DISABLE_P2P_REQ: deferMessage(message); break; case DISABLE_P2P_TIMED_OUT: if (mGroupCreatingTimeoutIndex == message.arg1) { loge("P2p disable timed out"); transitionTo(mP2pDisabledState); } break; default: return NOT_HANDLED; } return HANDLED; } @Override public void exit() { mWifiChannel.sendMessage(WifiStateMachine.CMD_DISABLE_P2P_RSP); } } class P2pDisabledState extends State { @Override public void enter() { if (DBG) logd(getName()); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { case WifiStateMachine.CMD_ENABLE_P2P: try { mNwService.setInterfaceUp(mInterface); } catch (RemoteException re) { loge("Unable to change interface settings: " + re); } catch (IllegalStateException ie) { loge("Unable to change interface settings: " + ie); } mWifiMonitor.startMonitoring(); transitionTo(mP2pEnablingState); break; default: return NOT_HANDLED; } return HANDLED; } } class P2pEnablingState extends State { @Override public void enter() { if (DBG) logd(getName()); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { case WifiMonitor.SUP_CONNECTION_EVENT: if (DBG) logd("P2p socket connection successful"); transitionTo(mInactiveState); break; case WifiMonitor.SUP_DISCONNECTION_EVENT: loge("P2p socket connection failed"); transitionTo(mP2pDisabledState); break; case WifiStateMachine.CMD_ENABLE_P2P: case WifiStateMachine.CMD_DISABLE_P2P_REQ: deferMessage(message); break; default: return NOT_HANDLED; } return HANDLED; } } class P2pEnabledState extends State { @Override public void enter() { if (DBG) logd(getName()); sendP2pStateChangedBroadcast(true); mNetworkInfo.setIsAvailable(true); sendP2pConnectionChangedBroadcast(); initializeP2pSettings(); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { case WifiMonitor.SUP_DISCONNECTION_EVENT: loge("Unexpected loss of p2p socket connection"); transitionTo(mP2pDisabledState); break; case WifiStateMachine.CMD_ENABLE_P2P: //Nothing to do break; case WifiStateMachine.CMD_DISABLE_P2P_REQ: if (mPeers.clear()) { sendPeersChangedBroadcast(); } if (mGroups.clear()) sendP2pPersistentGroupsChangedBroadcast(); mWifiNative.closeSupplicantConnection(); transitionTo(mP2pDisablingState); break; case WifiP2pManager.SET_DEVICE_NAME: { WifiP2pDevice d = (WifiP2pDevice) message.obj; if (d != null && setAndPersistDeviceName(d.deviceName)) { if (DBG) logd("set device name " + d.deviceName); replyToMessage(message, WifiP2pManager.SET_DEVICE_NAME_SUCCEEDED); } else { replyToMessage(message, WifiP2pManager.SET_DEVICE_NAME_FAILED, WifiP2pManager.ERROR); } break; } case WifiP2pManager.SET_WFD_INFO: { WifiP2pWfdInfo d = (WifiP2pWfdInfo) message.obj; if (d != null && setWfdInfo(d)) { replyToMessage(message, WifiP2pManager.SET_WFD_INFO_SUCCEEDED); } else { replyToMessage(message, WifiP2pManager.SET_WFD_INFO_FAILED, WifiP2pManager.ERROR); } break; } case BLOCK_DISCOVERY: boolean blocked = (message.arg1 == ENABLED ? true : false); if (mDiscoveryBlocked == blocked) break; mDiscoveryBlocked = blocked; if (blocked && mDiscoveryStarted) { mWifiNative.p2pStopFind(); mDiscoveryPostponed = true; } if (!blocked && mDiscoveryPostponed) { mDiscoveryPostponed = false; mWifiNative.p2pFind(DISCOVER_TIMEOUT_S); } if (blocked) { try { StateMachine m = (StateMachine)message.obj; m.sendMessage(message.arg2); } catch (Exception e) { loge("unable to send BLOCK_DISCOVERY response: " + e); } } break; case WifiP2pManager.DISCOVER_PEERS: if (mDiscoveryBlocked) { replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_FAILED, WifiP2pManager.BUSY); break; } // do not send service discovery request while normal find operation. clearSupplicantServiceRequest(); if (mWifiNative.p2pFind(DISCOVER_TIMEOUT_S)) { replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_SUCCEEDED); sendP2pDiscoveryChangedBroadcast(true); } else { replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_FAILED, WifiP2pManager.ERROR); } break; case WifiMonitor.P2P_FIND_STOPPED_EVENT: sendP2pDiscoveryChangedBroadcast(false); break; case WifiP2pManager.STOP_DISCOVERY: if (mWifiNative.p2pStopFind()) { replyToMessage(message, WifiP2pManager.STOP_DISCOVERY_SUCCEEDED); } else { replyToMessage(message, WifiP2pManager.STOP_DISCOVERY_FAILED, WifiP2pManager.ERROR); } break; case WifiP2pManager.DISCOVER_SERVICES: if (mDiscoveryBlocked) { replyToMessage(message, WifiP2pManager.DISCOVER_SERVICES_FAILED, WifiP2pManager.BUSY); break; } if (DBG) logd(getName() + " discover services"); if (!updateSupplicantServiceRequest()) { replyToMessage(message, WifiP2pManager.DISCOVER_SERVICES_FAILED, WifiP2pManager.NO_SERVICE_REQUESTS); break; } if (mWifiNative.p2pFind(DISCOVER_TIMEOUT_S)) { replyToMessage(message, WifiP2pManager.DISCOVER_SERVICES_SUCCEEDED); } else { replyToMessage(message, WifiP2pManager.DISCOVER_SERVICES_FAILED, WifiP2pManager.ERROR); } break; case WifiMonitor.P2P_DEVICE_FOUND_EVENT: WifiP2pDevice device = (WifiP2pDevice) message.obj; if (mThisDevice.deviceAddress.equals(device.deviceAddress)) break; mPeers.updateSupplicantDetails(device); sendPeersChangedBroadcast(); break; case WifiMonitor.P2P_DEVICE_LOST_EVENT: device = (WifiP2pDevice) message.obj; // Gets current details for the one removed device = mPeers.remove(device.deviceAddress); if (device != null) { sendPeersChangedBroadcast(); } break; case WifiP2pManager.ADD_LOCAL_SERVICE: if (DBG) logd(getName() + " add service"); WifiP2pServiceInfo servInfo = (WifiP2pServiceInfo)message.obj; if (addLocalService(message.replyTo, servInfo)) { replyToMessage(message, WifiP2pManager.ADD_LOCAL_SERVICE_SUCCEEDED); } else { replyToMessage(message, WifiP2pManager.ADD_LOCAL_SERVICE_FAILED); } break; case WifiP2pManager.REMOVE_LOCAL_SERVICE: if (DBG) logd(getName() + " remove service"); servInfo = (WifiP2pServiceInfo)message.obj; removeLocalService(message.replyTo, servInfo); replyToMessage(message, WifiP2pManager.REMOVE_LOCAL_SERVICE_SUCCEEDED); break; case WifiP2pManager.CLEAR_LOCAL_SERVICES: if (DBG) logd(getName() + " clear service"); clearLocalServices(message.replyTo); replyToMessage(message, WifiP2pManager.CLEAR_LOCAL_SERVICES_SUCCEEDED); break; case WifiP2pManager.ADD_SERVICE_REQUEST: if (DBG) logd(getName() + " add service request"); if (!addServiceRequest(message.replyTo, (WifiP2pServiceRequest)message.obj)) { replyToMessage(message, WifiP2pManager.ADD_SERVICE_REQUEST_FAILED); break; } replyToMessage(message, WifiP2pManager.ADD_SERVICE_REQUEST_SUCCEEDED); break; case WifiP2pManager.REMOVE_SERVICE_REQUEST: if (DBG) logd(getName() + " remove service request"); removeServiceRequest(message.replyTo, (WifiP2pServiceRequest)message.obj); replyToMessage(message, WifiP2pManager.REMOVE_SERVICE_REQUEST_SUCCEEDED); break; case WifiP2pManager.CLEAR_SERVICE_REQUESTS: if (DBG) logd(getName() + " clear service request"); clearServiceRequests(message.replyTo); replyToMessage(message, WifiP2pManager.CLEAR_SERVICE_REQUESTS_SUCCEEDED); break; case WifiMonitor.P2P_SERV_DISC_RESP_EVENT: if (DBG) logd(getName() + " receive service response"); List<WifiP2pServiceResponse> sdRespList = (List<WifiP2pServiceResponse>) message.obj; for (WifiP2pServiceResponse resp : sdRespList) { WifiP2pDevice dev = mPeers.get(resp.getSrcDevice().deviceAddress); resp.setSrcDevice(dev); sendServiceResponse(resp); } break; case WifiP2pManager.DELETE_PERSISTENT_GROUP: if (DBG) logd(getName() + " delete persistent group"); mGroups.remove(message.arg1); replyToMessage(message, WifiP2pManager.DELETE_PERSISTENT_GROUP_SUCCEEDED); break; case SET_MIRACAST_MODE: mWifiNative.setMiracastMode(message.arg1); break; default: return NOT_HANDLED; } return HANDLED; } @Override public void exit() { sendP2pStateChangedBroadcast(false); mNetworkInfo.setIsAvailable(false); } } class InactiveState extends State { @Override public void enter() { if (DBG) logd(getName()); mSavedPeerConfig.invalidate(); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { case WifiP2pManager.CONNECT: if (DBG) logd(getName() + " sending connect"); WifiP2pConfig config = (WifiP2pConfig) message.obj; if (isConfigInvalid(config)) { loge("Dropping connect requeset " + config); replyToMessage(message, WifiP2pManager.CONNECT_FAILED); break; } mAutonomousGroup = false; mWifiNative.p2pStopFind(); if (reinvokePersistentGroup(config)) { transitionTo(mGroupNegotiationState); } else { transitionTo(mProvisionDiscoveryState); } mSavedPeerConfig = config; mPeers.updateStatus(mSavedPeerConfig.deviceAddress, WifiP2pDevice.INVITED); sendPeersChangedBroadcast(); replyToMessage(message, WifiP2pManager.CONNECT_SUCCEEDED); break; case WifiP2pManager.STOP_DISCOVERY: if (mWifiNative.p2pStopFind()) { // When discovery stops in inactive state, flush to clear // state peer data mWifiNative.p2pFlush(); mServiceDiscReqId = null; replyToMessage(message, WifiP2pManager.STOP_DISCOVERY_SUCCEEDED); } else { replyToMessage(message, WifiP2pManager.STOP_DISCOVERY_FAILED, WifiP2pManager.ERROR); } break; case WifiMonitor.P2P_GO_NEGOTIATION_REQUEST_EVENT: config = (WifiP2pConfig) message.obj; if (isConfigInvalid(config)) { loge("Dropping GO neg request " + config); break; } mSavedPeerConfig = config; mAutonomousGroup = false; mJoinExistingGroup = false; transitionTo(mUserAuthorizingNegotiationRequestState); break; case WifiMonitor.P2P_INVITATION_RECEIVED_EVENT: WifiP2pGroup group = (WifiP2pGroup) message.obj; WifiP2pDevice owner = group.getOwner(); if (owner == null) { loge("Ignored invitation from null owner"); break; } config = new WifiP2pConfig(); config.deviceAddress = group.getOwner().deviceAddress; if (isConfigInvalid(config)) { loge("Dropping invitation request " + config); break; } mSavedPeerConfig = config; //Check if we have the owner in peer list and use appropriate //wps method. Default is to use PBC. if ((owner = mPeers.get(owner.deviceAddress)) != null) { if (owner.wpsPbcSupported()) { mSavedPeerConfig.wps.setup = WpsInfo.PBC; } else if (owner.wpsKeypadSupported()) { mSavedPeerConfig.wps.setup = WpsInfo.KEYPAD; } else if (owner.wpsDisplaySupported()) { mSavedPeerConfig.wps.setup = WpsInfo.DISPLAY; } } mAutonomousGroup = false; mJoinExistingGroup = true; transitionTo(mUserAuthorizingInviteRequestState); break; case WifiMonitor.P2P_PROV_DISC_PBC_REQ_EVENT: case WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT: case WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT: //We let the supplicant handle the provision discovery response //and wait instead for the GO_NEGOTIATION_REQUEST_EVENT. //Handling provision discovery and issuing a p2p_connect before //group negotiation comes through causes issues break; case WifiP2pManager.CREATE_GROUP: mAutonomousGroup = true; int netId = message.arg1; boolean ret = false; if (netId == WifiP2pGroup.PERSISTENT_NET_ID) { // check if the go persistent group is present. netId = mGroups.getNetworkId(mThisDevice.deviceAddress); if (netId != -1) { ret = mWifiNative.p2pGroupAdd(netId); } else { ret = mWifiNative.p2pGroupAdd(true); } } else { ret = mWifiNative.p2pGroupAdd(false); } if (ret) { replyToMessage(message, WifiP2pManager.CREATE_GROUP_SUCCEEDED); transitionTo(mGroupNegotiationState); } else { replyToMessage(message, WifiP2pManager.CREATE_GROUP_FAILED, WifiP2pManager.ERROR); // remain at this state. } break; case WifiMonitor.P2P_GROUP_STARTED_EVENT: mGroup = (WifiP2pGroup) message.obj; if (DBG) logd(getName() + " group started"); // We hit this scenario when a persistent group is reinvoked if (mGroup.getNetworkId() == WifiP2pGroup.PERSISTENT_NET_ID) { mAutonomousGroup = false; deferMessage(message); transitionTo(mGroupNegotiationState); } else { loge("Unexpected group creation, remove " + mGroup); mWifiNative.p2pGroupRemove(mGroup.getInterface()); } break; default: return NOT_HANDLED; } return HANDLED; } } class GroupCreatingState extends State { @Override public void enter() { if (DBG) logd(getName()); sendMessageDelayed(obtainMessage(GROUP_CREATING_TIMED_OUT, ++mGroupCreatingTimeoutIndex, 0), GROUP_CREATING_WAIT_TIME_MS); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); boolean ret = HANDLED; switch (message.what) { case GROUP_CREATING_TIMED_OUT: if (mGroupCreatingTimeoutIndex == message.arg1) { if (DBG) logd("Group negotiation timed out"); handleGroupCreationFailure(); transitionTo(mInactiveState); } break; case WifiMonitor.P2P_DEVICE_LOST_EVENT: WifiP2pDevice device = (WifiP2pDevice) message.obj; if (!mSavedPeerConfig.deviceAddress.equals(device.deviceAddress)) { if (DBG) { logd("mSavedPeerConfig " + mSavedPeerConfig.deviceAddress + "device " + device.deviceAddress); } // Do the regular device lost handling ret = NOT_HANDLED; break; } // Do nothing if (DBG) logd("Add device to lost list " + device); mPeersLostDuringConnection.updateSupplicantDetails(device); break; case WifiP2pManager.DISCOVER_PEERS: /* Discovery will break negotiation */ replyToMessage(message, WifiP2pManager.DISCOVER_PEERS_FAILED, WifiP2pManager.BUSY); break; case WifiP2pManager.CANCEL_CONNECT: //Do a supplicant p2p_cancel which only cancels an ongoing //group negotiation. This will fail for a pending provision //discovery or for a pending user action, but at the framework //level, we always treat cancel as succeeded and enter //an inactive state mWifiNative.p2pCancelConnect(); handleGroupCreationFailure(); transitionTo(mInactiveState); replyToMessage(message, WifiP2pManager.CANCEL_CONNECT_SUCCEEDED); break; default: ret = NOT_HANDLED; } return ret; } } class UserAuthorizingNegotiationRequestState extends State { @Override public void enter() { if (DBG) logd(getName()); notifyInvitationReceived(); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); boolean ret = HANDLED; switch (message.what) { case PEER_CONNECTION_USER_ACCEPT: mWifiNative.p2pStopFind(); p2pConnectWithPinDisplay(mSavedPeerConfig); mPeers.updateStatus(mSavedPeerConfig.deviceAddress, WifiP2pDevice.INVITED); sendPeersChangedBroadcast(); transitionTo(mGroupNegotiationState); break; case PEER_CONNECTION_USER_REJECT: if (DBG) logd("User rejected negotiation " + mSavedPeerConfig); transitionTo(mInactiveState); break; default: return NOT_HANDLED; } return ret; } @Override public void exit() { //TODO: dismiss dialog if not already done } } class UserAuthorizingInviteRequestState extends State { @Override public void enter() { if (DBG) logd(getName()); notifyInvitationReceived(); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); boolean ret = HANDLED; switch (message.what) { case PEER_CONNECTION_USER_ACCEPT: mWifiNative.p2pStopFind(); if (!reinvokePersistentGroup(mSavedPeerConfig)) { // Do negotiation when persistence fails p2pConnectWithPinDisplay(mSavedPeerConfig); } mPeers.updateStatus(mSavedPeerConfig.deviceAddress, WifiP2pDevice.INVITED); sendPeersChangedBroadcast(); transitionTo(mGroupNegotiationState); break; case PEER_CONNECTION_USER_REJECT: if (DBG) logd("User rejected invitation " + mSavedPeerConfig); transitionTo(mInactiveState); break; default: return NOT_HANDLED; } return ret; } @Override public void exit() { //TODO: dismiss dialog if not already done } } class ProvisionDiscoveryState extends State { @Override public void enter() { if (DBG) logd(getName()); mWifiNative.p2pProvisionDiscovery(mSavedPeerConfig); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); WifiP2pProvDiscEvent provDisc; WifiP2pDevice device; switch (message.what) { case WifiMonitor.P2P_PROV_DISC_PBC_RSP_EVENT: provDisc = (WifiP2pProvDiscEvent) message.obj; device = provDisc.device; if (!device.deviceAddress.equals(mSavedPeerConfig.deviceAddress)) break; if (mSavedPeerConfig.wps.setup == WpsInfo.PBC) { if (DBG) logd("Found a match " + mSavedPeerConfig); p2pConnectWithPinDisplay(mSavedPeerConfig); transitionTo(mGroupNegotiationState); } break; case WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT: provDisc = (WifiP2pProvDiscEvent) message.obj; device = provDisc.device; if (!device.deviceAddress.equals(mSavedPeerConfig.deviceAddress)) break; if (mSavedPeerConfig.wps.setup == WpsInfo.KEYPAD) { if (DBG) logd("Found a match " + mSavedPeerConfig); /* we already have the pin */ if (!TextUtils.isEmpty(mSavedPeerConfig.wps.pin)) { p2pConnectWithPinDisplay(mSavedPeerConfig); transitionTo(mGroupNegotiationState); } else { mJoinExistingGroup = false; transitionTo(mUserAuthorizingNegotiationRequestState); } } break; case WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT: provDisc = (WifiP2pProvDiscEvent) message.obj; device = provDisc.device; if (!device.deviceAddress.equals(mSavedPeerConfig.deviceAddress)) break; if (mSavedPeerConfig.wps.setup == WpsInfo.DISPLAY) { if (DBG) logd("Found a match " + mSavedPeerConfig); mSavedPeerConfig.wps.pin = provDisc.pin; p2pConnectWithPinDisplay(mSavedPeerConfig); notifyInvitationSent(provDisc.pin, device.deviceAddress); transitionTo(mGroupNegotiationState); } break; case WifiMonitor.P2P_PROV_DISC_FAILURE_EVENT: loge("provision discovery failed"); handleGroupCreationFailure(); transitionTo(mInactiveState); break; default: return NOT_HANDLED; } return HANDLED; } } class GroupNegotiationState extends State { @Override public void enter() { if (DBG) logd(getName()); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { // We ignore these right now, since we get a GROUP_STARTED notification // afterwards case WifiMonitor.P2P_GO_NEGOTIATION_SUCCESS_EVENT: case WifiMonitor.P2P_GROUP_FORMATION_SUCCESS_EVENT: if (DBG) logd(getName() + " go success"); break; case WifiMonitor.P2P_GROUP_STARTED_EVENT: mGroup = (WifiP2pGroup) message.obj; if (DBG) logd(getName() + " group started"); if (mGroup.getNetworkId() == WifiP2pGroup.PERSISTENT_NET_ID) { /* * update cache information and set network id to mGroup. */ updatePersistentNetworks(NO_RELOAD); String devAddr = mGroup.getOwner().deviceAddress; mGroup.setNetworkId(mGroups.getNetworkId(devAddr, mGroup.getNetworkName())); } if (mGroup.isGroupOwner()) { /* Setting an idle time out on GO causes issues with certain scenarios * on clients where it can be off-channel for longer and with the power * save modes used. * * TODO: Verify multi-channel scenarios and supplicant behavior are * better before adding a time out in future */ //Set group idle timeout of 10 sec, to avoid GO beaconing incase of any //failure during 4-way Handshake. if (!mAutonomousGroup) { mWifiNative.setP2pGroupIdle(mGroup.getInterface(), GROUP_IDLE_TIME_S); } startDhcpServer(mGroup.getInterface()); } else { mWifiNative.setP2pGroupIdle(mGroup.getInterface(), GROUP_IDLE_TIME_S); mDhcpStateMachine = DhcpStateMachine.makeDhcpStateMachine(mContext, P2pStateMachine.this, mGroup.getInterface()); // TODO: We should use DHCP state machine PRE message like WifiStateMachine mWifiNative.setP2pPowerSave(mGroup.getInterface(), false); mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_START_DHCP); WifiP2pDevice groupOwner = mGroup.getOwner(); WifiP2pDevice peer = mPeers.get(groupOwner.deviceAddress); if (peer != null) { // update group owner details with peer details found at discovery groupOwner.updateSupplicantDetails(peer); mPeers.updateStatus(groupOwner.deviceAddress, WifiP2pDevice.CONNECTED); sendPeersChangedBroadcast(); } else { // A supplicant bug can lead to reporting an invalid // group owner address (all zeroes) at times. Avoid a // crash, but continue group creation since it is not // essential. logw("Unknown group owner " + groupOwner); } } transitionTo(mGroupCreatedState); break; case WifiMonitor.P2P_GO_NEGOTIATION_FAILURE_EVENT: P2pStatus status = (P2pStatus) message.obj; if (status == P2pStatus.NO_COMMON_CHANNEL) { transitionTo(mFrequencyConflictState); break; } /* continue with group removal handling */ case WifiMonitor.P2P_GROUP_REMOVED_EVENT: if (DBG) logd(getName() + " go failure"); handleGroupCreationFailure(); transitionTo(mInactiveState); break; // A group formation failure is always followed by // a group removed event. Flushing things at group formation // failure causes supplicant issues. Ignore right now. case WifiMonitor.P2P_GROUP_FORMATION_FAILURE_EVENT: status = (P2pStatus) message.obj; if (status == P2pStatus.NO_COMMON_CHANNEL) { transitionTo(mFrequencyConflictState); break; } break; case WifiMonitor.P2P_INVITATION_RESULT_EVENT: status = (P2pStatus)message.obj; if (status == P2pStatus.SUCCESS) { // invocation was succeeded. // wait P2P_GROUP_STARTED_EVENT. break; } loge("Invitation result " + status); if (status == P2pStatus.UNKNOWN_P2P_GROUP) { // target device has already removed the credential. // So, remove this credential accordingly. int netId = mSavedPeerConfig.netId; if (netId >= 0) { if (DBG) logd("Remove unknown client from the list"); removeClientFromList(netId, mSavedPeerConfig.deviceAddress, true); } // Reinvocation has failed, try group negotiation mSavedPeerConfig.netId = WifiP2pGroup.PERSISTENT_NET_ID; p2pConnectWithPinDisplay(mSavedPeerConfig); } else if (status == P2pStatus.INFORMATION_IS_CURRENTLY_UNAVAILABLE) { // Devices setting persistent_reconnect to 0 in wpa_supplicant // always defer the invocation request and return // "information is currently unable" error. // So, try another way to connect for interoperability. mSavedPeerConfig.netId = WifiP2pGroup.PERSISTENT_NET_ID; p2pConnectWithPinDisplay(mSavedPeerConfig); } else if (status == P2pStatus.NO_COMMON_CHANNEL) { transitionTo(mFrequencyConflictState); } else { handleGroupCreationFailure(); transitionTo(mInactiveState); } break; default: return NOT_HANDLED; } return HANDLED; } } class FrequencyConflictState extends State { private AlertDialog mFrequencyConflictDialog; @Override public void enter() { if (DBG) logd(getName()); notifyFrequencyConflict(); } private void notifyFrequencyConflict() { logd("Notify frequency conflict"); Resources r = Resources.getSystem(); AlertDialog dialog = new AlertDialog.Builder(mContext) .setMessage(r.getString(R.string.wifi_p2p_frequency_conflict_message, getDeviceName(mSavedPeerConfig.deviceAddress))) .setPositiveButton(r.getString(R.string.dlg_ok), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { sendMessage(DROP_WIFI_USER_ACCEPT); } }) .setNegativeButton(r.getString(R.string.decline), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { sendMessage(DROP_WIFI_USER_REJECT); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface arg0) { sendMessage(DROP_WIFI_USER_REJECT); } }) .create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); mFrequencyConflictDialog = dialog; } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { case WifiMonitor.P2P_GO_NEGOTIATION_SUCCESS_EVENT: case WifiMonitor.P2P_GROUP_FORMATION_SUCCESS_EVENT: loge(getName() + "group sucess during freq conflict!"); break; case WifiMonitor.P2P_GROUP_STARTED_EVENT: loge(getName() + "group started after freq conflict, handle anyway"); deferMessage(message); transitionTo(mGroupNegotiationState); break; case WifiMonitor.P2P_GO_NEGOTIATION_FAILURE_EVENT: case WifiMonitor.P2P_GROUP_REMOVED_EVENT: case WifiMonitor.P2P_GROUP_FORMATION_FAILURE_EVENT: // Ignore failures since we retry again break; case DROP_WIFI_USER_REJECT: // User rejected dropping wifi in favour of p2p handleGroupCreationFailure(); transitionTo(mInactiveState); break; case DROP_WIFI_USER_ACCEPT: // User accepted dropping wifi in favour of p2p mWifiChannel.sendMessage(WifiP2pService.DISCONNECT_WIFI_REQUEST, 1); mTempoarilyDisconnectedWifi = true; break; case DISCONNECT_WIFI_RESPONSE: // Got a response from wifistatemachine, retry p2p if (DBG) logd(getName() + "Wifi disconnected, retry p2p"); transitionTo(mInactiveState); sendMessage(WifiP2pManager.CONNECT, mSavedPeerConfig); break; default: return NOT_HANDLED; } return HANDLED; } public void exit() { if (mFrequencyConflictDialog != null) mFrequencyConflictDialog.dismiss(); } } class GroupCreatedState extends State { @Override public void enter() { if (DBG) logd(getName()); // Once connected, peer config details are invalid mSavedPeerConfig.invalidate(); mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null, null); updateThisDevice(WifiP2pDevice.CONNECTED); //DHCP server has already been started if I am a group owner if (mGroup.isGroupOwner()) { setWifiP2pInfoOnGroupFormation(NetworkUtils.numericToInetAddress(SERVER_ADDRESS)); } // In case of a negotiation group, connection changed is sent // after a client joins. For autonomous, send now if (mAutonomousGroup) { sendP2pConnectionChangedBroadcast(); } } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { case WifiMonitor.AP_STA_CONNECTED_EVENT: WifiP2pDevice device = (WifiP2pDevice) message.obj; String deviceAddress = device.deviceAddress; // Clear timeout that was set when group was started. mWifiNative.setP2pGroupIdle(mGroup.getInterface(), 0); if (deviceAddress != null) { if (mPeers.get(deviceAddress) != null) { mGroup.addClient(mPeers.get(deviceAddress)); } else { mGroup.addClient(deviceAddress); } mPeers.updateStatus(deviceAddress, WifiP2pDevice.CONNECTED); if (DBG) logd(getName() + " ap sta connected"); sendPeersChangedBroadcast(); } else { loge("Connect on null device address, ignore"); } sendP2pConnectionChangedBroadcast(); break; case WifiMonitor.AP_STA_DISCONNECTED_EVENT: device = (WifiP2pDevice) message.obj; deviceAddress = device.deviceAddress; if (deviceAddress != null) { mPeers.updateStatus(deviceAddress, WifiP2pDevice.AVAILABLE); if (mGroup.removeClient(deviceAddress)) { if (DBG) logd("Removed client " + deviceAddress); if (!mAutonomousGroup && mGroup.isClientListEmpty()) { logd("Client list empty, remove non-persistent p2p group"); mWifiNative.p2pGroupRemove(mGroup.getInterface()); // We end up sending connection changed broadcast // when this happens at exit() } else { // Notify when a client disconnects from group sendP2pConnectionChangedBroadcast(); } } else { if (DBG) logd("Failed to remove client " + deviceAddress); for (WifiP2pDevice c : mGroup.getClientList()) { if (DBG) logd("client " + c.deviceAddress); } } sendPeersChangedBroadcast(); if (DBG) logd(getName() + " ap sta disconnected"); } else { loge("Disconnect on unknown device: " + device); } break; case DhcpStateMachine.CMD_POST_DHCP_ACTION: DhcpResults dhcpResults = (DhcpResults) message.obj; if (message.arg1 == DhcpStateMachine.DHCP_SUCCESS && dhcpResults != null) { if (DBG) logd("DhcpResults: " + dhcpResults); setWifiP2pInfoOnGroupFormation(dhcpResults.serverAddress); sendP2pConnectionChangedBroadcast(); //Turn on power save on client mWifiNative.setP2pPowerSave(mGroup.getInterface(), true); } else { loge("DHCP failed"); mWifiNative.p2pGroupRemove(mGroup.getInterface()); } break; case WifiP2pManager.REMOVE_GROUP: if (DBG) logd(getName() + " remove group"); if (mWifiNative.p2pGroupRemove(mGroup.getInterface())) { transitionTo(mOngoingGroupRemovalState); replyToMessage(message, WifiP2pManager.REMOVE_GROUP_SUCCEEDED); } else { handleGroupRemoved(); transitionTo(mInactiveState); replyToMessage(message, WifiP2pManager.REMOVE_GROUP_FAILED, WifiP2pManager.ERROR); } break; /* We do not listen to NETWORK_DISCONNECTION_EVENT for group removal * handling since supplicant actually tries to reconnect after a temporary * disconnect until group idle time out. Eventually, a group removal event * will come when group has been removed. * * When there are connectivity issues during temporary disconnect, the application * will also just remove the group. * * Treating network disconnection as group removal causes race conditions since * supplicant would still maintain the group at that stage. */ case WifiMonitor.P2P_GROUP_REMOVED_EVENT: if (DBG) logd(getName() + " group removed"); handleGroupRemoved(); transitionTo(mInactiveState); break; case WifiMonitor.P2P_DEVICE_LOST_EVENT: device = (WifiP2pDevice) message.obj; //Device loss for a connected device indicates it is not in discovery any more if (mGroup.contains(device)) { if (DBG) logd("Add device to lost list " + device); mPeersLostDuringConnection.updateSupplicantDetails(device); return HANDLED; } // Do the regular device lost handling return NOT_HANDLED; case WifiStateMachine.CMD_DISABLE_P2P_REQ: sendMessage(WifiP2pManager.REMOVE_GROUP); deferMessage(message); break; // This allows any client to join the GO during the // WPS window case WifiP2pManager.START_WPS: WpsInfo wps = (WpsInfo) message.obj; if (wps == null) { replyToMessage(message, WifiP2pManager.START_WPS_FAILED); break; } boolean ret = true; if (wps.setup == WpsInfo.PBC) { ret = mWifiNative.startWpsPbc(mGroup.getInterface(), null); } else { if (wps.pin == null) { String pin = mWifiNative.startWpsPinDisplay(mGroup.getInterface()); try { Integer.parseInt(pin); notifyInvitationSent(pin, "any"); } catch (NumberFormatException ignore) { ret = false; } } else { ret = mWifiNative.startWpsPinKeypad(mGroup.getInterface(), wps.pin); } } replyToMessage(message, ret ? WifiP2pManager.START_WPS_SUCCEEDED : WifiP2pManager.START_WPS_FAILED); break; case WifiP2pManager.CONNECT: WifiP2pConfig config = (WifiP2pConfig) message.obj; if (isConfigInvalid(config)) { loge("Dropping connect requeset " + config); replyToMessage(message, WifiP2pManager.CONNECT_FAILED); break; } logd("Inviting device : " + config.deviceAddress); mSavedPeerConfig = config; if (mWifiNative.p2pInvite(mGroup, config.deviceAddress)) { mPeers.updateStatus(config.deviceAddress, WifiP2pDevice.INVITED); sendPeersChangedBroadcast(); replyToMessage(message, WifiP2pManager.CONNECT_SUCCEEDED); } else { replyToMessage(message, WifiP2pManager.CONNECT_FAILED, WifiP2pManager.ERROR); } // TODO: figure out updating the status to declined when invitation is rejected break; case WifiMonitor.P2P_INVITATION_RESULT_EVENT: P2pStatus status = (P2pStatus)message.obj; if (status == P2pStatus.SUCCESS) { // invocation was succeeded. break; } loge("Invitation result " + status); if (status == P2pStatus.UNKNOWN_P2P_GROUP) { // target device has already removed the credential. // So, remove this credential accordingly. int netId = mGroup.getNetworkId(); if (netId >= 0) { if (DBG) logd("Remove unknown client from the list"); if (!removeClientFromList(netId, mSavedPeerConfig.deviceAddress, false)) { // not found the client on the list loge("Already removed the client, ignore"); break; } // try invitation. sendMessage(WifiP2pManager.CONNECT, mSavedPeerConfig); } } break; case WifiMonitor.P2P_PROV_DISC_PBC_REQ_EVENT: case WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT: case WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT: WifiP2pProvDiscEvent provDisc = (WifiP2pProvDiscEvent) message.obj; mSavedPeerConfig = new WifiP2pConfig(); mSavedPeerConfig.deviceAddress = provDisc.device.deviceAddress; if (message.what == WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT) { mSavedPeerConfig.wps.setup = WpsInfo.KEYPAD; } else if (message.what == WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT) { mSavedPeerConfig.wps.setup = WpsInfo.DISPLAY; mSavedPeerConfig.wps.pin = provDisc.pin; } else { mSavedPeerConfig.wps.setup = WpsInfo.PBC; } - transitionTo(mUserAuthorizingJoinState); + if (DBG) logd("mGroup.isGroupOwner()" + mGroup.isGroupOwner()); + if (mGroup.isGroupOwner()) { + if (DBG) logd("Local device is Group Owner, transiting to mUserAuthorizingJoinState"); + transitionTo(mUserAuthorizingJoinState); + } break; case WifiMonitor.P2P_GROUP_STARTED_EVENT: loge("Duplicate group creation event notice, ignore"); break; default: return NOT_HANDLED; } return HANDLED; } public void exit() { updateThisDevice(WifiP2pDevice.AVAILABLE); resetWifiP2pInfo(); mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null); sendP2pConnectionChangedBroadcast(); } } class UserAuthorizingJoinState extends State { @Override public void enter() { if (DBG) logd(getName()); notifyInvitationReceived(); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { case WifiMonitor.P2P_PROV_DISC_PBC_REQ_EVENT: case WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT: case WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT: //Ignore more client requests break; case PEER_CONNECTION_USER_ACCEPT: //Stop discovery to avoid failure due to channel switch mWifiNative.p2pStopFind(); if (mSavedPeerConfig.wps.setup == WpsInfo.PBC) { mWifiNative.startWpsPbc(mGroup.getInterface(), null); } else { mWifiNative.startWpsPinKeypad(mGroup.getInterface(), mSavedPeerConfig.wps.pin); } transitionTo(mGroupCreatedState); break; case PEER_CONNECTION_USER_REJECT: if (DBG) logd("User rejected incoming request"); transitionTo(mGroupCreatedState); break; default: return NOT_HANDLED; } return HANDLED; } @Override public void exit() { //TODO: dismiss dialog if not already done } } class OngoingGroupRemovalState extends State { @Override public void enter() { if (DBG) logd(getName()); } @Override public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { // Group removal ongoing. Multiple calls // end up removing persisted network. Do nothing. case WifiP2pManager.REMOVE_GROUP: replyToMessage(message, WifiP2pManager.REMOVE_GROUP_SUCCEEDED); break; // Parent state will transition out of this state // when removal is complete default: return NOT_HANDLED; } return HANDLED; } } @Override public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { super.dump(fd, pw, args); pw.println("mWifiP2pInfo " + mWifiP2pInfo); pw.println("mGroup " + mGroup); pw.println("mSavedPeerConfig " + mSavedPeerConfig); pw.println("mSavedP2pGroup " + mSavedP2pGroup); pw.println(); } private void sendP2pStateChangedBroadcast(boolean enabled) { final Intent intent = new Intent(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); if (enabled) { intent.putExtra(WifiP2pManager.EXTRA_WIFI_STATE, WifiP2pManager.WIFI_P2P_STATE_ENABLED); } else { intent.putExtra(WifiP2pManager.EXTRA_WIFI_STATE, WifiP2pManager.WIFI_P2P_STATE_DISABLED); } mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); } private void sendP2pDiscoveryChangedBroadcast(boolean started) { if (mDiscoveryStarted == started) return; mDiscoveryStarted = started; if (DBG) logd("discovery change broadcast " + started); final Intent intent = new Intent(WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); intent.putExtra(WifiP2pManager.EXTRA_DISCOVERY_STATE, started ? WifiP2pManager.WIFI_P2P_DISCOVERY_STARTED : WifiP2pManager.WIFI_P2P_DISCOVERY_STOPPED); mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); } private void sendThisDeviceChangedBroadcast() { final Intent intent = new Intent(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); intent.putExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE, new WifiP2pDevice(mThisDevice)); mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); } private void sendPeersChangedBroadcast() { final Intent intent = new Intent(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); intent.putExtra(WifiP2pManager.EXTRA_P2P_DEVICE_LIST, new WifiP2pDeviceList(mPeers)); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); mContext.sendBroadcastAsUser(intent, UserHandle.ALL); } private void sendP2pConnectionChangedBroadcast() { if (DBG) logd("sending p2p connection changed broadcast"); Intent intent = new Intent(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | Intent.FLAG_RECEIVER_REPLACE_PENDING); intent.putExtra(WifiP2pManager.EXTRA_WIFI_P2P_INFO, new WifiP2pInfo(mWifiP2pInfo)); intent.putExtra(WifiP2pManager.EXTRA_NETWORK_INFO, new NetworkInfo(mNetworkInfo)); intent.putExtra(WifiP2pManager.EXTRA_WIFI_P2P_GROUP, new WifiP2pGroup(mGroup)); mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); mWifiChannel.sendMessage(WifiP2pService.P2P_CONNECTION_CHANGED, new NetworkInfo(mNetworkInfo)); } private void sendP2pPersistentGroupsChangedBroadcast() { if (DBG) logd("sending p2p persistent groups changed broadcast"); Intent intent = new Intent(WifiP2pManager.WIFI_P2P_PERSISTENT_GROUPS_CHANGED_ACTION); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); } private void startDhcpServer(String intf) { InterfaceConfiguration ifcg = null; try { ifcg = mNwService.getInterfaceConfig(intf); ifcg.setLinkAddress(new LinkAddress(NetworkUtils.numericToInetAddress( SERVER_ADDRESS), 24)); ifcg.setInterfaceUp(); mNwService.setInterfaceConfig(intf, ifcg); /* This starts the dnsmasq server */ mNwService.startTethering(DHCP_RANGE); } catch (Exception e) { loge("Error configuring interface " + intf + ", :" + e); return; } logd("Started Dhcp server on " + intf); } private void stopDhcpServer(String intf) { try { mNwService.stopTethering(); } catch (Exception e) { loge("Error stopping Dhcp server" + e); return; } logd("Stopped Dhcp server"); } private void notifyP2pEnableFailure() { Resources r = Resources.getSystem(); AlertDialog dialog = new AlertDialog.Builder(mContext) .setTitle(r.getString(R.string.wifi_p2p_dialog_title)) .setMessage(r.getString(R.string.wifi_p2p_failed_message)) .setPositiveButton(r.getString(R.string.ok), null) .create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); } private void addRowToDialog(ViewGroup group, int stringId, String value) { Resources r = Resources.getSystem(); View row = LayoutInflater.from(mContext).inflate(R.layout.wifi_p2p_dialog_row, group, false); ((TextView) row.findViewById(R.id.name)).setText(r.getString(stringId)); ((TextView) row.findViewById(R.id.value)).setText(value); group.addView(row); } private void notifyInvitationSent(String pin, String peerAddress) { Resources r = Resources.getSystem(); final View textEntryView = LayoutInflater.from(mContext) .inflate(R.layout.wifi_p2p_dialog, null); ViewGroup group = (ViewGroup) textEntryView.findViewById(R.id.info); addRowToDialog(group, R.string.wifi_p2p_to_message, getDeviceName(peerAddress)); addRowToDialog(group, R.string.wifi_p2p_show_pin_message, pin); AlertDialog dialog = new AlertDialog.Builder(mContext) .setTitle(r.getString(R.string.wifi_p2p_invitation_sent_title)) .setView(textEntryView) .setPositiveButton(r.getString(R.string.ok), null) .create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); } private void notifyInvitationReceived() { Resources r = Resources.getSystem(); final WpsInfo wps = mSavedPeerConfig.wps; final View textEntryView = LayoutInflater.from(mContext) .inflate(R.layout.wifi_p2p_dialog, null); ViewGroup group = (ViewGroup) textEntryView.findViewById(R.id.info); addRowToDialog(group, R.string.wifi_p2p_from_message, getDeviceName( mSavedPeerConfig.deviceAddress)); final EditText pin = (EditText) textEntryView.findViewById(R.id.wifi_p2p_wps_pin); AlertDialog dialog = new AlertDialog.Builder(mContext) .setTitle(r.getString(R.string.wifi_p2p_invitation_to_connect_title)) .setView(textEntryView) .setPositiveButton(r.getString(R.string.accept), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (wps.setup == WpsInfo.KEYPAD) { mSavedPeerConfig.wps.pin = pin.getText().toString(); } if (DBG) logd(getName() + " accept invitation " + mSavedPeerConfig); sendMessage(PEER_CONNECTION_USER_ACCEPT); } }) .setNegativeButton(r.getString(R.string.decline), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (DBG) logd(getName() + " ignore connect"); sendMessage(PEER_CONNECTION_USER_REJECT); } }) .setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface arg0) { if (DBG) logd(getName() + " ignore connect"); sendMessage(PEER_CONNECTION_USER_REJECT); } }) .create(); //make the enter pin area or the display pin area visible switch (wps.setup) { case WpsInfo.KEYPAD: if (DBG) logd("Enter pin section visible"); textEntryView.findViewById(R.id.enter_pin_section).setVisibility(View.VISIBLE); break; case WpsInfo.DISPLAY: if (DBG) logd("Shown pin section visible"); addRowToDialog(group, R.string.wifi_p2p_show_pin_message, wps.pin); break; default: break; } if ((r.getConfiguration().uiMode & Configuration.UI_MODE_TYPE_APPLIANCE) == Configuration.UI_MODE_TYPE_APPLIANCE) { // For appliance devices, add a key listener which accepts. dialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // TODO: make the actual key come from a config value. if (keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) { sendMessage(PEER_CONNECTION_USER_ACCEPT); dialog.dismiss(); return true; } return false; } }); // TODO: add timeout for this dialog. // TODO: update UI in appliance mode to tell user what to do. } dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); } /** * Synchronize the persistent group list between * wpa_supplicant and mGroups. */ private void updatePersistentNetworks(boolean reload) { String listStr = mWifiNative.listNetworks(); if (listStr == null) return; boolean isSaveRequired = false; String[] lines = listStr.split("\n"); if (lines == null) return; if (reload) mGroups.clear(); // Skip the first line, which is a header for (int i = 1; i < lines.length; i++) { String[] result = lines[i].split("\t"); if (result == null || result.length < 4) { continue; } // network-id | ssid | bssid | flags int netId = -1; String ssid = result[1]; String bssid = result[2]; String flags = result[3]; try { netId = Integer.parseInt(result[0]); } catch(NumberFormatException e) { e.printStackTrace(); continue; } if (flags.indexOf("[CURRENT]") != -1) { continue; } if (flags.indexOf("[P2P-PERSISTENT]") == -1) { /* * The unused profile is sometimes remained when the p2p group formation is failed. * So, we clean up the p2p group here. */ if (DBG) logd("clean up the unused persistent group. netId=" + netId); mWifiNative.removeNetwork(netId); isSaveRequired = true; continue; } if (mGroups.contains(netId)) { continue; } WifiP2pGroup group = new WifiP2pGroup(); group.setNetworkId(netId); group.setNetworkName(ssid); String mode = mWifiNative.getNetworkVariable(netId, "mode"); if (mode != null && mode.equals("3")) { group.setIsGroupOwner(true); } if (bssid.equalsIgnoreCase(mThisDevice.deviceAddress)) { group.setOwner(mThisDevice); } else { WifiP2pDevice device = new WifiP2pDevice(); device.deviceAddress = bssid; group.setOwner(device); } mGroups.add(group); isSaveRequired = true; } if (reload || isSaveRequired) { mWifiNative.saveConfig(); sendP2pPersistentGroupsChangedBroadcast(); } } /** * A config is valid if it has a peer address that has already been * discovered * @return true if it is invalid, false otherwise */ private boolean isConfigInvalid(WifiP2pConfig config) { if (config == null) return true; if (TextUtils.isEmpty(config.deviceAddress)) return true; if (mPeers.get(config.deviceAddress) == null) return true; return false; } /* TODO: The supplicant does not provide group capability changes as an event. * Having it pushed as an event would avoid polling for this information right * before a connection */ private WifiP2pDevice fetchCurrentDeviceDetails(WifiP2pConfig config) { /* Fetch & update group capability from supplicant on the device */ int gc = mWifiNative.getGroupCapability(config.deviceAddress); mPeers.updateGroupCapability(config.deviceAddress, gc); return mPeers.get(config.deviceAddress); } /** * Start a p2p group negotiation and display pin if necessary * @param config for the peer */ private void p2pConnectWithPinDisplay(WifiP2pConfig config) { WifiP2pDevice dev = fetchCurrentDeviceDetails(config); String pin = mWifiNative.p2pConnect(config, dev.isGroupOwner()); try { Integer.parseInt(pin); notifyInvitationSent(pin, config.deviceAddress); } catch (NumberFormatException ignore) { // do nothing if p2pConnect did not return a pin } } /** * Reinvoke a persistent group. * * @param config for the peer * @return true on success, false on failure */ private boolean reinvokePersistentGroup(WifiP2pConfig config) { WifiP2pDevice dev = fetchCurrentDeviceDetails(config); boolean join = dev.isGroupOwner(); String ssid = mWifiNative.p2pGetSsid(dev.deviceAddress); if (DBG) logd("target ssid is " + ssid + " join:" + join); if (join && dev.isGroupLimit()) { if (DBG) logd("target device reaches group limit."); // if the target group has reached the limit, // try group formation. join = false; } else if (join) { int netId = mGroups.getNetworkId(dev.deviceAddress, ssid); if (netId >= 0) { // Skip WPS and start 4way handshake immediately. if (!mWifiNative.p2pGroupAdd(netId)) { return false; } return true; } } if (!join && dev.isDeviceLimit()) { loge("target device reaches the device limit."); return false; } if (!join && dev.isInvitationCapable()) { int netId = WifiP2pGroup.PERSISTENT_NET_ID; if (config.netId >= 0) { if (config.deviceAddress.equals(mGroups.getOwnerAddr(config.netId))) { netId = config.netId; } } else { netId = mGroups.getNetworkId(dev.deviceAddress); } if (netId < 0) { netId = getNetworkIdFromClientList(dev.deviceAddress); } if (DBG) logd("netId related with " + dev.deviceAddress + " = " + netId); if (netId >= 0) { // Invoke the persistent group. if (mWifiNative.p2pReinvoke(netId, dev.deviceAddress)) { // Save network id. It'll be used when an invitation result event is received. config.netId = netId; return true; } else { loge("p2pReinvoke() failed, update networks"); updatePersistentNetworks(RELOAD); return false; } } } return false; } /** * Return the network id of the group owner profile which has the p2p client with * the specified device address in it's client list. * If more than one persistent group of the same address is present in its client * lists, return the first one. * * @param deviceAddress p2p device address. * @return the network id. if not found, return -1. */ private int getNetworkIdFromClientList(String deviceAddress) { if (deviceAddress == null) return -1; Collection<WifiP2pGroup> groups = mGroups.getGroupList(); for (WifiP2pGroup group : groups) { int netId = group.getNetworkId(); String[] p2pClientList = getClientList(netId); if (p2pClientList == null) continue; for (String client : p2pClientList) { if (deviceAddress.equalsIgnoreCase(client)) { return netId; } } } return -1; } /** * Return p2p client list associated with the specified network id. * @param netId network id. * @return p2p client list. if not found, return null. */ private String[] getClientList(int netId) { String p2pClients = mWifiNative.getNetworkVariable(netId, "p2p_client_list"); if (p2pClients == null) { return null; } return p2pClients.split(" "); } /** * Remove the specified p2p client from the specified profile. * @param netId network id of the profile. * @param addr p2p client address to be removed. * @param isRemovable if true, remove the specified profile if its client list becomes empty. * @return whether removing the specified p2p client is successful or not. */ private boolean removeClientFromList(int netId, String addr, boolean isRemovable) { StringBuilder modifiedClientList = new StringBuilder(); String[] currentClientList = getClientList(netId); boolean isClientRemoved = false; if (currentClientList != null) { for (String client : currentClientList) { if (!client.equalsIgnoreCase(addr)) { modifiedClientList.append(" "); modifiedClientList.append(client); } else { isClientRemoved = true; } } } if (modifiedClientList.length() == 0 && isRemovable) { // the client list is empty. so remove it. if (DBG) logd("Remove unknown network"); mGroups.remove(netId); return true; } if (!isClientRemoved) { // specified p2p client is not found. already removed. return false; } if (DBG) logd("Modified client list: " + modifiedClientList); if (modifiedClientList.length() == 0) { modifiedClientList.append("\"\""); } mWifiNative.setNetworkVariable(netId, "p2p_client_list", modifiedClientList.toString()); mWifiNative.saveConfig(); return true; } private void setWifiP2pInfoOnGroupFormation(InetAddress serverInetAddress) { mWifiP2pInfo.groupFormed = true; mWifiP2pInfo.isGroupOwner = mGroup.isGroupOwner(); mWifiP2pInfo.groupOwnerAddress = serverInetAddress; } private void resetWifiP2pInfo() { mWifiP2pInfo.groupFormed = false; mWifiP2pInfo.isGroupOwner = false; mWifiP2pInfo.groupOwnerAddress = null; } private String getDeviceName(String deviceAddress) { WifiP2pDevice d = mPeers.get(deviceAddress); if (d != null) { return d.deviceName; } //Treat the address as name if there is no match return deviceAddress; } private String getPersistedDeviceName() { String deviceName = Settings.Global.getString(mContext.getContentResolver(), Settings.Global.WIFI_P2P_DEVICE_NAME); if (deviceName == null) { /* We use the 4 digits of the ANDROID_ID to have a friendly * default that has low likelihood of collision with a peer */ String id = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID); return "Android_" + id.substring(0,4); } return deviceName; } private boolean setAndPersistDeviceName(String devName) { if (devName == null) return false; if (!mWifiNative.setDeviceName(devName)) { loge("Failed to set device name " + devName); return false; } mThisDevice.deviceName = devName; mWifiNative.setP2pSsidPostfix("-" + mThisDevice.deviceName); Settings.Global.putString(mContext.getContentResolver(), Settings.Global.WIFI_P2P_DEVICE_NAME, devName); sendThisDeviceChangedBroadcast(); return true; } private boolean setWfdInfo(WifiP2pWfdInfo wfdInfo) { boolean success; if (!wfdInfo.isWfdEnabled()) { success = mWifiNative.setWfdEnable(false); } else { success = mWifiNative.setWfdEnable(true) && mWifiNative.setWfdDeviceInfo(wfdInfo.getDeviceInfoHex()); } if (!success) { loge("Failed to set wfd properties"); return false; } mThisDevice.wfdInfo = wfdInfo; sendThisDeviceChangedBroadcast(); return true; } private void initializeP2pSettings() { mWifiNative.setPersistentReconnect(true); mThisDevice.deviceName = getPersistedDeviceName(); mWifiNative.setDeviceName(mThisDevice.deviceName); // DIRECT-XY-DEVICENAME (XY is randomly generated) mWifiNative.setP2pSsidPostfix("-" + mThisDevice.deviceName); mWifiNative.setDeviceType(mThisDevice.primaryDeviceType); // Supplicant defaults to using virtual display with display // which refers to a remote display. Use physical_display mWifiNative.setConfigMethods("virtual_push_button physical_display keypad"); // STA has higher priority over P2P mWifiNative.setConcurrencyPriority("sta"); mThisDevice.deviceAddress = mWifiNative.p2pGetDeviceAddress(); updateThisDevice(WifiP2pDevice.AVAILABLE); if (DBG) logd("DeviceAddress: " + mThisDevice.deviceAddress); mClientInfoList.clear(); mWifiNative.p2pFlush(); mWifiNative.p2pServiceFlush(); mServiceTransactionId = 0; mServiceDiscReqId = null; updatePersistentNetworks(RELOAD); } private void updateThisDevice(int status) { mThisDevice.status = status; sendThisDeviceChangedBroadcast(); } private void handleGroupCreationFailure() { resetWifiP2pInfo(); mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.FAILED, null, null); sendP2pConnectionChangedBroadcast(); // Remove only the peer we failed to connect to so that other devices discovered // that have not timed out still remain in list for connection boolean peersChanged = mPeers.remove(mPeersLostDuringConnection); if (mPeers.remove(mSavedPeerConfig.deviceAddress) != null) { peersChanged = true; } if (peersChanged) { sendPeersChangedBroadcast(); } mPeersLostDuringConnection.clear(); mServiceDiscReqId = null; sendMessage(WifiP2pManager.DISCOVER_PEERS); } private void handleGroupRemoved() { if (mGroup.isGroupOwner()) { stopDhcpServer(mGroup.getInterface()); } else { if (DBG) logd("stop DHCP client"); mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_STOP_DHCP); mDhcpStateMachine.doQuit(); mDhcpStateMachine = null; } try { mNwService.clearInterfaceAddresses(mGroup.getInterface()); } catch (Exception e) { loge("Failed to clear addresses " + e); } NetworkUtils.resetConnections(mGroup.getInterface(), NetworkUtils.RESET_ALL_ADDRESSES); // Clear any timeout that was set. This is essential for devices // that reuse the main p2p interface for a created group. mWifiNative.setP2pGroupIdle(mGroup.getInterface(), 0); boolean peersChanged = false; // Remove only peers part of the group, so that other devices discovered // that have not timed out still remain in list for connection for (WifiP2pDevice d : mGroup.getClientList()) { if (mPeers.remove(d)) peersChanged = true; } if (mPeers.remove(mGroup.getOwner())) peersChanged = true; if (mPeers.remove(mPeersLostDuringConnection)) peersChanged = true; if (peersChanged) { sendPeersChangedBroadcast(); } mGroup = null; mPeersLostDuringConnection.clear(); mServiceDiscReqId = null; if (mTempoarilyDisconnectedWifi) { mWifiChannel.sendMessage(WifiP2pService.DISCONNECT_WIFI_REQUEST, 0); mTempoarilyDisconnectedWifi = false; } } //State machine initiated requests can have replyTo set to null indicating //there are no recipients, we ignore those reply actions private void replyToMessage(Message msg, int what) { if (msg.replyTo == null) return; Message dstMsg = obtainMessage(msg); dstMsg.what = what; mReplyChannel.replyToMessage(msg, dstMsg); } private void replyToMessage(Message msg, int what, int arg1) { if (msg.replyTo == null) return; Message dstMsg = obtainMessage(msg); dstMsg.what = what; dstMsg.arg1 = arg1; mReplyChannel.replyToMessage(msg, dstMsg); } private void replyToMessage(Message msg, int what, Object obj) { if (msg.replyTo == null) return; Message dstMsg = obtainMessage(msg); dstMsg.what = what; dstMsg.obj = obj; mReplyChannel.replyToMessage(msg, dstMsg); } /* arg2 on the source message has a hash code that needs to be retained in replies * see WifiP2pManager for details */ private Message obtainMessage(Message srcMsg) { Message msg = Message.obtain(); msg.arg2 = srcMsg.arg2; return msg; } @Override protected void logd(String s) { Slog.d(TAG, s); } @Override protected void loge(String s) { Slog.e(TAG, s); } /** * Update service discovery request to wpa_supplicant. */ private boolean updateSupplicantServiceRequest() { clearSupplicantServiceRequest(); StringBuffer sb = new StringBuffer(); for (ClientInfo c: mClientInfoList.values()) { int key; WifiP2pServiceRequest req; for (int i=0; i < c.mReqList.size(); i++) { req = c.mReqList.valueAt(i); if (req != null) { sb.append(req.getSupplicantQuery()); } } } if (sb.length() == 0) { return false; } mServiceDiscReqId = mWifiNative.p2pServDiscReq("00:00:00:00:00:00", sb.toString()); if (mServiceDiscReqId == null) { return false; } return true; } /** * Clear service discovery request in wpa_supplicant */ private void clearSupplicantServiceRequest() { if (mServiceDiscReqId == null) return; mWifiNative.p2pServDiscCancelReq(mServiceDiscReqId); mServiceDiscReqId = null; } /* TODO: We could track individual service adds separately and avoid * having to do update all service requests on every new request */ private boolean addServiceRequest(Messenger m, WifiP2pServiceRequest req) { clearClientDeadChannels(); ClientInfo clientInfo = getClientInfo(m, true); if (clientInfo == null) { return false; } ++mServiceTransactionId; //The Wi-Fi p2p spec says transaction id should be non-zero if (mServiceTransactionId == 0) ++mServiceTransactionId; req.setTransactionId(mServiceTransactionId); clientInfo.mReqList.put(mServiceTransactionId, req); if (mServiceDiscReqId == null) { return true; } return updateSupplicantServiceRequest(); } private void removeServiceRequest(Messenger m, WifiP2pServiceRequest req) { ClientInfo clientInfo = getClientInfo(m, false); if (clientInfo == null) { return; } //Application does not have transaction id information //go through stored requests to remove boolean removed = false; for (int i=0; i<clientInfo.mReqList.size(); i++) { if (req.equals(clientInfo.mReqList.valueAt(i))) { removed = true; clientInfo.mReqList.removeAt(i); break; } } if (!removed) return; if (clientInfo.mReqList.size() == 0 && clientInfo.mServList.size() == 0) { if (DBG) logd("remove client information from framework"); mClientInfoList.remove(clientInfo.mMessenger); } if (mServiceDiscReqId == null) { return; } updateSupplicantServiceRequest(); } private void clearServiceRequests(Messenger m) { ClientInfo clientInfo = getClientInfo(m, false); if (clientInfo == null) { return; } if (clientInfo.mReqList.size() == 0) { return; } clientInfo.mReqList.clear(); if (clientInfo.mServList.size() == 0) { if (DBG) logd("remove channel information from framework"); mClientInfoList.remove(clientInfo.mMessenger); } if (mServiceDiscReqId == null) { return; } updateSupplicantServiceRequest(); } private boolean addLocalService(Messenger m, WifiP2pServiceInfo servInfo) { clearClientDeadChannels(); ClientInfo clientInfo = getClientInfo(m, true); if (clientInfo == null) { return false; } if (!clientInfo.mServList.add(servInfo)) { return false; } if (!mWifiNative.p2pServiceAdd(servInfo)) { clientInfo.mServList.remove(servInfo); return false; } return true; } private void removeLocalService(Messenger m, WifiP2pServiceInfo servInfo) { ClientInfo clientInfo = getClientInfo(m, false); if (clientInfo == null) { return; } mWifiNative.p2pServiceDel(servInfo); clientInfo.mServList.remove(servInfo); if (clientInfo.mReqList.size() == 0 && clientInfo.mServList.size() == 0) { if (DBG) logd("remove client information from framework"); mClientInfoList.remove(clientInfo.mMessenger); } } private void clearLocalServices(Messenger m) { ClientInfo clientInfo = getClientInfo(m, false); if (clientInfo == null) { return; } for (WifiP2pServiceInfo servInfo: clientInfo.mServList) { mWifiNative.p2pServiceDel(servInfo); } clientInfo.mServList.clear(); if (clientInfo.mReqList.size() == 0) { if (DBG) logd("remove client information from framework"); mClientInfoList.remove(clientInfo.mMessenger); } } private void clearClientInfo(Messenger m) { clearLocalServices(m); clearServiceRequests(m); } /** * Send the service response to the WifiP2pManager.Channel. * * @param resp */ private void sendServiceResponse(WifiP2pServiceResponse resp) { for (ClientInfo c : mClientInfoList.values()) { WifiP2pServiceRequest req = c.mReqList.get(resp.getTransactionId()); if (req != null) { Message msg = Message.obtain(); msg.what = WifiP2pManager.RESPONSE_SERVICE; msg.arg1 = 0; msg.arg2 = 0; msg.obj = resp; try { c.mMessenger.send(msg); } catch (RemoteException e) { if (DBG) logd("detect dead channel"); clearClientInfo(c.mMessenger); return; } } } } /** * We dont get notifications of clients that have gone away. * We detect this actively when services are added and throw * them away. * * TODO: This can be done better with full async channels. */ private void clearClientDeadChannels() { ArrayList<Messenger> deadClients = new ArrayList<Messenger>(); for (ClientInfo c : mClientInfoList.values()) { Message msg = Message.obtain(); msg.what = WifiP2pManager.PING; msg.arg1 = 0; msg.arg2 = 0; msg.obj = null; try { c.mMessenger.send(msg); } catch (RemoteException e) { if (DBG) logd("detect dead channel"); deadClients.add(c.mMessenger); } } for (Messenger m : deadClients) { clearClientInfo(m); } } /** * Return the specified ClientInfo. * @param m Messenger * @param createIfNotExist if true and the specified channel info does not exist, * create new client info. * @return the specified ClientInfo. */ private ClientInfo getClientInfo(Messenger m, boolean createIfNotExist) { ClientInfo clientInfo = mClientInfoList.get(m); if (clientInfo == null && createIfNotExist) { if (DBG) logd("add a new client"); clientInfo = new ClientInfo(m); mClientInfoList.put(m, clientInfo); } return clientInfo; } } /** * Information about a particular client and we track the service discovery requests * and the local services registered by the client. */ private class ClientInfo { /* * A reference to WifiP2pManager.Channel handler. * The response of this request is notified to WifiP2pManager.Channel handler */ private Messenger mMessenger; /* * A service discovery request list. */ private SparseArray<WifiP2pServiceRequest> mReqList; /* * A local service information list. */ private List<WifiP2pServiceInfo> mServList; private ClientInfo(Messenger m) { mMessenger = m; mReqList = new SparseArray(); mServList = new ArrayList<WifiP2pServiceInfo>(); } } }
true
true
public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { case WifiMonitor.AP_STA_CONNECTED_EVENT: WifiP2pDevice device = (WifiP2pDevice) message.obj; String deviceAddress = device.deviceAddress; // Clear timeout that was set when group was started. mWifiNative.setP2pGroupIdle(mGroup.getInterface(), 0); if (deviceAddress != null) { if (mPeers.get(deviceAddress) != null) { mGroup.addClient(mPeers.get(deviceAddress)); } else { mGroup.addClient(deviceAddress); } mPeers.updateStatus(deviceAddress, WifiP2pDevice.CONNECTED); if (DBG) logd(getName() + " ap sta connected"); sendPeersChangedBroadcast(); } else { loge("Connect on null device address, ignore"); } sendP2pConnectionChangedBroadcast(); break; case WifiMonitor.AP_STA_DISCONNECTED_EVENT: device = (WifiP2pDevice) message.obj; deviceAddress = device.deviceAddress; if (deviceAddress != null) { mPeers.updateStatus(deviceAddress, WifiP2pDevice.AVAILABLE); if (mGroup.removeClient(deviceAddress)) { if (DBG) logd("Removed client " + deviceAddress); if (!mAutonomousGroup && mGroup.isClientListEmpty()) { logd("Client list empty, remove non-persistent p2p group"); mWifiNative.p2pGroupRemove(mGroup.getInterface()); // We end up sending connection changed broadcast // when this happens at exit() } else { // Notify when a client disconnects from group sendP2pConnectionChangedBroadcast(); } } else { if (DBG) logd("Failed to remove client " + deviceAddress); for (WifiP2pDevice c : mGroup.getClientList()) { if (DBG) logd("client " + c.deviceAddress); } } sendPeersChangedBroadcast(); if (DBG) logd(getName() + " ap sta disconnected"); } else { loge("Disconnect on unknown device: " + device); } break; case DhcpStateMachine.CMD_POST_DHCP_ACTION: DhcpResults dhcpResults = (DhcpResults) message.obj; if (message.arg1 == DhcpStateMachine.DHCP_SUCCESS && dhcpResults != null) { if (DBG) logd("DhcpResults: " + dhcpResults); setWifiP2pInfoOnGroupFormation(dhcpResults.serverAddress); sendP2pConnectionChangedBroadcast(); //Turn on power save on client mWifiNative.setP2pPowerSave(mGroup.getInterface(), true); } else { loge("DHCP failed"); mWifiNative.p2pGroupRemove(mGroup.getInterface()); } break; case WifiP2pManager.REMOVE_GROUP: if (DBG) logd(getName() + " remove group"); if (mWifiNative.p2pGroupRemove(mGroup.getInterface())) { transitionTo(mOngoingGroupRemovalState); replyToMessage(message, WifiP2pManager.REMOVE_GROUP_SUCCEEDED); } else { handleGroupRemoved(); transitionTo(mInactiveState); replyToMessage(message, WifiP2pManager.REMOVE_GROUP_FAILED, WifiP2pManager.ERROR); } break; /* We do not listen to NETWORK_DISCONNECTION_EVENT for group removal * handling since supplicant actually tries to reconnect after a temporary * disconnect until group idle time out. Eventually, a group removal event * will come when group has been removed. * * When there are connectivity issues during temporary disconnect, the application * will also just remove the group. * * Treating network disconnection as group removal causes race conditions since * supplicant would still maintain the group at that stage. */ case WifiMonitor.P2P_GROUP_REMOVED_EVENT: if (DBG) logd(getName() + " group removed"); handleGroupRemoved(); transitionTo(mInactiveState); break; case WifiMonitor.P2P_DEVICE_LOST_EVENT: device = (WifiP2pDevice) message.obj; //Device loss for a connected device indicates it is not in discovery any more if (mGroup.contains(device)) { if (DBG) logd("Add device to lost list " + device); mPeersLostDuringConnection.updateSupplicantDetails(device); return HANDLED; } // Do the regular device lost handling return NOT_HANDLED; case WifiStateMachine.CMD_DISABLE_P2P_REQ: sendMessage(WifiP2pManager.REMOVE_GROUP); deferMessage(message); break; // This allows any client to join the GO during the // WPS window case WifiP2pManager.START_WPS: WpsInfo wps = (WpsInfo) message.obj; if (wps == null) { replyToMessage(message, WifiP2pManager.START_WPS_FAILED); break; } boolean ret = true; if (wps.setup == WpsInfo.PBC) { ret = mWifiNative.startWpsPbc(mGroup.getInterface(), null); } else { if (wps.pin == null) { String pin = mWifiNative.startWpsPinDisplay(mGroup.getInterface()); try { Integer.parseInt(pin); notifyInvitationSent(pin, "any"); } catch (NumberFormatException ignore) { ret = false; } } else { ret = mWifiNative.startWpsPinKeypad(mGroup.getInterface(), wps.pin); } } replyToMessage(message, ret ? WifiP2pManager.START_WPS_SUCCEEDED : WifiP2pManager.START_WPS_FAILED); break; case WifiP2pManager.CONNECT: WifiP2pConfig config = (WifiP2pConfig) message.obj; if (isConfigInvalid(config)) { loge("Dropping connect requeset " + config); replyToMessage(message, WifiP2pManager.CONNECT_FAILED); break; } logd("Inviting device : " + config.deviceAddress); mSavedPeerConfig = config; if (mWifiNative.p2pInvite(mGroup, config.deviceAddress)) { mPeers.updateStatus(config.deviceAddress, WifiP2pDevice.INVITED); sendPeersChangedBroadcast(); replyToMessage(message, WifiP2pManager.CONNECT_SUCCEEDED); } else { replyToMessage(message, WifiP2pManager.CONNECT_FAILED, WifiP2pManager.ERROR); } // TODO: figure out updating the status to declined when invitation is rejected break; case WifiMonitor.P2P_INVITATION_RESULT_EVENT: P2pStatus status = (P2pStatus)message.obj; if (status == P2pStatus.SUCCESS) { // invocation was succeeded. break; } loge("Invitation result " + status); if (status == P2pStatus.UNKNOWN_P2P_GROUP) { // target device has already removed the credential. // So, remove this credential accordingly. int netId = mGroup.getNetworkId(); if (netId >= 0) { if (DBG) logd("Remove unknown client from the list"); if (!removeClientFromList(netId, mSavedPeerConfig.deviceAddress, false)) { // not found the client on the list loge("Already removed the client, ignore"); break; } // try invitation. sendMessage(WifiP2pManager.CONNECT, mSavedPeerConfig); } } break; case WifiMonitor.P2P_PROV_DISC_PBC_REQ_EVENT: case WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT: case WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT: WifiP2pProvDiscEvent provDisc = (WifiP2pProvDiscEvent) message.obj; mSavedPeerConfig = new WifiP2pConfig(); mSavedPeerConfig.deviceAddress = provDisc.device.deviceAddress; if (message.what == WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT) { mSavedPeerConfig.wps.setup = WpsInfo.KEYPAD; } else if (message.what == WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT) { mSavedPeerConfig.wps.setup = WpsInfo.DISPLAY; mSavedPeerConfig.wps.pin = provDisc.pin; } else { mSavedPeerConfig.wps.setup = WpsInfo.PBC; } transitionTo(mUserAuthorizingJoinState); break; case WifiMonitor.P2P_GROUP_STARTED_EVENT: loge("Duplicate group creation event notice, ignore"); break; default: return NOT_HANDLED; } return HANDLED; }
public boolean processMessage(Message message) { if (DBG) logd(getName() + message.toString()); switch (message.what) { case WifiMonitor.AP_STA_CONNECTED_EVENT: WifiP2pDevice device = (WifiP2pDevice) message.obj; String deviceAddress = device.deviceAddress; // Clear timeout that was set when group was started. mWifiNative.setP2pGroupIdle(mGroup.getInterface(), 0); if (deviceAddress != null) { if (mPeers.get(deviceAddress) != null) { mGroup.addClient(mPeers.get(deviceAddress)); } else { mGroup.addClient(deviceAddress); } mPeers.updateStatus(deviceAddress, WifiP2pDevice.CONNECTED); if (DBG) logd(getName() + " ap sta connected"); sendPeersChangedBroadcast(); } else { loge("Connect on null device address, ignore"); } sendP2pConnectionChangedBroadcast(); break; case WifiMonitor.AP_STA_DISCONNECTED_EVENT: device = (WifiP2pDevice) message.obj; deviceAddress = device.deviceAddress; if (deviceAddress != null) { mPeers.updateStatus(deviceAddress, WifiP2pDevice.AVAILABLE); if (mGroup.removeClient(deviceAddress)) { if (DBG) logd("Removed client " + deviceAddress); if (!mAutonomousGroup && mGroup.isClientListEmpty()) { logd("Client list empty, remove non-persistent p2p group"); mWifiNative.p2pGroupRemove(mGroup.getInterface()); // We end up sending connection changed broadcast // when this happens at exit() } else { // Notify when a client disconnects from group sendP2pConnectionChangedBroadcast(); } } else { if (DBG) logd("Failed to remove client " + deviceAddress); for (WifiP2pDevice c : mGroup.getClientList()) { if (DBG) logd("client " + c.deviceAddress); } } sendPeersChangedBroadcast(); if (DBG) logd(getName() + " ap sta disconnected"); } else { loge("Disconnect on unknown device: " + device); } break; case DhcpStateMachine.CMD_POST_DHCP_ACTION: DhcpResults dhcpResults = (DhcpResults) message.obj; if (message.arg1 == DhcpStateMachine.DHCP_SUCCESS && dhcpResults != null) { if (DBG) logd("DhcpResults: " + dhcpResults); setWifiP2pInfoOnGroupFormation(dhcpResults.serverAddress); sendP2pConnectionChangedBroadcast(); //Turn on power save on client mWifiNative.setP2pPowerSave(mGroup.getInterface(), true); } else { loge("DHCP failed"); mWifiNative.p2pGroupRemove(mGroup.getInterface()); } break; case WifiP2pManager.REMOVE_GROUP: if (DBG) logd(getName() + " remove group"); if (mWifiNative.p2pGroupRemove(mGroup.getInterface())) { transitionTo(mOngoingGroupRemovalState); replyToMessage(message, WifiP2pManager.REMOVE_GROUP_SUCCEEDED); } else { handleGroupRemoved(); transitionTo(mInactiveState); replyToMessage(message, WifiP2pManager.REMOVE_GROUP_FAILED, WifiP2pManager.ERROR); } break; /* We do not listen to NETWORK_DISCONNECTION_EVENT for group removal * handling since supplicant actually tries to reconnect after a temporary * disconnect until group idle time out. Eventually, a group removal event * will come when group has been removed. * * When there are connectivity issues during temporary disconnect, the application * will also just remove the group. * * Treating network disconnection as group removal causes race conditions since * supplicant would still maintain the group at that stage. */ case WifiMonitor.P2P_GROUP_REMOVED_EVENT: if (DBG) logd(getName() + " group removed"); handleGroupRemoved(); transitionTo(mInactiveState); break; case WifiMonitor.P2P_DEVICE_LOST_EVENT: device = (WifiP2pDevice) message.obj; //Device loss for a connected device indicates it is not in discovery any more if (mGroup.contains(device)) { if (DBG) logd("Add device to lost list " + device); mPeersLostDuringConnection.updateSupplicantDetails(device); return HANDLED; } // Do the regular device lost handling return NOT_HANDLED; case WifiStateMachine.CMD_DISABLE_P2P_REQ: sendMessage(WifiP2pManager.REMOVE_GROUP); deferMessage(message); break; // This allows any client to join the GO during the // WPS window case WifiP2pManager.START_WPS: WpsInfo wps = (WpsInfo) message.obj; if (wps == null) { replyToMessage(message, WifiP2pManager.START_WPS_FAILED); break; } boolean ret = true; if (wps.setup == WpsInfo.PBC) { ret = mWifiNative.startWpsPbc(mGroup.getInterface(), null); } else { if (wps.pin == null) { String pin = mWifiNative.startWpsPinDisplay(mGroup.getInterface()); try { Integer.parseInt(pin); notifyInvitationSent(pin, "any"); } catch (NumberFormatException ignore) { ret = false; } } else { ret = mWifiNative.startWpsPinKeypad(mGroup.getInterface(), wps.pin); } } replyToMessage(message, ret ? WifiP2pManager.START_WPS_SUCCEEDED : WifiP2pManager.START_WPS_FAILED); break; case WifiP2pManager.CONNECT: WifiP2pConfig config = (WifiP2pConfig) message.obj; if (isConfigInvalid(config)) { loge("Dropping connect requeset " + config); replyToMessage(message, WifiP2pManager.CONNECT_FAILED); break; } logd("Inviting device : " + config.deviceAddress); mSavedPeerConfig = config; if (mWifiNative.p2pInvite(mGroup, config.deviceAddress)) { mPeers.updateStatus(config.deviceAddress, WifiP2pDevice.INVITED); sendPeersChangedBroadcast(); replyToMessage(message, WifiP2pManager.CONNECT_SUCCEEDED); } else { replyToMessage(message, WifiP2pManager.CONNECT_FAILED, WifiP2pManager.ERROR); } // TODO: figure out updating the status to declined when invitation is rejected break; case WifiMonitor.P2P_INVITATION_RESULT_EVENT: P2pStatus status = (P2pStatus)message.obj; if (status == P2pStatus.SUCCESS) { // invocation was succeeded. break; } loge("Invitation result " + status); if (status == P2pStatus.UNKNOWN_P2P_GROUP) { // target device has already removed the credential. // So, remove this credential accordingly. int netId = mGroup.getNetworkId(); if (netId >= 0) { if (DBG) logd("Remove unknown client from the list"); if (!removeClientFromList(netId, mSavedPeerConfig.deviceAddress, false)) { // not found the client on the list loge("Already removed the client, ignore"); break; } // try invitation. sendMessage(WifiP2pManager.CONNECT, mSavedPeerConfig); } } break; case WifiMonitor.P2P_PROV_DISC_PBC_REQ_EVENT: case WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT: case WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT: WifiP2pProvDiscEvent provDisc = (WifiP2pProvDiscEvent) message.obj; mSavedPeerConfig = new WifiP2pConfig(); mSavedPeerConfig.deviceAddress = provDisc.device.deviceAddress; if (message.what == WifiMonitor.P2P_PROV_DISC_ENTER_PIN_EVENT) { mSavedPeerConfig.wps.setup = WpsInfo.KEYPAD; } else if (message.what == WifiMonitor.P2P_PROV_DISC_SHOW_PIN_EVENT) { mSavedPeerConfig.wps.setup = WpsInfo.DISPLAY; mSavedPeerConfig.wps.pin = provDisc.pin; } else { mSavedPeerConfig.wps.setup = WpsInfo.PBC; } if (DBG) logd("mGroup.isGroupOwner()" + mGroup.isGroupOwner()); if (mGroup.isGroupOwner()) { if (DBG) logd("Local device is Group Owner, transiting to mUserAuthorizingJoinState"); transitionTo(mUserAuthorizingJoinState); } break; case WifiMonitor.P2P_GROUP_STARTED_EVENT: loge("Duplicate group creation event notice, ignore"); break; default: return NOT_HANDLED; } return HANDLED; }
diff --git a/src/test/java/org/nohope/app/spring/GetImplementationsTest.java b/src/test/java/org/nohope/app/spring/GetImplementationsTest.java index 9435ccf..dab2e8a 100644 --- a/src/test/java/org/nohope/app/spring/GetImplementationsTest.java +++ b/src/test/java/org/nohope/app/spring/GetImplementationsTest.java @@ -1,70 +1,70 @@ package org.nohope.app.spring; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Test; import org.junit.matchers.JUnitMatchers; import java.util.ArrayList; import java.util.List; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertThat; /** * Date: 30.07.12 * Time: 17:41 */ public class GetImplementationsTest { private interface Iface { } private interface Marker1 { } private interface Marker2 { } @Test public void testGetImpl() { final List<ModuleDescriptor<Iface>> allModules = new ArrayList<>(); class M1Impl implements Marker1, Iface { } class M2Impl implements Marker2, Iface { } allModules.add(new ModuleDescriptor<Iface>("M1-1", new M1Impl() { }, null)); allModules.add(new ModuleDescriptor<Iface>("M1-2", new M1Impl() { }, null)); allModules.add(new ModuleDescriptor<Iface>("M2-1", new M2Impl() { }, null)); allModules.add(new ModuleDescriptor<Iface>("M2-2", new M2Impl() { }, null)); - List<Marker1> lst = SpringAsyncModularAppWithModuleStorage.getImplementations(Marker1.class, allModules); + final List<Marker1> lst = SpringAsyncModularAppWithModuleStorage.getImplementations(Marker1.class, allModules); assertEquals(2, lst.size()); assertThat(lst, JUnitMatchers.everyItem(new BaseMatcher<Marker1>() { @Override public boolean matches(final Object o) { return o instanceof M1Impl; } @Override public void describeTo(final Description description) { description.appendText("Something"); } })); } }
true
true
public void testGetImpl() { final List<ModuleDescriptor<Iface>> allModules = new ArrayList<>(); class M1Impl implements Marker1, Iface { } class M2Impl implements Marker2, Iface { } allModules.add(new ModuleDescriptor<Iface>("M1-1", new M1Impl() { }, null)); allModules.add(new ModuleDescriptor<Iface>("M1-2", new M1Impl() { }, null)); allModules.add(new ModuleDescriptor<Iface>("M2-1", new M2Impl() { }, null)); allModules.add(new ModuleDescriptor<Iface>("M2-2", new M2Impl() { }, null)); List<Marker1> lst = SpringAsyncModularAppWithModuleStorage.getImplementations(Marker1.class, allModules); assertEquals(2, lst.size()); assertThat(lst, JUnitMatchers.everyItem(new BaseMatcher<Marker1>() { @Override public boolean matches(final Object o) { return o instanceof M1Impl; } @Override public void describeTo(final Description description) { description.appendText("Something"); } })); }
public void testGetImpl() { final List<ModuleDescriptor<Iface>> allModules = new ArrayList<>(); class M1Impl implements Marker1, Iface { } class M2Impl implements Marker2, Iface { } allModules.add(new ModuleDescriptor<Iface>("M1-1", new M1Impl() { }, null)); allModules.add(new ModuleDescriptor<Iface>("M1-2", new M1Impl() { }, null)); allModules.add(new ModuleDescriptor<Iface>("M2-1", new M2Impl() { }, null)); allModules.add(new ModuleDescriptor<Iface>("M2-2", new M2Impl() { }, null)); final List<Marker1> lst = SpringAsyncModularAppWithModuleStorage.getImplementations(Marker1.class, allModules); assertEquals(2, lst.size()); assertThat(lst, JUnitMatchers.everyItem(new BaseMatcher<Marker1>() { @Override public boolean matches(final Object o) { return o instanceof M1Impl; } @Override public void describeTo(final Description description) { description.appendText("Something"); } })); }
diff --git a/code/uci/pacman/multiplayer/Server.java b/code/uci/pacman/multiplayer/Server.java index 5a222ca..a2d51a9 100644 --- a/code/uci/pacman/multiplayer/Server.java +++ b/code/uci/pacman/multiplayer/Server.java @@ -1,246 +1,246 @@ package code.uci.pacman.multiplayer; import code.uci.pacman.game.*; import java.io.*; import java.net.*; import java.util.*; /// COMMAND ENUMS enum PType { JOIN, // (duh) GTYPE, // GHOST_TYPE (Tells the ghost what ghost he will be) GMOVE, // DIR, GHOST_TYPE (tells the direction and what ghost to move) PMOVE, // DIR ( direction of pacman) GAMEOVER, // (duh) LEAVE, // GHOST_TYPE (tells the server to drop the ghost) GAMEFULL, // (tells a client that the game is full) GAMESTART // (duh) }; // The ghost type enum GhostType { BLINKY,CLYDE,INKY,PINKY }; /** * Server is responsible for handling incoming client requests. * @author Networking Team * */ public class Server extends Thread { private static final long serialVersionUID = 1L; protected DatagramSocket socket = null; protected static ArrayList<InetAddress> clients; private static InetAddress localAddr; protected boolean moreQuotes = true; /** * Starts the Server. * @throws IOException */ public Server() throws IOException { this("Server"); } /** * Starts a server at socket 4445 * @param name unknown * @throws IOException */ public Server(String name) throws IOException { super(name); socket = new DatagramSocket(4445); Server.clients = new ArrayList<InetAddress>(); // We first fill the list up with fake stuff as a placeholder Server.localAddr = InetAddress.getByName("127.0.0.1"); Server.clients.add(localAddr); Server.clients.add(localAddr); Server.clients.add(localAddr); Server.clients.add(localAddr); System.out.println("START SERVER"); } // a single command /** * Sends a command * @param type the command to send out */ public static void send(PType type) { byte[] buf = new byte[4]; buf[0] = new Integer(type.ordinal()).byteValue(); Server.sendData(buf); } /** * Sends a command * @param ghost the type of ghost * @param dir the direction its moving */ public static void send(GhostType ghost, Direction dir) { byte[] buf = new byte[4]; buf[0] = new Integer(PType.GMOVE.ordinal()).byteValue(); // TYPE buf[1] = new Integer(dir.ordinal()).byteValue(); // DIRECTION buf[2] = new Integer(ghost.ordinal()).byteValue(); // GHOST_TYPE Server.sendData(buf); } /** * Used for moving pacman * @param dir the direction pacman is moving */ public static void send(Direction dir) { byte[] buf = new byte[4]; buf[0] = new Integer(PType.PMOVE.ordinal()).byteValue(); buf[1] = new Integer(dir.ordinal()).byteValue(); Server.sendData(buf); } /** * Sends a command * @param type the type of command to send * @param dir the direction command to send */ public static void send(PType type, Direction dir) { byte[] buf = new byte[4]; buf[0] = new Integer(type.ordinal()).byteValue(); buf[1] = new Integer(dir.ordinal()).byteValue(); Server.sendData(buf); } private static void sendData(byte[] buf) { for(int i=0; i < Server.clients.size(); i++) { Server.sendClientData(i, buf); } } // sends raw data to a client private static void sendClientData(InetAddress addr, byte[] buf) { if( !Server.localAddr.equals( addr ) ) { try { DatagramSocket socketSend = new DatagramSocket(); DatagramPacket packet = new DatagramPacket(buf, buf.length, addr, 4445); socketSend.send(packet); socketSend.close(); } catch(Exception e) { // they failed out, so remove from player table Server.clients.remove(addr); } } } // just an alias private static void sendClientData(int clientID, byte[] buf) { sendClientData( Server.clients.get(clientID), buf); } /** * runs the server */ public void run() { // should be while game is not over while (moreQuotes) { try { byte[] buf = new byte[4]; byte[] bufOut = new byte[4]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); buf = packet.getData(); // get client address InetAddress address = packet.getAddress(); // get the packet type int packetType = buf[0] & 0x000000FF; int data1 = buf[1] & 0x000000FF; int data2 = buf[2] & 0x000000FF; int data3 = buf[3] & 0x000000FF; if( PType.JOIN.ordinal() == packetType ) { System.out.println("JOIN"); if( Server.clients.contains(Server.localAddr) ) { // find the next slot available int localIndex = Server.clients.indexOf(Server.localAddr); // get their address // build the packet bufOut[0] = new Integer( PType.GTYPE.ordinal() ).byteValue(); bufOut[1] = new Integer( localIndex ).byteValue(); Server.clients.set( localIndex, address ); sendClientData( address, bufOut ); } else { // game is full bufOut[0] = new Integer( PType.GAMEFULL.ordinal() ).byteValue(); sendClientData( address, bufOut ); } } else if( PType.GMOVE.ordinal() == packetType ) { // a ghost move } else if( PType.LEAVE.ordinal() == packetType ) { // a ghost is leaving } else { // some other junk packet - System.out.println("UNKNOWN"); + System.out.println("UNKNOWN("+packetType+")"); } // figure out response /*String dString = null; dString = new Date().toString(); buf = dString.getBytes(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet);*/ } catch (IOException e) { e.printStackTrace(); moreQuotes = false; } } System.out.println("Server Shutdown"); socket.close(); }//run }
true
true
public void run() { // should be while game is not over while (moreQuotes) { try { byte[] buf = new byte[4]; byte[] bufOut = new byte[4]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); buf = packet.getData(); // get client address InetAddress address = packet.getAddress(); // get the packet type int packetType = buf[0] & 0x000000FF; int data1 = buf[1] & 0x000000FF; int data2 = buf[2] & 0x000000FF; int data3 = buf[3] & 0x000000FF; if( PType.JOIN.ordinal() == packetType ) { System.out.println("JOIN"); if( Server.clients.contains(Server.localAddr) ) { // find the next slot available int localIndex = Server.clients.indexOf(Server.localAddr); // get their address // build the packet bufOut[0] = new Integer( PType.GTYPE.ordinal() ).byteValue(); bufOut[1] = new Integer( localIndex ).byteValue(); Server.clients.set( localIndex, address ); sendClientData( address, bufOut ); } else { // game is full bufOut[0] = new Integer( PType.GAMEFULL.ordinal() ).byteValue(); sendClientData( address, bufOut ); } } else if( PType.GMOVE.ordinal() == packetType ) { // a ghost move } else if( PType.LEAVE.ordinal() == packetType ) { // a ghost is leaving } else { // some other junk packet System.out.println("UNKNOWN"); } // figure out response /*String dString = null; dString = new Date().toString(); buf = dString.getBytes(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet);*/ } catch (IOException e) { e.printStackTrace(); moreQuotes = false; } } System.out.println("Server Shutdown"); socket.close(); }//run
public void run() { // should be while game is not over while (moreQuotes) { try { byte[] buf = new byte[4]; byte[] bufOut = new byte[4]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); buf = packet.getData(); // get client address InetAddress address = packet.getAddress(); // get the packet type int packetType = buf[0] & 0x000000FF; int data1 = buf[1] & 0x000000FF; int data2 = buf[2] & 0x000000FF; int data3 = buf[3] & 0x000000FF; if( PType.JOIN.ordinal() == packetType ) { System.out.println("JOIN"); if( Server.clients.contains(Server.localAddr) ) { // find the next slot available int localIndex = Server.clients.indexOf(Server.localAddr); // get their address // build the packet bufOut[0] = new Integer( PType.GTYPE.ordinal() ).byteValue(); bufOut[1] = new Integer( localIndex ).byteValue(); Server.clients.set( localIndex, address ); sendClientData( address, bufOut ); } else { // game is full bufOut[0] = new Integer( PType.GAMEFULL.ordinal() ).byteValue(); sendClientData( address, bufOut ); } } else if( PType.GMOVE.ordinal() == packetType ) { // a ghost move } else if( PType.LEAVE.ordinal() == packetType ) { // a ghost is leaving } else { // some other junk packet System.out.println("UNKNOWN("+packetType+")"); } // figure out response /*String dString = null; dString = new Date().toString(); buf = dString.getBytes(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet);*/ } catch (IOException e) { e.printStackTrace(); moreQuotes = false; } } System.out.println("Server Shutdown"); socket.close(); }//run
diff --git a/source/RMG/jing/rxnSys/RateBasedRME.java b/source/RMG/jing/rxnSys/RateBasedRME.java index fb9c3b2c..722019b9 100644 --- a/source/RMG/jing/rxnSys/RateBasedRME.java +++ b/source/RMG/jing/rxnSys/RateBasedRME.java @@ -1,500 +1,500 @@ //////////////////////////////////////////////////////////////////////////////// // // RMG - Reaction Mechanism Generator // // Copyright (c) 2002-2009 Prof. William H. Green ([email protected]) and the // RMG Team ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //////////////////////////////////////////////////////////////////////////////// package jing.rxnSys; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import jing.param.*; import jing.rxn.NegativeRateException; import jing.rxn.Reaction; import jing.rxn.Structure; import jing.rxn.TemplateReaction; import jing.chem.ChemGraph; import jing.chem.Species; import jing.rxnSys.SpeciesStatus; import jing.chem.SpeciesDictionary; //import RMG; //## package jing::rxnSys //---------------------------------------------------------------------------- // jing\rxnSys\RateBasedRME.java //---------------------------------------------------------------------------- //## class RateBasedRME public class RateBasedRME implements ReactionModelEnlarger { protected HashSet includeSpecies = null; //these species are included into the core even if they have very //low flux. // Constructors public RateBasedRME() { } public void addIncludeSpecies(HashSet p_includeSpecies){ if (includeSpecies == null) { includeSpecies = p_includeSpecies; } else { System.out.println("IncludeSpecies have already been added!!"); System.exit(0); } } //9/25/07 gmagoon: added ReactionModel parameter //10/30/07 gmagoon: updated parameters to match ReactionModelEnlarger //## operation enlargeReactionModel(ReactionSystem) public void enlargeReactionModel(LinkedList p_reactionSystemList, ReactionModel rm, LinkedList p_validList){ //public void enlargeReactionModel(ReactionSystem p_reactionSystem, ReactionModel rm) //#[ operation enlargeReactionModel(ReactionSystem) //ReactionModel rm = p_reactionSystem.getReactionModel(); if (!(rm instanceof CoreEdgeReactionModel)) throw new InvalidReactionModelTypeException(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm; //10/30/07 gmagoon: iterate over reaction systems that are not valid LinkedList nextList = new LinkedList(); double startTime = System.currentTimeMillis(); for (Integer i = 0; i < p_reactionSystemList.size(); i++) { if (!(Boolean) p_validList.get(i)) { PresentStatus ps = ((ReactionSystem) p_reactionSystemList.get(i)).getPresentStatus(); String maxflux = ""; Species next = getNextCandidateSpecies(cerm, ps, maxflux); nextList.add(next); } else { nextList.add(null);//****hopefully, null will contribute to length of list; otherwise, modifications will be needed } } // generate new reaction set /*startTime = System.currentTimeMillis(); LinkedHashSet newReactionSet = p_reactionSystem.lrg.react(cerm.getReactedSpeciesSet(),next); newReactionSet.addAll(p_reactionSystem.getReactionGenerator().react(cerm.getReactedSpeciesSet(),next)); double enlargeTime = (System.currentTimeMillis()-startTime)/1000/60;*/ startTime = System.currentTimeMillis(); //10/30/07 gmagoon: add species from nextList for (Integer i = 0; i < p_reactionSystemList.size(); i++) { if (!(Boolean) p_validList.get(i)) { Species newCoreSpecies = (Species) nextList.get(i); if (cerm.containsAsReactedSpecies(newCoreSpecies)) //throw new InvalidNextCandidateSpeciesException(); { System.out.println("Species " + newCoreSpecies.getName() + "(" + Integer.toString(newCoreSpecies.getID()) + ") is already present in reaction model"); } else { double findSpeciesTime = (System.currentTimeMillis() - startTime) / 1000 / 60; //Global.diagnosticInfo.append(next.getChemkinName() + "\t" + maxflux + "\t" + ((RateBasedVT) ((ReactionSystem) p_reactionSystemList.get(i)).finishController.validityTester).Rmin + "\t" + findSpeciesTime + "\t"); System.out.print("\nAdd a new reacted Species:"); System.out.println(newCoreSpecies.getName()); Temperature temp = new Temperature(298, "K"); double H = newCoreSpecies.calculateH(temp); double S = newCoreSpecies.calculateS(temp); double G = newCoreSpecies.calculateG(temp); double Cp = newCoreSpecies.calculateCp(temp); System.out.println("Thermo of species at 298K (H, S, G, Cp, respectively)\t" + String.valueOf(H) + '\t' + String.valueOf(S) + '\t' + String.valueOf(G) + '\t' + String.valueOf(Cp)); cerm.moveFromUnreactedToReactedSpecies(newCoreSpecies); cerm.moveFromUnreactedToReactedReaction(); Global.moveUnreactedToReacted = (System.currentTimeMillis() - startTime) / 1000 / 60; // add species status to reaction system SpeciesStatus speciesStatus = new SpeciesStatus(newCoreSpecies, 1, 0.0, 0.0); // (species, type (reacted=1), concentration, flux) PresentStatus ps = ((ReactionSystem) p_reactionSystemList.get(i)).getPresentStatus(); ps.putSpeciesStatus(speciesStatus); // generate new reaction set startTime = System.currentTimeMillis(); // Species List is first reacted by Library Reaction Generator and then sent to RMG Model Generator // Check Reaction Library ReactionSystem rxnSystem = (ReactionSystem) p_reactionSystemList.get(i); - System.out.println("Checking Reaction Library "+rxnSystem.getLibraryReactionGenerator().getReactionLibrary().getName()+" for reactions of "+newCoreSpecies.getName()+" with the core."); + System.out.println("Checking Reaction Library for reactions of "+newCoreSpecies.getName()+" with the core."); // At this point the core (cerm.getReactedSpeciesSet()) already contains newCoreSpecies, so we can just react the entire core. LinkedHashSet newReactionSet = rxnSystem.getLibraryReactionGenerator().react(cerm.getReactedSpeciesSet()); //LinkedHashSet newReactionSet = rxnSystem.getLibraryReactionGenerator().react(cerm.getReactedSpeciesSet(),newCoreSpecies,"All"); // Report only those that contain the new species (newCoreSpecies) Iterator ReactionIter = newReactionSet.iterator(); while(ReactionIter.hasNext()){ Reaction current_reaction = (Reaction)ReactionIter.next(); if (current_reaction.contains(newCoreSpecies)) { System.out.println("Library Reaction: " + current_reaction.toString() ); } } // Calls in Reaction Model Generator and adds it to Reaction Set ( if duplicate reaction is found it is not added I think ) System.out.println("Generating reactions using reaction family templates."); // Add reactions found from reaction template to current reaction set newReactionSet.addAll(((ReactionSystem) p_reactionSystemList.get(i)).getReactionGenerator().react(cerm.getReactedSpeciesSet(), newCoreSpecies, "All")); // shamel 6/22/2010 Suppressed output , line is only for debugging //System.out.println("Reaction Set Found after LRG + ReactionGenerator call "+newReactionSet); // Remove Duplicate entrys from reaction set i.e same reaction might be coming from seed/reaction library and reaction template // Same means == same family and not same structure coming from different families LinkedHashSet newReactionSet_nodup = RemoveDuplicateReac(newReactionSet); // shamel 6/22/2010 Suppressed output , line is only for debugging //System.out.println("Reaction Set Found after LRG + ReactionGenerator call and Removing Dups"+newReactionSet_nodup); double enlargeTime = (System.currentTimeMillis() - startTime) / 1000 / 60; startTime = System.currentTimeMillis(); double restartTime = (System.currentTimeMillis() - startTime) / 1000 / 60; Global.diagnosticInfo.append(Global.moveUnreactedToReacted + "\t" + enlargeTime + "\t" + restartTime + "\t"); // partition the reaction set into reacted reaction set and unreacted reaction set // update the corresponding core and edge model of CoreEdgeReactionModel cerm.addReactionSet(newReactionSet_nodup); } } } return; } public LinkedHashSet RemoveDuplicateReac(LinkedHashSet reaction_set){ // Get the reactants and products of a reaction and check with other reaction if both reactants and products // match - delete duplicate entry, give preference to Seed Mechanism > Reaction Library > Reaction Template // this information might be available from the comments LinkedHashSet newreaction_set = new LinkedHashSet(); Iterator iter_reaction =reaction_set.iterator(); Reaction current_reaction; while(iter_reaction.hasNext()){ // Cast it into a Reaction ( i.e pick the reaction ) current_reaction = (Reaction)iter_reaction.next(); // To remove current reaction from reaction_set reaction_set.remove(current_reaction); // Match Current Reaction with the reaction set and if a duplicate reaction is found remove that reaction LinkedHashSet dupreaction_set = dupreaction(reaction_set,current_reaction); // Remove the duplicate reaction from reaction set reaction_set.removeAll(dupreaction_set); // If duplicate reaction set was not empty if(!dupreaction_set.isEmpty()){ // Add current reaction to duplicate set and from among this choose reaction according to // following hierarchy Seed > Reaction Library > Template. Add that reaction to the newreaction_set // Add current_reaction to duplicate set dupreaction_set.add(current_reaction); // Get Reaction according to hierarchy LinkedHashSet reaction_toadd = reaction_add(dupreaction_set); // Add all the Reactions to be kept to new_reaction set newreaction_set.addAll(reaction_toadd); } else{ // If no duplicate reaction was found add the current reaction to the newreaction set newreaction_set.add(current_reaction); } // Need to change iterate over counter here iter_reaction =reaction_set.iterator(); } return newreaction_set; } public LinkedHashSet reaction_add(LinkedHashSet reaction_set){ Reaction current_reaction; Iterator iter_reaction = reaction_set.iterator(); LinkedHashSet reaction_seedset = new LinkedHashSet(); LinkedHashSet reaction_rlset = new LinkedHashSet(); LinkedHashSet reaction_trset = new LinkedHashSet(); while(iter_reaction.hasNext()){ // Cast it into a Reaction ( i.e pick the reaction ) current_reaction = (Reaction)iter_reaction.next(); // As I cant call the instance test as I have casted my reaction as a Reaction // I will use the source (comments) to find whether a reaction is from Seed Mechanism // Reaction Library or Template Reaction String source = current_reaction.getKineticsSource(0); //System.out.println("Source"+source); if (source == null){ // If source is null I am assuming that its not a Reaction from Reaction Library or Seed Mechanism source = "TemplateReaction:"; } // To grab the First word from the source of the comment // As we have Reaction_Type:, we will use : as our string tokenizer StringTokenizer st = new StringTokenizer(source,":"); String reaction_type = st.nextToken(); // shamel: Cant think of more elegant way for now // Splitting the set into Reactions from Seed Mechanism/Reaction Library and otherwise Template Reaction if (reaction_type.equals( "SeedMechanism")){ // Add to seed mechanism set reaction_seedset.add(current_reaction); } else if (reaction_type.equals("ReactionLibrary") ){ // Add to reaction library set reaction_rlset.add(current_reaction); } else{ // Add to template reaction set reaction_trset.add(current_reaction); } } if(!reaction_seedset.isEmpty()){ // shamel: 6/10/2010 Debug lines //System.out.println("Reaction Set Being Returned"+reaction_seedset); return reaction_seedset; } else if(!reaction_rlset.isEmpty()){ //System.out.println("Reaction Set Being Returned in RatebasedRME"+reaction_rlset); return reaction_rlset; } else{ //System.out.println("Reaction Set Being Returned"+reaction_trset); return reaction_trset; } } public LinkedHashSet dupreaction(LinkedHashSet reaction_set, Reaction test_reaction){ // Iterate over the reaction set and find if a duplicate reaction exist for the the test reaction LinkedHashSet dupreaction_set = new LinkedHashSet(); Iterator iter_reaction =reaction_set.iterator(); Reaction current_reaction; // we will test if reaction are equal by structure test here, structure dosent require kinetics // Get Structure of test reaction Structure test_reactionstructure = test_reaction.getStructure(); // Get reverse structure of test reaction Structure test_reactionstructure_rev = test_reactionstructure.generateReverseStructure(); while(iter_reaction.hasNext()){ // Cast it into a Reaction ( i.e pick the reaction ) current_reaction = (Reaction)iter_reaction.next(); // Get Structure of current reaction to be tested for equality to test reaction Structure current_reactionstructure = current_reaction.getStructure(); // Check if Current Reaction Structure matches the Fwd Structure of Test Reaction if(current_reactionstructure.equals(test_reactionstructure)){ dupreaction_set.add(current_reaction); } // Check if Current Reaction Structure matches the Reverse Structure of Test Reaction if(current_reactionstructure.equals(test_reactionstructure_rev)){ dupreaction_set.add(current_reaction); } } // Print out the dupreaction set if not empty if(!dupreaction_set.isEmpty()){ System.out.println("dupreaction_set" + dupreaction_set); } // Return the duplicate reaction set return dupreaction_set; } public boolean presentInIncludedSpecies(Species p_species){ Iterator iter = includeSpecies.iterator(); while (iter.hasNext()){ Species spe = (Species)iter.next(); Iterator isomers = spe.getResonanceIsomers(); while (isomers.hasNext()){ ChemGraph cg = (ChemGraph)isomers.next(); if (cg.equals(p_species.getChemGraph())) return true; } } return false; } //## operation getNextCandidateSpecies(CoreEdgeReactionModel,PresentStatus) public Species getNextCandidateSpecies(CoreEdgeReactionModel p_reactionModel, PresentStatus p_presentStatus, String maxflux) { //#[ operation getNextCandidateSpecies(CoreEdgeReactionModel,PresentStatus) LinkedHashSet unreactedSpecies = p_reactionModel.getUnreactedSpeciesSet(); Species maxSpecies = null; double maxFlux = 0; Species maxIncludedSpecies = null; double maxIncludedFlux = 0; Iterator iter = unreactedSpecies.iterator(); while (iter.hasNext()) { Species us = (Species)iter.next(); //double thisFlux = Math.abs(p_presentStatus.getSpeciesStatus(us).getFlux()); //System.out.println(p_presentStatus.unreactedSpeciesFlux[83]); //System.exit(0); double thisFlux = Math.abs(p_presentStatus.unreactedSpeciesFlux[us.getID()]); if (includeSpecies != null && includeSpecies.contains(us)) { if (thisFlux > maxIncludedFlux) { maxIncludedFlux = thisFlux; maxIncludedSpecies = us; } } else { if (thisFlux > maxFlux) { maxFlux = thisFlux; maxSpecies = us; } } } if (maxIncludedSpecies != null){ System.out.println("Instead of "+maxSpecies.toChemkinString()+" with flux "+ maxFlux + " "+ maxIncludedSpecies.toChemkinString() +" with flux " + maxIncludedFlux); maxFlux = maxIncludedFlux; maxSpecies = maxIncludedSpecies; includeSpecies.remove(maxIncludedSpecies); } maxflux = ""+maxFlux; if (maxSpecies == null) throw new NullPointerException(); LinkedHashSet ur = p_reactionModel.getUnreactedReactionSet(); HashMap significantReactions = new HashMap(); int reactionWithSpecies = 0; for (Iterator iur = ur.iterator(); iur.hasNext();) { Reaction r = (Reaction)iur.next(); double flux = 0; Temperature p_temperature = p_presentStatus.temperature; Pressure p_pressure = p_presentStatus.pressure;//10/30/07 gmagoon: added if (r.contains(maxSpecies)){ reactionWithSpecies++; if (r instanceof TemplateReaction) { flux = ((TemplateReaction)r).calculateTotalPDepRate(p_temperature, p_pressure);//10/30/07 gmagoon: changed to include pressure //flux = ((TemplateReaction)r).calculateTotalPDepRate(p_temperature); } else { flux = r.calculateTotalRate(p_temperature); } if (flux > 0) { for (Iterator rIter=r.getReactants(); rIter.hasNext();) { Species spe = (Species)rIter.next(); SpeciesStatus status = p_presentStatus.getSpeciesStatus(spe); if (status == null) flux = 0; else { double conc = status.getConcentration(); if (conc<0) { double aTol = ReactionModelGenerator.getAtol(); //if (Math.abs(conc) < aTol) conc = 0; //else throw new NegativeConcentrationException(spe.getName() + ": " + String.valueOf(conc)); if (conc < -100.0 * aTol) throw new NegativeConcentrationException("Species " + spe.getName() + " has negative concentration: " + String.valueOf(conc)); } flux *= conc; } } } else { throw new NegativeRateException(r.toChemkinString(p_temperature) + ": " + String.valueOf(flux));//10/30/07 gmagoon: changed to avoid use of Global.temperature //throw new NegativeRateException(r.toChemkinString(Global.temperature) + ": " + String.valueOf(flux)); } if (flux > 0.01 * maxFlux) significantReactions.put(r,flux); } } System.out.print("Time: "); System.out.println(p_presentStatus.getTime()); System.out.println("Unreacted species " + maxSpecies.getName() + " has highest flux: " + String.valueOf(maxFlux)); System.out.println("The total number of unreacted reactions with this species is "+reactionWithSpecies+". Significant ones are:"); Iterator reactionIter = significantReactions.keySet().iterator(); while (reactionIter.hasNext()){ Reaction r = (Reaction)reactionIter.next(); System.out.println(" "+r.getStructure().toChemkinString(r.hasReverseReaction())+"\t"+significantReactions.get(r)); } return maxSpecies; //#] } } /********************************************************************* File Path : RMG\RMG\jing\rxnSys\RateBasedRME.java *********************************************************************/
true
true
public void enlargeReactionModel(LinkedList p_reactionSystemList, ReactionModel rm, LinkedList p_validList){ //public void enlargeReactionModel(ReactionSystem p_reactionSystem, ReactionModel rm) //#[ operation enlargeReactionModel(ReactionSystem) //ReactionModel rm = p_reactionSystem.getReactionModel(); if (!(rm instanceof CoreEdgeReactionModel)) throw new InvalidReactionModelTypeException(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm; //10/30/07 gmagoon: iterate over reaction systems that are not valid LinkedList nextList = new LinkedList(); double startTime = System.currentTimeMillis(); for (Integer i = 0; i < p_reactionSystemList.size(); i++) { if (!(Boolean) p_validList.get(i)) { PresentStatus ps = ((ReactionSystem) p_reactionSystemList.get(i)).getPresentStatus(); String maxflux = ""; Species next = getNextCandidateSpecies(cerm, ps, maxflux); nextList.add(next); } else { nextList.add(null);//****hopefully, null will contribute to length of list; otherwise, modifications will be needed } } // generate new reaction set /*startTime = System.currentTimeMillis(); LinkedHashSet newReactionSet = p_reactionSystem.lrg.react(cerm.getReactedSpeciesSet(),next); newReactionSet.addAll(p_reactionSystem.getReactionGenerator().react(cerm.getReactedSpeciesSet(),next)); double enlargeTime = (System.currentTimeMillis()-startTime)/1000/60;*/ startTime = System.currentTimeMillis(); //10/30/07 gmagoon: add species from nextList for (Integer i = 0; i < p_reactionSystemList.size(); i++) { if (!(Boolean) p_validList.get(i)) { Species newCoreSpecies = (Species) nextList.get(i); if (cerm.containsAsReactedSpecies(newCoreSpecies)) //throw new InvalidNextCandidateSpeciesException(); { System.out.println("Species " + newCoreSpecies.getName() + "(" + Integer.toString(newCoreSpecies.getID()) + ") is already present in reaction model"); } else { double findSpeciesTime = (System.currentTimeMillis() - startTime) / 1000 / 60; //Global.diagnosticInfo.append(next.getChemkinName() + "\t" + maxflux + "\t" + ((RateBasedVT) ((ReactionSystem) p_reactionSystemList.get(i)).finishController.validityTester).Rmin + "\t" + findSpeciesTime + "\t"); System.out.print("\nAdd a new reacted Species:"); System.out.println(newCoreSpecies.getName()); Temperature temp = new Temperature(298, "K"); double H = newCoreSpecies.calculateH(temp); double S = newCoreSpecies.calculateS(temp); double G = newCoreSpecies.calculateG(temp); double Cp = newCoreSpecies.calculateCp(temp); System.out.println("Thermo of species at 298K (H, S, G, Cp, respectively)\t" + String.valueOf(H) + '\t' + String.valueOf(S) + '\t' + String.valueOf(G) + '\t' + String.valueOf(Cp)); cerm.moveFromUnreactedToReactedSpecies(newCoreSpecies); cerm.moveFromUnreactedToReactedReaction(); Global.moveUnreactedToReacted = (System.currentTimeMillis() - startTime) / 1000 / 60; // add species status to reaction system SpeciesStatus speciesStatus = new SpeciesStatus(newCoreSpecies, 1, 0.0, 0.0); // (species, type (reacted=1), concentration, flux) PresentStatus ps = ((ReactionSystem) p_reactionSystemList.get(i)).getPresentStatus(); ps.putSpeciesStatus(speciesStatus); // generate new reaction set startTime = System.currentTimeMillis(); // Species List is first reacted by Library Reaction Generator and then sent to RMG Model Generator // Check Reaction Library ReactionSystem rxnSystem = (ReactionSystem) p_reactionSystemList.get(i); System.out.println("Checking Reaction Library "+rxnSystem.getLibraryReactionGenerator().getReactionLibrary().getName()+" for reactions of "+newCoreSpecies.getName()+" with the core."); // At this point the core (cerm.getReactedSpeciesSet()) already contains newCoreSpecies, so we can just react the entire core. LinkedHashSet newReactionSet = rxnSystem.getLibraryReactionGenerator().react(cerm.getReactedSpeciesSet()); //LinkedHashSet newReactionSet = rxnSystem.getLibraryReactionGenerator().react(cerm.getReactedSpeciesSet(),newCoreSpecies,"All"); // Report only those that contain the new species (newCoreSpecies) Iterator ReactionIter = newReactionSet.iterator(); while(ReactionIter.hasNext()){ Reaction current_reaction = (Reaction)ReactionIter.next(); if (current_reaction.contains(newCoreSpecies)) { System.out.println("Library Reaction: " + current_reaction.toString() ); } } // Calls in Reaction Model Generator and adds it to Reaction Set ( if duplicate reaction is found it is not added I think ) System.out.println("Generating reactions using reaction family templates."); // Add reactions found from reaction template to current reaction set newReactionSet.addAll(((ReactionSystem) p_reactionSystemList.get(i)).getReactionGenerator().react(cerm.getReactedSpeciesSet(), newCoreSpecies, "All")); // shamel 6/22/2010 Suppressed output , line is only for debugging //System.out.println("Reaction Set Found after LRG + ReactionGenerator call "+newReactionSet); // Remove Duplicate entrys from reaction set i.e same reaction might be coming from seed/reaction library and reaction template // Same means == same family and not same structure coming from different families LinkedHashSet newReactionSet_nodup = RemoveDuplicateReac(newReactionSet); // shamel 6/22/2010 Suppressed output , line is only for debugging //System.out.println("Reaction Set Found after LRG + ReactionGenerator call and Removing Dups"+newReactionSet_nodup); double enlargeTime = (System.currentTimeMillis() - startTime) / 1000 / 60; startTime = System.currentTimeMillis(); double restartTime = (System.currentTimeMillis() - startTime) / 1000 / 60; Global.diagnosticInfo.append(Global.moveUnreactedToReacted + "\t" + enlargeTime + "\t" + restartTime + "\t"); // partition the reaction set into reacted reaction set and unreacted reaction set // update the corresponding core and edge model of CoreEdgeReactionModel cerm.addReactionSet(newReactionSet_nodup); } } } return; }
public void enlargeReactionModel(LinkedList p_reactionSystemList, ReactionModel rm, LinkedList p_validList){ //public void enlargeReactionModel(ReactionSystem p_reactionSystem, ReactionModel rm) //#[ operation enlargeReactionModel(ReactionSystem) //ReactionModel rm = p_reactionSystem.getReactionModel(); if (!(rm instanceof CoreEdgeReactionModel)) throw new InvalidReactionModelTypeException(); CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm; //10/30/07 gmagoon: iterate over reaction systems that are not valid LinkedList nextList = new LinkedList(); double startTime = System.currentTimeMillis(); for (Integer i = 0; i < p_reactionSystemList.size(); i++) { if (!(Boolean) p_validList.get(i)) { PresentStatus ps = ((ReactionSystem) p_reactionSystemList.get(i)).getPresentStatus(); String maxflux = ""; Species next = getNextCandidateSpecies(cerm, ps, maxflux); nextList.add(next); } else { nextList.add(null);//****hopefully, null will contribute to length of list; otherwise, modifications will be needed } } // generate new reaction set /*startTime = System.currentTimeMillis(); LinkedHashSet newReactionSet = p_reactionSystem.lrg.react(cerm.getReactedSpeciesSet(),next); newReactionSet.addAll(p_reactionSystem.getReactionGenerator().react(cerm.getReactedSpeciesSet(),next)); double enlargeTime = (System.currentTimeMillis()-startTime)/1000/60;*/ startTime = System.currentTimeMillis(); //10/30/07 gmagoon: add species from nextList for (Integer i = 0; i < p_reactionSystemList.size(); i++) { if (!(Boolean) p_validList.get(i)) { Species newCoreSpecies = (Species) nextList.get(i); if (cerm.containsAsReactedSpecies(newCoreSpecies)) //throw new InvalidNextCandidateSpeciesException(); { System.out.println("Species " + newCoreSpecies.getName() + "(" + Integer.toString(newCoreSpecies.getID()) + ") is already present in reaction model"); } else { double findSpeciesTime = (System.currentTimeMillis() - startTime) / 1000 / 60; //Global.diagnosticInfo.append(next.getChemkinName() + "\t" + maxflux + "\t" + ((RateBasedVT) ((ReactionSystem) p_reactionSystemList.get(i)).finishController.validityTester).Rmin + "\t" + findSpeciesTime + "\t"); System.out.print("\nAdd a new reacted Species:"); System.out.println(newCoreSpecies.getName()); Temperature temp = new Temperature(298, "K"); double H = newCoreSpecies.calculateH(temp); double S = newCoreSpecies.calculateS(temp); double G = newCoreSpecies.calculateG(temp); double Cp = newCoreSpecies.calculateCp(temp); System.out.println("Thermo of species at 298K (H, S, G, Cp, respectively)\t" + String.valueOf(H) + '\t' + String.valueOf(S) + '\t' + String.valueOf(G) + '\t' + String.valueOf(Cp)); cerm.moveFromUnreactedToReactedSpecies(newCoreSpecies); cerm.moveFromUnreactedToReactedReaction(); Global.moveUnreactedToReacted = (System.currentTimeMillis() - startTime) / 1000 / 60; // add species status to reaction system SpeciesStatus speciesStatus = new SpeciesStatus(newCoreSpecies, 1, 0.0, 0.0); // (species, type (reacted=1), concentration, flux) PresentStatus ps = ((ReactionSystem) p_reactionSystemList.get(i)).getPresentStatus(); ps.putSpeciesStatus(speciesStatus); // generate new reaction set startTime = System.currentTimeMillis(); // Species List is first reacted by Library Reaction Generator and then sent to RMG Model Generator // Check Reaction Library ReactionSystem rxnSystem = (ReactionSystem) p_reactionSystemList.get(i); System.out.println("Checking Reaction Library for reactions of "+newCoreSpecies.getName()+" with the core."); // At this point the core (cerm.getReactedSpeciesSet()) already contains newCoreSpecies, so we can just react the entire core. LinkedHashSet newReactionSet = rxnSystem.getLibraryReactionGenerator().react(cerm.getReactedSpeciesSet()); //LinkedHashSet newReactionSet = rxnSystem.getLibraryReactionGenerator().react(cerm.getReactedSpeciesSet(),newCoreSpecies,"All"); // Report only those that contain the new species (newCoreSpecies) Iterator ReactionIter = newReactionSet.iterator(); while(ReactionIter.hasNext()){ Reaction current_reaction = (Reaction)ReactionIter.next(); if (current_reaction.contains(newCoreSpecies)) { System.out.println("Library Reaction: " + current_reaction.toString() ); } } // Calls in Reaction Model Generator and adds it to Reaction Set ( if duplicate reaction is found it is not added I think ) System.out.println("Generating reactions using reaction family templates."); // Add reactions found from reaction template to current reaction set newReactionSet.addAll(((ReactionSystem) p_reactionSystemList.get(i)).getReactionGenerator().react(cerm.getReactedSpeciesSet(), newCoreSpecies, "All")); // shamel 6/22/2010 Suppressed output , line is only for debugging //System.out.println("Reaction Set Found after LRG + ReactionGenerator call "+newReactionSet); // Remove Duplicate entrys from reaction set i.e same reaction might be coming from seed/reaction library and reaction template // Same means == same family and not same structure coming from different families LinkedHashSet newReactionSet_nodup = RemoveDuplicateReac(newReactionSet); // shamel 6/22/2010 Suppressed output , line is only for debugging //System.out.println("Reaction Set Found after LRG + ReactionGenerator call and Removing Dups"+newReactionSet_nodup); double enlargeTime = (System.currentTimeMillis() - startTime) / 1000 / 60; startTime = System.currentTimeMillis(); double restartTime = (System.currentTimeMillis() - startTime) / 1000 / 60; Global.diagnosticInfo.append(Global.moveUnreactedToReacted + "\t" + enlargeTime + "\t" + restartTime + "\t"); // partition the reaction set into reacted reaction set and unreacted reaction set // update the corresponding core and edge model of CoreEdgeReactionModel cerm.addReactionSet(newReactionSet_nodup); } } } return; }