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/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java index 66e54b550..b4456db67 100644 --- a/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java +++ b/htmlunit/src/test/java/com/gargoylesoftware/htmlunit/javascript/SimpleScriptableTest.java @@ -1,428 +1,430 @@ /* * Copyright (c) 2002-2009 Gargoyle Software 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.gargoylesoftware.htmlunit.javascript; import static org.junit.Assert.fail; import java.io.File; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.commons.lang.ClassUtils; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import com.gargoylesoftware.htmlunit.BrowserRunner; import com.gargoylesoftware.htmlunit.CollectingAlertHandler; import com.gargoylesoftware.htmlunit.MockWebConnection; import com.gargoylesoftware.htmlunit.ScriptException; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.WebTestCase; import com.gargoylesoftware.htmlunit.BrowserRunner.Alerts; import com.gargoylesoftware.htmlunit.BrowserRunner.Browser; import com.gargoylesoftware.htmlunit.BrowserRunner.Browsers; import com.gargoylesoftware.htmlunit.BrowserRunner.NotYetImplemented; import com.gargoylesoftware.htmlunit.html.HtmlElement; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.javascript.configuration.JavaScriptConfiguration; /** * Tests for {@link SimpleScriptable}. * * @version $Revision$ * @author <a href="mailto:[email protected]">Mike Bowler</a> * @author <a href="mailto:[email protected]">Barnaby Court</a> * @author David K. Taylor * @author <a href="mailto:[email protected]">Ben Curren</a> * @author Marc Guillemot * @author Chris Erskine * @author Ahmed Ashour * @author Sudhan Moghe * @author <a href="mailto:[email protected]">Mike Dirolf</a> */ @RunWith(BrowserRunner.class) public class SimpleScriptableTest extends WebTestCase { /** * @throws Exception if the test fails */ @Test public void callInheritedFunction() throws Exception { final WebClient client = getWebClient(); final MockWebConnection webConnection = new MockWebConnection(); final String content = "<html><head><title>foo</title><script>\n" + "function doTest() {\n" + " document.form1.textfield1.focus();\n" + " alert('past focus');\n" + "}\n" + "</script></head><body onload='doTest()'>\n" + "<p>hello world</p>\n" + "<form name='form1'>\n" + " <input type='text' name='textfield1' id='textfield1' value='foo'/>\n" + "</form>\n" + "</body></html>"; webConnection.setDefaultResponse(content); client.setWebConnection(webConnection); final List<String> expectedAlerts = Collections.singletonList("past focus"); createTestPageForRealBrowserIfNeeded(content, expectedAlerts); final List<String> collectedAlerts = new ArrayList<String>(); client.setAlertHandler(new CollectingAlertHandler(collectedAlerts)); final HtmlPage page = client.getPage(URL_GARGOYLE); assertEquals("foo", page.getTitleText()); Assert.assertEquals("focus not changed to textfield1", page.getFormByName("form1").getInputByName("textfield1"), page.getFocusedElement()); assertEquals(expectedAlerts, collectedAlerts); } /** * Test. */ @Test @Browsers(Browser.NONE) public void htmlJavaScriptMapping_AllJavaScriptClassesArePresent() { final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map = JavaScriptConfiguration.getHtmlJavaScriptMapping(); final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host"; final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar)); // Now pull out those names that we know don't have HTML equivalents names.remove("ActiveXObject"); names.remove("ActiveXObjectImpl"); names.remove("BoxObject"); names.remove("ClipboardData"); names.remove("ComputedCSSStyleDeclaration"); + names.remove("CSSImportRule"); names.remove("CSSRule"); names.remove("CSSRuleList"); names.remove("CSSStyleDeclaration"); names.remove("CSSStyleRule"); names.remove("Document"); names.remove("DOMImplementation"); names.remove("DOMParser"); names.remove("Enumerator"); names.remove("Event"); names.remove("EventNode"); names.remove("EventHandler"); names.remove("EventListenersContainer"); names.remove("FormField"); names.remove("History"); names.remove("HTMLCollection"); names.remove("HTMLCollectionTags"); names.remove("HTMLDocument"); names.remove("HTMLOptionsCollection"); names.remove("JavaScriptBackgroundJob"); names.remove("Location"); + names.remove("MediaList"); names.remove("MimeType"); names.remove("MimeTypeArray"); names.remove("MouseEvent"); names.remove("Namespace"); names.remove("NamespaceCollection"); names.remove("Navigator"); names.remove("Node"); names.remove("NodeFilter"); names.remove("Plugin"); names.remove("PluginArray"); names.remove("Popup"); names.remove("Range"); names.remove("RowContainer"); names.remove("Screen"); names.remove("ScoperFunctionObject"); names.remove("Selection"); names.remove("SimpleArray"); names.remove("Stylesheet"); names.remove("StyleSheetList"); names.remove("TextRange"); names.remove("TextRectangle"); names.remove("TreeWalker"); names.remove("UIEvent"); names.remove("Window"); names.remove("WindowProxy"); names.remove("XMLDocument"); names.remove("XMLDOMParseError"); names.remove("XMLHttpRequest"); names.remove("XMLSerializer"); names.remove("XPathNSResolver"); names.remove("XPathResult"); names.remove("XSLTProcessor"); names.remove("XSLTemplate"); names.remove("XMLAttr"); final Collection<String> hostClassNames = new ArrayList<String>(); for (final Class< ? extends SimpleScriptable> clazz : map.values()) { hostClassNames.add(ClassUtils.getShortClassName(clazz)); } assertEquals(new TreeSet<String>(names).toString(), new TreeSet<String>(hostClassNames).toString()); } private Set<String> getFileNames(final String directoryName) { File directory = new File("." + File.separatorChar + directoryName); if (!directory.exists()) { directory = new File("./src/main/java/".replace('/', File.separatorChar) + directoryName); } assertTrue("directory exists", directory.exists()); assertTrue("is a directory", directory.isDirectory()); final Set<String> collection = new HashSet<String>(); for (final String name : directory.list()) { if (name.endsWith(".java")) { collection.add(name.substring(0, name.length() - 5)); } } return collection; } /** * This test fails on IE and FF but not by HtmlUnit because according to Ecma standard, * attempts to set read only properties should be silently ignored. * Furthermore document.body = document.body will work on FF but not on IE * @throws Exception if the test fails */ @Test @NotYetImplemented public void setNonWritableProperty() throws Exception { final String content = "<html><head><title>foo</title></head><body onload='document.body=123456'>" + "</body></html>"; try { loadPage(getBrowserVersion(), content, null); fail("Exception should have been thrown"); } catch (final ScriptException e) { // it's ok } } /** * Works since Rhino 1.7. * @throws Exception if the test fails */ @Test @Alerts("[object Object]") public void arguments_toString() throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " alert(arguments);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * @throws Exception if the test fails */ @Test @Alerts("3") public void stringWithExclamationMark() throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " var x = '<!>';\n" + " alert(x.length);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * Test the host class names match the Firefox (w3c names). * @see <a * href="http://java.sun.com/j2se/1.5.0/docs/guide/plugin/dom/org/w3c/dom/html/package-summary.html">DOM API</a> * @throws Exception if the test fails */ @Test @Browsers(Browser.FF) @NotYetImplemented public void hostClassNames() throws Exception { testHostClassNames("HTMLAnchorElement"); } private void testHostClassNames(final String className) throws Exception { final String content = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " alert(" + className + ");\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; final String[] expectedAlerts = {'[' + className + ']'}; final List<String> collectedAlerts = new ArrayList<String>(); loadPage(getBrowserVersion(), content, collectedAlerts); assertEquals(expectedAlerts, collectedAlerts); } /** * Blocked by Rhino bug 419090 (https://bugzilla.mozilla.org/show_bug.cgi?id=419090). * @throws Exception if the test fails */ @Test @Alerts({ "x1", "x2", "x3", "x4", "x5" }) public void arrayedMap() throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " var map = {};\n" + " map['x1'] = 'y1';\n" + " map['x2'] = 'y2';\n" + " map['x3'] = 'y3';\n" + " map['x4'] = 'y4';\n" + " map['x5'] = 'y5';\n" + " for (var i in map) {\n" + " alert(i);\n" + " }" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * @throws Exception if the test fails */ @Test @Browsers(Browser.FF) public void isParentOf() throws Exception { isParentOf("Node", "Element", true); isParentOf("Document", "XMLDocument", true); isParentOf("Node", "XPathResult", false); isParentOf("Element", "HTMLElement", true); isParentOf("HTMLElement", "HTMLHtmlElement", true); isParentOf("CSSStyleDeclaration", "ComputedCSSStyleDeclaration", true); //although Image != HTMLImageElement, they seem to be synonyms!!! isParentOf("Image", "HTMLImageElement", true); isParentOf("HTMLImageElement", "Image", true); } private void isParentOf(final String object1, final String object2, final boolean status) throws Exception { final String html = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " alert(isParentOf(" + object1 + ", " + object2 + "));\n" + " }\n" + " /**\n" + " * Returns true if o1 prototype is parent/grandparent of o2 prototype\n" + " */\n" + " function isParentOf(o1, o2) {\n" + " o1.prototype.myCustomFunction = function() {};\n" + " return o2.prototype.myCustomFunction != undefined;\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; final String[] expectedAlerts = {Boolean.toString(status)}; final List<String> collectedAlerts = new ArrayList<String>(); loadPage(getBrowserVersion(), html, collectedAlerts); assertEquals(expectedAlerts, collectedAlerts); } /** * This is related to HtmlUnitContextFactory.hasFeature(Context.FEATURE_PARENT_PROTO_PROPERTIES). * @throws Exception if the test fails */ @Test @Alerts(IE = "false", FF = "true") public void parentProtoFeature() throws Exception { final String html = "<html><head><title>First</title><script>\n" + "function test() {\n" + " alert(document.createElement('div').__proto__ != undefined);\n" + "}\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * Test for https://sourceforge.net/tracker/index.php?func=detail&aid=1933943&group_id=47038&atid=448266. * See also http://groups.google.com/group/mozilla.dev.tech.js-engine.rhino/browse_thread/thread/1f1c24f58f662c58. * @throws Exception if the test fails */ @Test @Alerts("1") public void passFunctionAsParameter() throws Exception { final String html = "<html><head><title>First</title><script>\n" + " function run(fun) {\n" + " fun('alert(1)');\n" + " }\n" + "\n" + " function test() {\n" + " run(eval);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; loadPageWithAlerts(html); } /** * Test JavaScript: 'new Date().getTimezoneOffset()' compared to java.text.SimpleDateFormat.format(). * * @throws Exception if the test fails */ @Test @Browsers(Browser.NONE) public void dateGetTimezoneOffset() throws Exception { final String content = "<html><head><title>foo</title><script>\n" + " function test() {\n" + " var offset = Math.abs(new Date().getTimezoneOffset());\n" + " var timezone = '' + (offset/60);\n" + " if (timezone.length == 1)\n" + " timezone = '0' + timezone;\n" + " alert(timezone);\n" + " }\n" + "</script></head><body onload='test()'>\n" + "</body></html>"; final String timeZone = new SimpleDateFormat("Z").format(Calendar.getInstance().getTime()); final String hour = timeZone.substring(1, 3); String strMinutes = timeZone.substring(3, 5); final int minutes = Integer.parseInt(strMinutes); final StringBuilder sb = new StringBuilder(); if (minutes != 0) { sb.append(hour.substring(1)); strMinutes = String.valueOf((double) minutes / 60); strMinutes = strMinutes.substring(1); sb.append(strMinutes); } else { sb.append(hour); } final String[] expectedAlerts = {sb.toString()}; final List<String> collectedAlerts = new ArrayList<String>(); createTestPageForRealBrowserIfNeeded(content, expectedAlerts); loadPage(content, collectedAlerts); assertEquals(expectedAlerts, collectedAlerts); } }
false
true
public void htmlJavaScriptMapping_AllJavaScriptClassesArePresent() { final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map = JavaScriptConfiguration.getHtmlJavaScriptMapping(); final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host"; final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar)); // Now pull out those names that we know don't have HTML equivalents names.remove("ActiveXObject"); names.remove("ActiveXObjectImpl"); names.remove("BoxObject"); names.remove("ClipboardData"); names.remove("ComputedCSSStyleDeclaration"); names.remove("CSSRule"); names.remove("CSSRuleList"); names.remove("CSSStyleDeclaration"); names.remove("CSSStyleRule"); names.remove("Document"); names.remove("DOMImplementation"); names.remove("DOMParser"); names.remove("Enumerator"); names.remove("Event"); names.remove("EventNode"); names.remove("EventHandler"); names.remove("EventListenersContainer"); names.remove("FormField"); names.remove("History"); names.remove("HTMLCollection"); names.remove("HTMLCollectionTags"); names.remove("HTMLDocument"); names.remove("HTMLOptionsCollection"); names.remove("JavaScriptBackgroundJob"); names.remove("Location"); names.remove("MimeType"); names.remove("MimeTypeArray"); names.remove("MouseEvent"); names.remove("Namespace"); names.remove("NamespaceCollection"); names.remove("Navigator"); names.remove("Node"); names.remove("NodeFilter"); names.remove("Plugin"); names.remove("PluginArray"); names.remove("Popup"); names.remove("Range"); names.remove("RowContainer"); names.remove("Screen"); names.remove("ScoperFunctionObject"); names.remove("Selection"); names.remove("SimpleArray"); names.remove("Stylesheet"); names.remove("StyleSheetList"); names.remove("TextRange"); names.remove("TextRectangle"); names.remove("TreeWalker"); names.remove("UIEvent"); names.remove("Window"); names.remove("WindowProxy"); names.remove("XMLDocument"); names.remove("XMLDOMParseError"); names.remove("XMLHttpRequest"); names.remove("XMLSerializer"); names.remove("XPathNSResolver"); names.remove("XPathResult"); names.remove("XSLTProcessor"); names.remove("XSLTemplate"); names.remove("XMLAttr"); final Collection<String> hostClassNames = new ArrayList<String>(); for (final Class< ? extends SimpleScriptable> clazz : map.values()) { hostClassNames.add(ClassUtils.getShortClassName(clazz)); } assertEquals(new TreeSet<String>(names).toString(), new TreeSet<String>(hostClassNames).toString()); }
public void htmlJavaScriptMapping_AllJavaScriptClassesArePresent() { final Map<Class < ? extends HtmlElement>, Class < ? extends SimpleScriptable>> map = JavaScriptConfiguration.getHtmlJavaScriptMapping(); final String directoryName = "../../../src/main/java/com/gargoylesoftware/htmlunit/javascript/host"; final Set<String> names = getFileNames(directoryName.replace('/', File.separatorChar)); // Now pull out those names that we know don't have HTML equivalents names.remove("ActiveXObject"); names.remove("ActiveXObjectImpl"); names.remove("BoxObject"); names.remove("ClipboardData"); names.remove("ComputedCSSStyleDeclaration"); names.remove("CSSImportRule"); names.remove("CSSRule"); names.remove("CSSRuleList"); names.remove("CSSStyleDeclaration"); names.remove("CSSStyleRule"); names.remove("Document"); names.remove("DOMImplementation"); names.remove("DOMParser"); names.remove("Enumerator"); names.remove("Event"); names.remove("EventNode"); names.remove("EventHandler"); names.remove("EventListenersContainer"); names.remove("FormField"); names.remove("History"); names.remove("HTMLCollection"); names.remove("HTMLCollectionTags"); names.remove("HTMLDocument"); names.remove("HTMLOptionsCollection"); names.remove("JavaScriptBackgroundJob"); names.remove("Location"); names.remove("MediaList"); names.remove("MimeType"); names.remove("MimeTypeArray"); names.remove("MouseEvent"); names.remove("Namespace"); names.remove("NamespaceCollection"); names.remove("Navigator"); names.remove("Node"); names.remove("NodeFilter"); names.remove("Plugin"); names.remove("PluginArray"); names.remove("Popup"); names.remove("Range"); names.remove("RowContainer"); names.remove("Screen"); names.remove("ScoperFunctionObject"); names.remove("Selection"); names.remove("SimpleArray"); names.remove("Stylesheet"); names.remove("StyleSheetList"); names.remove("TextRange"); names.remove("TextRectangle"); names.remove("TreeWalker"); names.remove("UIEvent"); names.remove("Window"); names.remove("WindowProxy"); names.remove("XMLDocument"); names.remove("XMLDOMParseError"); names.remove("XMLHttpRequest"); names.remove("XMLSerializer"); names.remove("XPathNSResolver"); names.remove("XPathResult"); names.remove("XSLTProcessor"); names.remove("XSLTemplate"); names.remove("XMLAttr"); final Collection<String> hostClassNames = new ArrayList<String>(); for (final Class< ? extends SimpleScriptable> clazz : map.values()) { hostClassNames.add(ClassUtils.getShortClassName(clazz)); } assertEquals(new TreeSet<String>(names).toString(), new TreeSet<String>(hostClassNames).toString()); }
diff --git a/org/postgresql/util/PSQLException.java b/org/postgresql/util/PSQLException.java index 36290a5..1f206ad 100644 --- a/org/postgresql/util/PSQLException.java +++ b/org/postgresql/util/PSQLException.java @@ -1,111 +1,115 @@ package org.postgresql.util; import java.sql.*; import java.text.*; import java.util.*; /** * This class extends SQLException, and provides our internationalisation handling */ public class PSQLException extends SQLException { private String message; // Cache for future errors static ResourceBundle bundle; /** * This provides the same functionality to SQLException * @param error Error string */ public PSQLException(String error) { super(); translate(error,null); } /** * A more generic entry point. * @param error Error string or standard message id * @param args Array of arguments */ public PSQLException(String error,Object[] args) { //super(); translate(error,args); } /** * Helper version for 1 arg */ public PSQLException(String error,Object arg) { super(); Object[] argv = new Object[1]; argv[0] = arg; translate(error,argv); } /** * Helper version for 2 args */ public PSQLException(String error,Object arg1,Object arg2) { super(); Object[] argv = new Object[2]; argv[0] = arg1; argv[1] = arg2; translate(error,argv); } /** * This does the actual translation */ private void translate(String id,Object[] args) { if(bundle == null) { try { bundle = ResourceBundle.getBundle("org.postgresql.errors"); } catch(MissingResourceException e) { + // translation files have not been installed. + message = id; } } + if (bundle != null) { // Now look up a localized message. If one is not found, then use // the supplied message instead. - message = null; - try { - message = bundle.getString(id); - } catch(MissingResourceException e) { - message = id; - } + message = null; + try { + message = bundle.getString(id); + } catch(MissingResourceException e) { + message = id; + } + } // Expand any arguments if(args!=null) message = MessageFormat.format(message,args); } /** * Overides Throwable */ public String getLocalizedMessage() { return message; } /** * Overides Throwable */ public String getMessage() { return message; } /** * Overides Object */ public String toString() { return message; } }
false
true
private void translate(String id,Object[] args) { if(bundle == null) { try { bundle = ResourceBundle.getBundle("org.postgresql.errors"); } catch(MissingResourceException e) { } } // Now look up a localized message. If one is not found, then use // the supplied message instead. message = null; try { message = bundle.getString(id); } catch(MissingResourceException e) { message = id; } // Expand any arguments if(args!=null) message = MessageFormat.format(message,args); }
private void translate(String id,Object[] args) { if(bundle == null) { try { bundle = ResourceBundle.getBundle("org.postgresql.errors"); } catch(MissingResourceException e) { // translation files have not been installed. message = id; } } if (bundle != null) { // Now look up a localized message. If one is not found, then use // the supplied message instead. message = null; try { message = bundle.getString(id); } catch(MissingResourceException e) { message = id; } } // Expand any arguments if(args!=null) message = MessageFormat.format(message,args); }
diff --git a/src/java/com/eviware/soapui/impl/wsdl/actions/testcase/TestCaseOptionsAction.java b/src/java/com/eviware/soapui/impl/wsdl/actions/testcase/TestCaseOptionsAction.java index 2c31e8643..e327946a8 100644 --- a/src/java/com/eviware/soapui/impl/wsdl/actions/testcase/TestCaseOptionsAction.java +++ b/src/java/com/eviware/soapui/impl/wsdl/actions/testcase/TestCaseOptionsAction.java @@ -1,183 +1,183 @@ /* * soapUI, copyright (C) 2004-2011 eviware.com * * soapUI is free software; you can redistribute it and/or modify it under the * terms of version 2.1 of the GNU Lesser General Public License as published by * the Free Software Foundation. * * soapUI 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 at gnu.org. */ package com.eviware.soapui.impl.wsdl.actions.testcase; import com.eviware.soapui.config.WsrmVersionTypeConfig; import com.eviware.soapui.impl.wsdl.support.HelpUrls; import com.eviware.soapui.impl.wsdl.testcase.WsdlTestCase; import com.eviware.soapui.settings.HttpSettings; import com.eviware.soapui.support.UISupport; import com.eviware.soapui.support.action.support.AbstractSoapUIAction; import com.eviware.soapui.support.types.StringToStringMap; import com.eviware.x.form.XForm; import com.eviware.x.form.XForm.FieldType; import com.eviware.x.form.XFormDialog; import com.eviware.x.form.XFormDialogBuilder; import com.eviware.x.form.XFormFactory; import com.eviware.x.form.XFormField; import com.eviware.x.form.XFormFieldListener; /** * Options dialog for testcases * * @author Ole.Matzura */ public class TestCaseOptionsAction extends AbstractSoapUIAction<WsdlTestCase> { private static final String KEEP_SESSION = "Session"; private static final String FAIL_ON_ERROR = "Abort on Error"; private static final String FAIL_TESTCASE_ON_ERROR = "Fail TestCase on Error"; private static final String DISCARD_OK_RESULTS = "Discard OK Results"; private static final String SOCKET_TIMEOUT = "Socket timeout"; private static final String SEARCH_PROPERTIES = "Search Properties"; public static final String SOAPUI_ACTION_ID = "TestCaseOptionsAction"; private static final String TESTCASE_TIMEOUT = "TestCase timeout"; private static final String MAXRESULTS = "Max Results"; private static final String WS_RM_ENABLED = "WS-RM Enabled"; private static final String WS_RM_VERSION = "WS-RM Version"; private static final String WS_RM_ACK_TO = "WS-RM Ack To"; private static final String WS_RM_EXPIRES = "WS-RM Expires"; private static final String AMF_LOGIN = "login"; private static final String AMF_PASSWORD = "password"; private static final String AMF_AUTHORISATION_ENABLE = "AMF Session"; private static final String AMF_ENDPOINT = "endpoint"; private XFormDialog dialog; private XForm form; private XForm amfForm; private XForm wsrmForm; public TestCaseOptionsAction() { super( "Options", "Sets options for this TestCase" ); } public void perform( WsdlTestCase testCase, Object param ) { if( dialog == null ) { XFormDialogBuilder builder = XFormFactory.createDialogBuilder( "TestCase Options" ); form = builder.createForm( "Basic" ); form.addCheckBox( SEARCH_PROPERTIES, "Search preceding TestSteps for property values" ); form.addCheckBox( KEEP_SESSION, "Maintain HTTP session" ); form.addCheckBox( FAIL_ON_ERROR, "Fail on error" ).addFormFieldListener( new XFormFieldListener() { public void valueChanged( XFormField sourceField, String newValue, String oldValue ) { form.getFormField( FAIL_TESTCASE_ON_ERROR ).setEnabled( !Boolean.parseBoolean( newValue ) ); } } ); form.addCheckBox( FAIL_TESTCASE_ON_ERROR, "Fail TestCase if it has failed TestSteps" ); form.addCheckBox( DISCARD_OK_RESULTS, "Discards successful TestStep results to preserve memory" ); form.addTextField( SOCKET_TIMEOUT, "Socket timeout in milliseconds", FieldType.TEXT ); form.addTextField( TESTCASE_TIMEOUT, "Timeout in milliseconds for entire TestCase", FieldType.TEXT ); form.addTextField( MAXRESULTS, "Maximum number of TestStep results to keep in memory during a run", FieldType.TEXT ); wsrmForm = builder.createForm( "WS-RM" ); wsrmForm.addCheckBox( WS_RM_ENABLED, "Use WS-Reliable Messaging" ); wsrmForm.addComboBox( WS_RM_VERSION, new String[] { WsrmVersionTypeConfig.X_1_0.toString(), WsrmVersionTypeConfig.X_1_1.toString(), WsrmVersionTypeConfig.X_1_2.toString() }, "The property for managing WS-RM version" ); wsrmForm.addTextField( WS_RM_ACK_TO, "Acknowledgments To", FieldType.TEXT ); wsrmForm.addTextField( WS_RM_EXPIRES, "Expires after", FieldType.TEXT ); amfForm = builder.createForm( "AMF" ); amfForm.addCheckBox( AMF_AUTHORISATION_ENABLE, "Enable AMF Session" ).addFormFieldListener( new AMFXFormFieldListener() ); amfForm.addTextField( AMF_ENDPOINT, "AMF Authorization endpoint", FieldType.TEXT ); amfForm.addTextField( AMF_LOGIN, "AMF Authorization usernmae", FieldType.TEXT ); - amfForm.addTextField( AMF_PASSWORD, "AMF Authorization password", FieldType.TEXT ); + amfForm.addTextField( AMF_PASSWORD, "AMF Authorization password", FieldType.PASSWORD ); dialog = builder.buildDialog( builder.buildOkCancelHelpActions( HelpUrls.TESTCASEOPTIONS_HELP_URL ), "Specify general options for this TestCase", UISupport.OPTIONS_ICON ); } StringToStringMap values = new StringToStringMap(); values.put( SEARCH_PROPERTIES, String.valueOf( testCase.getSearchProperties() ) ); values.put( KEEP_SESSION, String.valueOf( testCase.getKeepSession() ) ); values.put( FAIL_ON_ERROR, String.valueOf( testCase.getFailOnError() ) ); values.put( FAIL_TESTCASE_ON_ERROR, String.valueOf( testCase.getFailTestCaseOnErrors() ) ); values.put( DISCARD_OK_RESULTS, String.valueOf( testCase.getDiscardOkResults() ) ); values.put( SOCKET_TIMEOUT, String.valueOf( testCase.getSettings().getString( HttpSettings.SOCKET_TIMEOUT, "" ) ) ); values.put( TESTCASE_TIMEOUT, String.valueOf( testCase.getTimeout() ) ); values.put( MAXRESULTS, String.valueOf( testCase.getMaxResults() ) ); values.put( WS_RM_ENABLED, String.valueOf( testCase.getWsrmEnabled() ) ); values.put( WS_RM_VERSION, String.valueOf( testCase.getWsrmVersion() ) ); if( testCase.getWsrmAckTo() != null ) values.put( WS_RM_ACK_TO, String.valueOf( testCase.getWsrmAckTo() ) ); if( testCase.getWsrmExpires() != 0 ) values.put( WS_RM_EXPIRES, String.valueOf( testCase.getWsrmExpires() ) ); values.put( AMF_AUTHORISATION_ENABLE, String.valueOf( testCase.getAmfAuthorisation() ) ); values.put( AMF_ENDPOINT, String.valueOf( testCase.getAmfEndpoint() ) ); values.put( AMF_LOGIN, String.valueOf( testCase.getAmfLogin() ) ); values.put( AMF_PASSWORD, String.valueOf( testCase.getAmfPassword() ) ); dialog.getFormField( FAIL_TESTCASE_ON_ERROR ).setEnabled( !Boolean.parseBoolean( String.valueOf( testCase.getFailOnError() ) ) ); values = dialog.show( values ); if( dialog.getReturnValue() == XFormDialog.OK_OPTION ) { try { testCase.setSearchProperties( Boolean.parseBoolean( values.get( SEARCH_PROPERTIES ) ) ); testCase.setKeepSession( Boolean.parseBoolean( values.get( KEEP_SESSION ) ) ); testCase.setDiscardOkResults( Boolean.parseBoolean( values.get( DISCARD_OK_RESULTS ) ) ); testCase.setFailOnError( Boolean.parseBoolean( values.get( FAIL_ON_ERROR ) ) ); testCase.setFailTestCaseOnErrors( Boolean.parseBoolean( values.get( FAIL_TESTCASE_ON_ERROR ) ) ); testCase.setTimeout( Long.parseLong( values.get( TESTCASE_TIMEOUT ) ) ); testCase.setMaxResults( Integer.parseInt( values.get( MAXRESULTS ) ) ); testCase.setWsrmEnabled( Boolean.parseBoolean( values.get( WS_RM_ENABLED ) ) ); testCase.setWsrmVersion( values.get( WS_RM_VERSION ) ); testCase.setWsrmAckTo( values.get( WS_RM_ACK_TO ) ); if( values.get( WS_RM_EXPIRES ) != null && values.get( WS_RM_EXPIRES ).length() > 0 ) testCase.setWsrmExpires( Long.parseLong( values.get( WS_RM_EXPIRES ) ) ); String timeout = values.get( SOCKET_TIMEOUT ); if( timeout.trim().length() == 0 ) testCase.getSettings().clearSetting( HttpSettings.SOCKET_TIMEOUT ); else testCase.getSettings().setString( HttpSettings.SOCKET_TIMEOUT, timeout ); testCase.setAmfAuthorisation( Boolean.parseBoolean( values.get( AMF_AUTHORISATION_ENABLE ) ) ); testCase.setAmfEndpoint( values.get( AMF_ENDPOINT ) ); testCase.setAmfLogin( values.get( AMF_LOGIN ) ); testCase.setAmfPassword( values.get( AMF_PASSWORD ) ); } catch( Exception e1 ) { UISupport.showErrorMessage( e1.getMessage() ); } } } private class AMFXFormFieldListener implements XFormFieldListener { public void valueChanged( XFormField sourceField, String newValue, String oldValue ) { amfForm.getFormField( AMF_ENDPOINT ).setEnabled( Boolean.parseBoolean( newValue ) ); amfForm.getFormField( AMF_LOGIN ).setEnabled( Boolean.parseBoolean( newValue ) ); amfForm.getFormField( AMF_PASSWORD ).setEnabled( Boolean.parseBoolean( newValue ) ); } } }
true
true
public void perform( WsdlTestCase testCase, Object param ) { if( dialog == null ) { XFormDialogBuilder builder = XFormFactory.createDialogBuilder( "TestCase Options" ); form = builder.createForm( "Basic" ); form.addCheckBox( SEARCH_PROPERTIES, "Search preceding TestSteps for property values" ); form.addCheckBox( KEEP_SESSION, "Maintain HTTP session" ); form.addCheckBox( FAIL_ON_ERROR, "Fail on error" ).addFormFieldListener( new XFormFieldListener() { public void valueChanged( XFormField sourceField, String newValue, String oldValue ) { form.getFormField( FAIL_TESTCASE_ON_ERROR ).setEnabled( !Boolean.parseBoolean( newValue ) ); } } ); form.addCheckBox( FAIL_TESTCASE_ON_ERROR, "Fail TestCase if it has failed TestSteps" ); form.addCheckBox( DISCARD_OK_RESULTS, "Discards successful TestStep results to preserve memory" ); form.addTextField( SOCKET_TIMEOUT, "Socket timeout in milliseconds", FieldType.TEXT ); form.addTextField( TESTCASE_TIMEOUT, "Timeout in milliseconds for entire TestCase", FieldType.TEXT ); form.addTextField( MAXRESULTS, "Maximum number of TestStep results to keep in memory during a run", FieldType.TEXT ); wsrmForm = builder.createForm( "WS-RM" ); wsrmForm.addCheckBox( WS_RM_ENABLED, "Use WS-Reliable Messaging" ); wsrmForm.addComboBox( WS_RM_VERSION, new String[] { WsrmVersionTypeConfig.X_1_0.toString(), WsrmVersionTypeConfig.X_1_1.toString(), WsrmVersionTypeConfig.X_1_2.toString() }, "The property for managing WS-RM version" ); wsrmForm.addTextField( WS_RM_ACK_TO, "Acknowledgments To", FieldType.TEXT ); wsrmForm.addTextField( WS_RM_EXPIRES, "Expires after", FieldType.TEXT ); amfForm = builder.createForm( "AMF" ); amfForm.addCheckBox( AMF_AUTHORISATION_ENABLE, "Enable AMF Session" ).addFormFieldListener( new AMFXFormFieldListener() ); amfForm.addTextField( AMF_ENDPOINT, "AMF Authorization endpoint", FieldType.TEXT ); amfForm.addTextField( AMF_LOGIN, "AMF Authorization usernmae", FieldType.TEXT ); amfForm.addTextField( AMF_PASSWORD, "AMF Authorization password", FieldType.TEXT ); dialog = builder.buildDialog( builder.buildOkCancelHelpActions( HelpUrls.TESTCASEOPTIONS_HELP_URL ), "Specify general options for this TestCase", UISupport.OPTIONS_ICON ); } StringToStringMap values = new StringToStringMap(); values.put( SEARCH_PROPERTIES, String.valueOf( testCase.getSearchProperties() ) ); values.put( KEEP_SESSION, String.valueOf( testCase.getKeepSession() ) ); values.put( FAIL_ON_ERROR, String.valueOf( testCase.getFailOnError() ) ); values.put( FAIL_TESTCASE_ON_ERROR, String.valueOf( testCase.getFailTestCaseOnErrors() ) ); values.put( DISCARD_OK_RESULTS, String.valueOf( testCase.getDiscardOkResults() ) ); values.put( SOCKET_TIMEOUT, String.valueOf( testCase.getSettings().getString( HttpSettings.SOCKET_TIMEOUT, "" ) ) ); values.put( TESTCASE_TIMEOUT, String.valueOf( testCase.getTimeout() ) ); values.put( MAXRESULTS, String.valueOf( testCase.getMaxResults() ) ); values.put( WS_RM_ENABLED, String.valueOf( testCase.getWsrmEnabled() ) ); values.put( WS_RM_VERSION, String.valueOf( testCase.getWsrmVersion() ) ); if( testCase.getWsrmAckTo() != null ) values.put( WS_RM_ACK_TO, String.valueOf( testCase.getWsrmAckTo() ) ); if( testCase.getWsrmExpires() != 0 ) values.put( WS_RM_EXPIRES, String.valueOf( testCase.getWsrmExpires() ) ); values.put( AMF_AUTHORISATION_ENABLE, String.valueOf( testCase.getAmfAuthorisation() ) ); values.put( AMF_ENDPOINT, String.valueOf( testCase.getAmfEndpoint() ) ); values.put( AMF_LOGIN, String.valueOf( testCase.getAmfLogin() ) ); values.put( AMF_PASSWORD, String.valueOf( testCase.getAmfPassword() ) ); dialog.getFormField( FAIL_TESTCASE_ON_ERROR ).setEnabled( !Boolean.parseBoolean( String.valueOf( testCase.getFailOnError() ) ) ); values = dialog.show( values ); if( dialog.getReturnValue() == XFormDialog.OK_OPTION ) { try { testCase.setSearchProperties( Boolean.parseBoolean( values.get( SEARCH_PROPERTIES ) ) ); testCase.setKeepSession( Boolean.parseBoolean( values.get( KEEP_SESSION ) ) ); testCase.setDiscardOkResults( Boolean.parseBoolean( values.get( DISCARD_OK_RESULTS ) ) ); testCase.setFailOnError( Boolean.parseBoolean( values.get( FAIL_ON_ERROR ) ) ); testCase.setFailTestCaseOnErrors( Boolean.parseBoolean( values.get( FAIL_TESTCASE_ON_ERROR ) ) ); testCase.setTimeout( Long.parseLong( values.get( TESTCASE_TIMEOUT ) ) ); testCase.setMaxResults( Integer.parseInt( values.get( MAXRESULTS ) ) ); testCase.setWsrmEnabled( Boolean.parseBoolean( values.get( WS_RM_ENABLED ) ) ); testCase.setWsrmVersion( values.get( WS_RM_VERSION ) ); testCase.setWsrmAckTo( values.get( WS_RM_ACK_TO ) ); if( values.get( WS_RM_EXPIRES ) != null && values.get( WS_RM_EXPIRES ).length() > 0 ) testCase.setWsrmExpires( Long.parseLong( values.get( WS_RM_EXPIRES ) ) ); String timeout = values.get( SOCKET_TIMEOUT ); if( timeout.trim().length() == 0 ) testCase.getSettings().clearSetting( HttpSettings.SOCKET_TIMEOUT ); else testCase.getSettings().setString( HttpSettings.SOCKET_TIMEOUT, timeout ); testCase.setAmfAuthorisation( Boolean.parseBoolean( values.get( AMF_AUTHORISATION_ENABLE ) ) ); testCase.setAmfEndpoint( values.get( AMF_ENDPOINT ) ); testCase.setAmfLogin( values.get( AMF_LOGIN ) ); testCase.setAmfPassword( values.get( AMF_PASSWORD ) ); } catch( Exception e1 ) { UISupport.showErrorMessage( e1.getMessage() ); } } }
public void perform( WsdlTestCase testCase, Object param ) { if( dialog == null ) { XFormDialogBuilder builder = XFormFactory.createDialogBuilder( "TestCase Options" ); form = builder.createForm( "Basic" ); form.addCheckBox( SEARCH_PROPERTIES, "Search preceding TestSteps for property values" ); form.addCheckBox( KEEP_SESSION, "Maintain HTTP session" ); form.addCheckBox( FAIL_ON_ERROR, "Fail on error" ).addFormFieldListener( new XFormFieldListener() { public void valueChanged( XFormField sourceField, String newValue, String oldValue ) { form.getFormField( FAIL_TESTCASE_ON_ERROR ).setEnabled( !Boolean.parseBoolean( newValue ) ); } } ); form.addCheckBox( FAIL_TESTCASE_ON_ERROR, "Fail TestCase if it has failed TestSteps" ); form.addCheckBox( DISCARD_OK_RESULTS, "Discards successful TestStep results to preserve memory" ); form.addTextField( SOCKET_TIMEOUT, "Socket timeout in milliseconds", FieldType.TEXT ); form.addTextField( TESTCASE_TIMEOUT, "Timeout in milliseconds for entire TestCase", FieldType.TEXT ); form.addTextField( MAXRESULTS, "Maximum number of TestStep results to keep in memory during a run", FieldType.TEXT ); wsrmForm = builder.createForm( "WS-RM" ); wsrmForm.addCheckBox( WS_RM_ENABLED, "Use WS-Reliable Messaging" ); wsrmForm.addComboBox( WS_RM_VERSION, new String[] { WsrmVersionTypeConfig.X_1_0.toString(), WsrmVersionTypeConfig.X_1_1.toString(), WsrmVersionTypeConfig.X_1_2.toString() }, "The property for managing WS-RM version" ); wsrmForm.addTextField( WS_RM_ACK_TO, "Acknowledgments To", FieldType.TEXT ); wsrmForm.addTextField( WS_RM_EXPIRES, "Expires after", FieldType.TEXT ); amfForm = builder.createForm( "AMF" ); amfForm.addCheckBox( AMF_AUTHORISATION_ENABLE, "Enable AMF Session" ).addFormFieldListener( new AMFXFormFieldListener() ); amfForm.addTextField( AMF_ENDPOINT, "AMF Authorization endpoint", FieldType.TEXT ); amfForm.addTextField( AMF_LOGIN, "AMF Authorization usernmae", FieldType.TEXT ); amfForm.addTextField( AMF_PASSWORD, "AMF Authorization password", FieldType.PASSWORD ); dialog = builder.buildDialog( builder.buildOkCancelHelpActions( HelpUrls.TESTCASEOPTIONS_HELP_URL ), "Specify general options for this TestCase", UISupport.OPTIONS_ICON ); } StringToStringMap values = new StringToStringMap(); values.put( SEARCH_PROPERTIES, String.valueOf( testCase.getSearchProperties() ) ); values.put( KEEP_SESSION, String.valueOf( testCase.getKeepSession() ) ); values.put( FAIL_ON_ERROR, String.valueOf( testCase.getFailOnError() ) ); values.put( FAIL_TESTCASE_ON_ERROR, String.valueOf( testCase.getFailTestCaseOnErrors() ) ); values.put( DISCARD_OK_RESULTS, String.valueOf( testCase.getDiscardOkResults() ) ); values.put( SOCKET_TIMEOUT, String.valueOf( testCase.getSettings().getString( HttpSettings.SOCKET_TIMEOUT, "" ) ) ); values.put( TESTCASE_TIMEOUT, String.valueOf( testCase.getTimeout() ) ); values.put( MAXRESULTS, String.valueOf( testCase.getMaxResults() ) ); values.put( WS_RM_ENABLED, String.valueOf( testCase.getWsrmEnabled() ) ); values.put( WS_RM_VERSION, String.valueOf( testCase.getWsrmVersion() ) ); if( testCase.getWsrmAckTo() != null ) values.put( WS_RM_ACK_TO, String.valueOf( testCase.getWsrmAckTo() ) ); if( testCase.getWsrmExpires() != 0 ) values.put( WS_RM_EXPIRES, String.valueOf( testCase.getWsrmExpires() ) ); values.put( AMF_AUTHORISATION_ENABLE, String.valueOf( testCase.getAmfAuthorisation() ) ); values.put( AMF_ENDPOINT, String.valueOf( testCase.getAmfEndpoint() ) ); values.put( AMF_LOGIN, String.valueOf( testCase.getAmfLogin() ) ); values.put( AMF_PASSWORD, String.valueOf( testCase.getAmfPassword() ) ); dialog.getFormField( FAIL_TESTCASE_ON_ERROR ).setEnabled( !Boolean.parseBoolean( String.valueOf( testCase.getFailOnError() ) ) ); values = dialog.show( values ); if( dialog.getReturnValue() == XFormDialog.OK_OPTION ) { try { testCase.setSearchProperties( Boolean.parseBoolean( values.get( SEARCH_PROPERTIES ) ) ); testCase.setKeepSession( Boolean.parseBoolean( values.get( KEEP_SESSION ) ) ); testCase.setDiscardOkResults( Boolean.parseBoolean( values.get( DISCARD_OK_RESULTS ) ) ); testCase.setFailOnError( Boolean.parseBoolean( values.get( FAIL_ON_ERROR ) ) ); testCase.setFailTestCaseOnErrors( Boolean.parseBoolean( values.get( FAIL_TESTCASE_ON_ERROR ) ) ); testCase.setTimeout( Long.parseLong( values.get( TESTCASE_TIMEOUT ) ) ); testCase.setMaxResults( Integer.parseInt( values.get( MAXRESULTS ) ) ); testCase.setWsrmEnabled( Boolean.parseBoolean( values.get( WS_RM_ENABLED ) ) ); testCase.setWsrmVersion( values.get( WS_RM_VERSION ) ); testCase.setWsrmAckTo( values.get( WS_RM_ACK_TO ) ); if( values.get( WS_RM_EXPIRES ) != null && values.get( WS_RM_EXPIRES ).length() > 0 ) testCase.setWsrmExpires( Long.parseLong( values.get( WS_RM_EXPIRES ) ) ); String timeout = values.get( SOCKET_TIMEOUT ); if( timeout.trim().length() == 0 ) testCase.getSettings().clearSetting( HttpSettings.SOCKET_TIMEOUT ); else testCase.getSettings().setString( HttpSettings.SOCKET_TIMEOUT, timeout ); testCase.setAmfAuthorisation( Boolean.parseBoolean( values.get( AMF_AUTHORISATION_ENABLE ) ) ); testCase.setAmfEndpoint( values.get( AMF_ENDPOINT ) ); testCase.setAmfLogin( values.get( AMF_LOGIN ) ); testCase.setAmfPassword( values.get( AMF_PASSWORD ) ); } catch( Exception e1 ) { UISupport.showErrorMessage( e1.getMessage() ); } } }
diff --git a/testing-project/asakusa-test-data-provider/src/test/java/com/asakusafw/testdriver/excel/ExcelSheetSinkTest.java b/testing-project/asakusa-test-data-provider/src/test/java/com/asakusafw/testdriver/excel/ExcelSheetSinkTest.java index e12afae7c..1c1f5e6b8 100644 --- a/testing-project/asakusa-test-data-provider/src/test/java/com/asakusafw/testdriver/excel/ExcelSheetSinkTest.java +++ b/testing-project/asakusa-test-data-provider/src/test/java/com/asakusafw/testdriver/excel/ExcelSheetSinkTest.java @@ -1,353 +1,353 @@ /** * Copyright 2011-2013 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.testdriver.excel; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.asakusafw.testdriver.core.DataModelDefinition; import com.asakusafw.testdriver.core.DataModelReflection; import com.asakusafw.testdriver.core.DataModelSink; import com.asakusafw.testdriver.core.PropertyName; import com.asakusafw.testdriver.core.PropertyType; import com.asakusafw.testdriver.core.TestContext; import com.asakusafw.testdriver.model.SimpleDataModelDefinition; /** * Test for {@link ExcelSheetSink}. */ public class ExcelSheetSinkTest { static final DataModelDefinition<Simple> SIMPLE = new SimpleDataModelDefinition<Simple>(Simple.class); /** * Temporary folder. */ @Rule public final TemporaryFolder folder = new TemporaryFolder(); /** * simple. * @throws Exception if occur */ @Test public void simple() throws Exception { verify("simple.xls"); } /** * using xslx. * @throws Exception if occur */ @Test public void xssf() throws Exception { verify("simple.xlsx", ".xlsx"); } /** * automatically creates folder. * @throws Exception if occur */ @Test public void create_folder() throws Exception { File container = folder.newFolder("middle"); File file = new File(container, "file.xls"); assertThat(container.delete(), is(true)); assertThat(file.isFile(), is(false)); ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory(file); DataModelSink sink = factory.createSink(SIMPLE, new TestContext.Empty()); try { sink.put(SIMPLE.toReflection(new Simple())); } finally { sink.close(); } assertThat(file.isFile(), is(true)); } /** * multiple rows. * @throws Exception if occur */ @Test public void multiple() throws Exception { verify("multiple.xls"); } /** * contains blank cells. * @throws Exception if occur */ @Test public void blank_cell() throws Exception { verify("blank_cell.xls"); } /** * stringified by '. * @throws Exception if occur */ @Test public void stringify() throws Exception { verify("stringify.xls"); } /** * empty string. * @throws Exception if occur */ @Test public void empty_string() throws Exception { verify("empty_string.xls"); } /** * boolean values. * @throws Exception if occur */ @Test public void boolean_values() throws Exception { verify("boolean.xls"); } /** * byte values. * @throws Exception if occur */ @Test public void byte_values() throws Exception { verify("byte.xls"); } /** * short values. * @throws Exception if occur */ @Test public void short_values() throws Exception { verify("short.xls"); } /** * int values. * @throws Exception if occur */ @Test public void int_values() throws Exception { verify("int.xls"); } /** * long values. * @throws Exception if occur */ @Test public void long_values() throws Exception { verify("long.xls"); } /** * float values. * @throws Exception if occur */ @Test public void float_values() throws Exception { verify("float.xls"); } /** * double values. * @throws Exception if occur */ @Test public void double_values() throws Exception { verify("double.xls"); } /** * big integer values. * @throws Exception if occur */ @Test public void integer_values() throws Exception { verify("integer.xls"); } /** * big decimal values. * @throws Exception if occur */ @Test public void decimal_values() throws Exception { verify("decimal.xls"); } /** * date values. * @throws Exception if occur */ @Test public void date_values() throws Exception { verify("date.xls"); } /** * date values. * @throws Exception if occur */ @Test public void datetime_values() throws Exception { verify("datetime.xls"); } /** * contains blank row. * @throws Exception if occur */ @Test public void blank_row() throws Exception { verify("blank_row.xls"); } /** * contains blank row but is decorated. * @throws Exception if occur */ @Test public void decorated_blank_row() throws Exception { verify("decorated_blank_row.xls"); } /** * many columns. * @throws Exception if occur */ @Test public void many_columns() throws Exception { Object[] value = new Object[256]; Map<PropertyName, PropertyType> map = new TreeMap<PropertyName, PropertyType>(); for (int i = 0; i < value.length; i++) { map.put(PropertyName.newInstance(String.format("p%04x", i)), PropertyType.INT); value[i] = i; } ArrayModelDefinition def = new ArrayModelDefinition(map); File file = folder.newFile("temp.xls"); ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory(file); DataModelSink sink = factory.createSink(def, new TestContext.Empty()); try { sink.put(def.toReflection(value)); } finally { sink.close(); } InputStream in = new FileInputStream(file); try { Workbook workbook = Util.openWorkbookFor(file.getPath(), in); Sheet sheet = workbook.getSheetAt(0); Row title = sheet.getRow(0); - assertThat(title.getLastCellNum(), is((short) 255)); + assertThat(title.getLastCellNum(), is((short) 256)); Row content = sheet.getRow(1); for (int i = 0; i < title.getLastCellNum(); i++) { assertThat(content.getCell(i).getNumericCellValue(), is((double) (Integer) value[i])); } } finally { in.close(); } } private void verify(String file) throws IOException { verify(file, ".xls"); } private void verify(String file, String extension) throws IOException { Set<DataModelReflection> expected = collect(open(file)); File temp = folder.newFile("temp" + extension); ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory(temp); DataModelSink sink = factory.createSink(SIMPLE, new TestContext.Empty()); try { for (DataModelReflection model : expected) { sink.put(model); } } finally { sink.close(); } Set<DataModelReflection> actual = collect(open(temp.toURI().toURL())); assertThat(actual, is(expected)); } private Set<DataModelReflection> collect(ExcelSheetDataModelSource source) throws IOException { Set<DataModelReflection> results = new HashSet<DataModelReflection>(); try { while (true) { DataModelReflection next = source.next(); if (next == null) { break; } assertThat(next.toString(), results.contains(source), is(false)); results.add(next); } } finally { source.close(); } return results; } private ExcelSheetDataModelSource open(String file) throws IOException { URL resource = getClass().getResource("data/" + file); assertThat(file, resource, not(nullValue())); return open(resource); } private ExcelSheetDataModelSource open(URL resource) throws IOException { URI uri; try { uri = resource.toURI(); } catch (URISyntaxException e) { throw new AssertionError(e); } InputStream in = resource.openStream(); try { Workbook book = Util.openWorkbookFor(resource.getFile(), in); Sheet sheet = book.getSheetAt(0); return new ExcelSheetDataModelSource(SIMPLE, uri, sheet); } finally { in.close(); } } }
true
true
public void many_columns() throws Exception { Object[] value = new Object[256]; Map<PropertyName, PropertyType> map = new TreeMap<PropertyName, PropertyType>(); for (int i = 0; i < value.length; i++) { map.put(PropertyName.newInstance(String.format("p%04x", i)), PropertyType.INT); value[i] = i; } ArrayModelDefinition def = new ArrayModelDefinition(map); File file = folder.newFile("temp.xls"); ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory(file); DataModelSink sink = factory.createSink(def, new TestContext.Empty()); try { sink.put(def.toReflection(value)); } finally { sink.close(); } InputStream in = new FileInputStream(file); try { Workbook workbook = Util.openWorkbookFor(file.getPath(), in); Sheet sheet = workbook.getSheetAt(0); Row title = sheet.getRow(0); assertThat(title.getLastCellNum(), is((short) 255)); Row content = sheet.getRow(1); for (int i = 0; i < title.getLastCellNum(); i++) { assertThat(content.getCell(i).getNumericCellValue(), is((double) (Integer) value[i])); } } finally { in.close(); } }
public void many_columns() throws Exception { Object[] value = new Object[256]; Map<PropertyName, PropertyType> map = new TreeMap<PropertyName, PropertyType>(); for (int i = 0; i < value.length; i++) { map.put(PropertyName.newInstance(String.format("p%04x", i)), PropertyType.INT); value[i] = i; } ArrayModelDefinition def = new ArrayModelDefinition(map); File file = folder.newFile("temp.xls"); ExcelSheetSinkFactory factory = new ExcelSheetSinkFactory(file); DataModelSink sink = factory.createSink(def, new TestContext.Empty()); try { sink.put(def.toReflection(value)); } finally { sink.close(); } InputStream in = new FileInputStream(file); try { Workbook workbook = Util.openWorkbookFor(file.getPath(), in); Sheet sheet = workbook.getSheetAt(0); Row title = sheet.getRow(0); assertThat(title.getLastCellNum(), is((short) 256)); Row content = sheet.getRow(1); for (int i = 0; i < title.getLastCellNum(); i++) { assertThat(content.getCell(i).getNumericCellValue(), is((double) (Integer) value[i])); } } finally { in.close(); } }
diff --git a/webit-script/src/main/java/webit/script/core/ast/operators/MinusMinusBefore.java b/webit-script/src/main/java/webit/script/core/ast/operators/MinusMinusBefore.java index 8ce48313..983cca03 100644 --- a/webit-script/src/main/java/webit/script/core/ast/operators/MinusMinusBefore.java +++ b/webit-script/src/main/java/webit/script/core/ast/operators/MinusMinusBefore.java @@ -1,28 +1,28 @@ // Copyright (c) 2013-2014, Webit Team. All Rights Reserved. package webit.script.core.ast.operators; import webit.script.Context; import webit.script.core.ast.AbstractExpression; import webit.script.core.ast.ResetableValueExpression; import webit.script.util.ALU; import webit.script.util.StatementUtil; /** * * @author Zqq */ public final class MinusMinusBefore extends AbstractExpression { private final ResetableValueExpression expr; public MinusMinusBefore(ResetableValueExpression expr, int line, int column) { super(line, column); this.expr = expr; } public Object execute(final Context context) { final ResetableValueExpression _expr; - return StatementUtil.executeSetValue(_expr = this.expr, context, ALU.plusOne( + return StatementUtil.executeSetValue(_expr = this.expr, context, ALU.minusOne( StatementUtil.execute(_expr, context))); } }
true
true
public Object execute(final Context context) { final ResetableValueExpression _expr; return StatementUtil.executeSetValue(_expr = this.expr, context, ALU.plusOne( StatementUtil.execute(_expr, context))); }
public Object execute(final Context context) { final ResetableValueExpression _expr; return StatementUtil.executeSetValue(_expr = this.expr, context, ALU.minusOne( StatementUtil.execute(_expr, context))); }
diff --git a/ips/src/main/java/de/bergischweb/ips/Main.java b/ips/src/main/java/de/bergischweb/ips/Main.java index 9719d95..772e370 100644 --- a/ips/src/main/java/de/bergischweb/ips/Main.java +++ b/ips/src/main/java/de/bergischweb/ips/Main.java @@ -1,89 +1,90 @@ /* * Copyright 2010 Johannes Th&ouml;nes <[email protected]>. * * 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. * under the License. */ package de.bergischweb.ips; import org.jruby.embed.PathType; import org.jruby.embed.ScriptingContainer; import javax.swing.*; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; /** * The Main class for starting the scripts. * * @author Copyright 2010 Johannes Th&ouml;nes <[email protected]> */ public class Main { public static class FatalExceptionHandler implements Thread.UncaughtExceptionHandler { /** * Method invoked when the given thread terminates due to the * given uncaught exception. * <p>Any exception thrown by this method will be ignored by the * Java Virtual Machine. * * @param t the thread * @param e the exception */ @Override public void uncaughtException(Thread t, Throwable e) { try { - File f = File.createTempFile("error", "log"); + File f = File.createTempFile("error", ".log"); PrintWriter writer = new PrintWriter(f); e.printStackTrace(writer); + writer.close(); message("Unexpected Error", "An error occured. Please see the log file " + f.getPath()); e.printStackTrace(); } catch (Exception e1) { StringWriter result = new StringWriter(); PrintWriter writer = new PrintWriter(result); e1.printStackTrace(writer); message("Fatal Error", "StackTrace: \n\n" + result.toString()); e1.printStackTrace(); } } private void message(String title, String message) { JOptionPane.showMessageDialog(null, message, "Error", JOptionPane.ERROR_MESSAGE); } } /** * The entry point into the simulation. * <p/> * Executes the Ruby Start Scripts. The first parameter is the name of the script. * The rest ist passed as parameter to the script. * * @param args Ignored */ public static void main(String... args) throws IOException { Thread.setDefaultUncaughtExceptionHandler(new FatalExceptionHandler()); ClassLoader classLoader = Main.class.getClassLoader(); ScriptingContainer container = new ScriptingContainer(); container.put("$CLASS_LOADER", container.getProvider().getRuntime().getJRubyClassLoader()); container.runScriptlet(PathType.CLASSPATH, "scripts/run_gui.rb"); } }
false
true
public void uncaughtException(Thread t, Throwable e) { try { File f = File.createTempFile("error", "log"); PrintWriter writer = new PrintWriter(f); e.printStackTrace(writer); message("Unexpected Error", "An error occured. Please see the log file " + f.getPath()); e.printStackTrace(); } catch (Exception e1) { StringWriter result = new StringWriter(); PrintWriter writer = new PrintWriter(result); e1.printStackTrace(writer); message("Fatal Error", "StackTrace: \n\n" + result.toString()); e1.printStackTrace(); } }
public void uncaughtException(Thread t, Throwable e) { try { File f = File.createTempFile("error", ".log"); PrintWriter writer = new PrintWriter(f); e.printStackTrace(writer); writer.close(); message("Unexpected Error", "An error occured. Please see the log file " + f.getPath()); e.printStackTrace(); } catch (Exception e1) { StringWriter result = new StringWriter(); PrintWriter writer = new PrintWriter(result); e1.printStackTrace(writer); message("Fatal Error", "StackTrace: \n\n" + result.toString()); e1.printStackTrace(); } }
diff --git a/illaclient/src/illarion/client/world/MusicBox.java b/illaclient/src/illarion/client/world/MusicBox.java index e9098c08..c7544e43 100644 --- a/illaclient/src/illarion/client/world/MusicBox.java +++ b/illaclient/src/illarion/client/world/MusicBox.java @@ -1,241 +1,241 @@ /* * This file is part of the Illarion Client. * * Copyright © 2013 - Illarion e.V. * * The Illarion Client 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. * * The Illarion Client 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 the Illarion Client. If not, see <http://www.gnu.org/licenses/>. */ package illarion.client.world; import illarion.client.IllaClient; import illarion.client.resources.SongFactory; import illarion.common.config.Config; import illarion.common.config.ConfigChangedEvent; import illarion.common.util.Stoppable; import illarion.common.util.StoppableStorage; import org.apache.log4j.Logger; import org.bushe.swing.event.annotation.AnnotationProcessor; import org.bushe.swing.event.annotation.EventTopicPatternSubscriber; import org.illarion.engine.Engine; import org.illarion.engine.sound.Music; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.NotThreadSafe; /** * This is the music box. What is does is playing music. This class handles the playback of the background music * according to the settings. Also it ensures that the different overwriting levels of the music are kept as they are * supposed to be. * * @author Martin Karing &lt;[email protected]&gt; */ @NotThreadSafe public final class MusicBox implements Stoppable { /** * The ID of the combat music. */ private static final int COMBAT_TRACK = 1; /** * This is the constant that applies in case no overwrite track is set and the background music is supposed to * play the default music. */ public static final int NO_TRACK = 0; /** * The current music track that is playing. */ private int currentDefaultTrack; /** * The ID of the music that is currently played. */ private int currentMusicId; /** * This flag is set {@code true} in case the music box is supposed to play the fighting background music. * This overwrites any other track that is currently played. */ private boolean fightingMusicPlaying; /** * This variable stores the ID of the track that overwrites the current * default track. */ private int overrideSoundId; @Nonnull private final Engine engine; /** * This is the constructor that prepares this class for proper operation. */ MusicBox(@Nonnull final Engine engine) { this.engine = engine; overrideSoundId = NO_TRACK; fightingMusicPlaying = false; currentDefaultTrack = NO_TRACK; StoppableStorage.getInstance().add(this); AnnotationProcessor.process(this); updateSettings(null, IllaClient.getCfg()); } private void updateSettings(@Nullable final String setting, @Nonnull final Config cfg) { if ((setting == null) || "musicOn".equals(setting)) { final boolean musicEnabled = cfg.getBoolean("musicOn"); if (musicEnabled) { final float musicVolume = cfg.getFloat("musicVolume") / Player.MAX_CLIENT_VOL; engine.getSounds().setMusicVolume(musicVolume); } else { engine.getSounds().setMusicVolume(0.f); } } if ((setting == null) || "musicVolume".equals(setting)) { final float musicVolume = cfg.getFloat("musicVolume") / Player.MAX_CLIENT_VOL; if (IllaClient.getCfg().getBoolean("musicOn")) { engine.getSounds().setMusicVolume(musicVolume); } } if ((setting == null) || "soundOn".equals(setting)) { final boolean soundEnabled = cfg.getBoolean("soundOn"); if (soundEnabled) { final float soundVolume = cfg.getFloat("soundVolume") / Player.MAX_CLIENT_VOL; engine.getSounds().setSoundVolume(soundVolume); } else { engine.getSounds().setSoundVolume(0.f); } } if ((setting == null) || "soundVolume".equals(setting)) { final float soundVolume = cfg.getFloat("soundVolume") / Player.MAX_CLIENT_VOL; if (IllaClient.getCfg().getBoolean("soundOn")) { - engine.getSounds().setMusicVolume(soundVolume); + engine.getSounds().setSoundVolume(soundVolume); } } } @EventTopicPatternSubscriber(topicPattern = "((music)|(sound))((On)|(Volume))") public void onUpdateSoundMusicConfig(@Nonnull final String topic, @Nonnull final ConfigChangedEvent data) { updateSettings(topic, data.getConfig()); } /** * Play the default music now that is set by the tile the player is standing on. */ public void playDefaultMusic() { playMusicTrack(NO_TRACK); } /** * Play the fighting sound track now. This will overwrite all other playback. */ public void playFightingMusic() { if (!fightingMusicPlaying) { fightingMusicPlaying = true; } } /** * Set the sound ID that is supposed to be played. This will overwrite the default sound track that is set with * the music ID embedded to the tiles. * * @param musicId the ID of the music to play */ public void playMusicTrack(final int musicId) { if (musicId != overrideSoundId) { overrideSoundId = musicId; } } @Override public void saveShutdown() { engine.getSounds().stopMusic(0); } /** * Set the sound track that is supposed to be played now. This function does not perform any additional checks. * It will plain and simple start playing the newly chosen sound track now. It does this even in case the current * and the new sound track are equal. * * @param id the ID of the sound track to play */ private void setSoundTrack(final int id) { if (currentMusicId == id) { return; } currentMusicId = id; if (id == NO_TRACK) { engine.getSounds().stopMusic(500); return; } final Music currentMusic = SongFactory.getInstance().getSong(id, engine.getAssets().getSoundsManager()); if (currentMusic == null) { LOGGER.error("Requested music was not found: " + id); return; } engine.getSounds().playMusic(currentMusic, 250, 250); } /** * The logging instance that takes care for the logging output of this class. */ private static final Logger LOGGER = Logger.getLogger(MusicBox.class); /** * Stop playing the fighting music and fall back to the last sound track played. */ public void stopFightingMusic() { if (fightingMusicPlaying) { fightingMusicPlaying = false; } } /** * Update the location where the player is currently at. This will update the soundtrack that is played in case * its needed. */ public void updatePlayerLocation() { final MapTile tile = World.getMap().getMapAt(World.getPlayer().getLocation()); final int newId; if (tile == null) { // in case the tile is not found, stick with the default tracks to prevent the music from acting up newId = currentDefaultTrack; } else { newId = tile.getTileMusic(); } if (newId != currentDefaultTrack) { currentDefaultTrack = newId; } } /** * This handler is called during the update loop and should be used to change the currently played music to make * sure that changing the music is in sync with the rest of the game. */ public void update() { if (fightingMusicPlaying) { setSoundTrack(COMBAT_TRACK); } else if (overrideSoundId > NO_TRACK) { setSoundTrack(overrideSoundId); } else { setSoundTrack(currentDefaultTrack); } } }
true
true
private void updateSettings(@Nullable final String setting, @Nonnull final Config cfg) { if ((setting == null) || "musicOn".equals(setting)) { final boolean musicEnabled = cfg.getBoolean("musicOn"); if (musicEnabled) { final float musicVolume = cfg.getFloat("musicVolume") / Player.MAX_CLIENT_VOL; engine.getSounds().setMusicVolume(musicVolume); } else { engine.getSounds().setMusicVolume(0.f); } } if ((setting == null) || "musicVolume".equals(setting)) { final float musicVolume = cfg.getFloat("musicVolume") / Player.MAX_CLIENT_VOL; if (IllaClient.getCfg().getBoolean("musicOn")) { engine.getSounds().setMusicVolume(musicVolume); } } if ((setting == null) || "soundOn".equals(setting)) { final boolean soundEnabled = cfg.getBoolean("soundOn"); if (soundEnabled) { final float soundVolume = cfg.getFloat("soundVolume") / Player.MAX_CLIENT_VOL; engine.getSounds().setSoundVolume(soundVolume); } else { engine.getSounds().setSoundVolume(0.f); } } if ((setting == null) || "soundVolume".equals(setting)) { final float soundVolume = cfg.getFloat("soundVolume") / Player.MAX_CLIENT_VOL; if (IllaClient.getCfg().getBoolean("soundOn")) { engine.getSounds().setMusicVolume(soundVolume); } } }
private void updateSettings(@Nullable final String setting, @Nonnull final Config cfg) { if ((setting == null) || "musicOn".equals(setting)) { final boolean musicEnabled = cfg.getBoolean("musicOn"); if (musicEnabled) { final float musicVolume = cfg.getFloat("musicVolume") / Player.MAX_CLIENT_VOL; engine.getSounds().setMusicVolume(musicVolume); } else { engine.getSounds().setMusicVolume(0.f); } } if ((setting == null) || "musicVolume".equals(setting)) { final float musicVolume = cfg.getFloat("musicVolume") / Player.MAX_CLIENT_VOL; if (IllaClient.getCfg().getBoolean("musicOn")) { engine.getSounds().setMusicVolume(musicVolume); } } if ((setting == null) || "soundOn".equals(setting)) { final boolean soundEnabled = cfg.getBoolean("soundOn"); if (soundEnabled) { final float soundVolume = cfg.getFloat("soundVolume") / Player.MAX_CLIENT_VOL; engine.getSounds().setSoundVolume(soundVolume); } else { engine.getSounds().setSoundVolume(0.f); } } if ((setting == null) || "soundVolume".equals(setting)) { final float soundVolume = cfg.getFloat("soundVolume") / Player.MAX_CLIENT_VOL; if (IllaClient.getCfg().getBoolean("soundOn")) { engine.getSounds().setSoundVolume(soundVolume); } } }
diff --git a/dune-server/src/main/java/lv/k2611a/domain/unitgoals/Move.java b/dune-server/src/main/java/lv/k2611a/domain/unitgoals/Move.java index 00015c8..d6b76b8 100644 --- a/dune-server/src/main/java/lv/k2611a/domain/unitgoals/Move.java +++ b/dune-server/src/main/java/lv/k2611a/domain/unitgoals/Move.java @@ -1,89 +1,91 @@ package lv.k2611a.domain.unitgoals; import java.util.List; import lv.k2611a.domain.Map; import lv.k2611a.domain.Unit; import lv.k2611a.domain.ViewDirection; import lv.k2611a.util.AStar; import lv.k2611a.util.Node; import lv.k2611a.util.Point; public class Move implements UnitGoal { private int goalX; private int goalY; private List<Node> path; private AStar aStarCache = new AStar(); public Move(int goalX, int goalY) { this.goalX = goalX; this.goalY = goalY; } public Move(Point point) { this.goalX = point.getX(); this.goalY = point.getY(); } public int getGoalX() { return goalX; } public int getGoalY() { return goalY; } @Override public void process(Unit unit, Map map) { if (path == null) { path = aStarCache.calcShortestPath(unit.getX(), unit.getY(), goalX, goalY, map, unit.getId()); lookAtNextNode(unit); } if (path.isEmpty()) { unit.removeGoal(this); + unit.setTicksMovingToNextCell(0); return; } int ticksToNextCell = unit.getUnitType().getSpeed(); if (unit.getTicksMovingToNextCell() >= ticksToNextCell-1) { // moved to new cell unit.setTicksMovingToNextCell(0); Node next = path.get(0); unit.setX(next.getX()); unit.setY(next.getY()); path.remove(next); if (!(path.isEmpty())) { next = path.get(0); // recalc path if we hit an obstacle if (map.isObstacle(next, unit.getId())) { path = aStarCache.calcShortestPath(unit.getX(), unit.getY(), goalX, goalY, map, unit.getId()); } lookAtNextNode(unit); } } else { if (!path.isEmpty()) { Node next = path.get(0); if (map.isObstacle(next, unit.getId())) { path = aStarCache.calcShortestPath(unit.getX(), unit.getY(), goalX, goalY, map, unit.getId()); lookAtNextNode(unit); } else { unit.setTicksMovingToNextCell(unit.getTicksMovingToNextCell() + 1); } } } if (path.isEmpty()) { unit.removeGoal(null); + unit.setTicksMovingToNextCell(0); } } private void lookAtNextNode(Unit unit) { if (path.isEmpty()) { return; } Node next = path.get(0); unit.setViewDirection(ViewDirection.getDirection(unit.getX(), unit.getY(), next.getX(), next.getY())); } }
false
true
public void process(Unit unit, Map map) { if (path == null) { path = aStarCache.calcShortestPath(unit.getX(), unit.getY(), goalX, goalY, map, unit.getId()); lookAtNextNode(unit); } if (path.isEmpty()) { unit.removeGoal(this); return; } int ticksToNextCell = unit.getUnitType().getSpeed(); if (unit.getTicksMovingToNextCell() >= ticksToNextCell-1) { // moved to new cell unit.setTicksMovingToNextCell(0); Node next = path.get(0); unit.setX(next.getX()); unit.setY(next.getY()); path.remove(next); if (!(path.isEmpty())) { next = path.get(0); // recalc path if we hit an obstacle if (map.isObstacle(next, unit.getId())) { path = aStarCache.calcShortestPath(unit.getX(), unit.getY(), goalX, goalY, map, unit.getId()); } lookAtNextNode(unit); } } else { if (!path.isEmpty()) { Node next = path.get(0); if (map.isObstacle(next, unit.getId())) { path = aStarCache.calcShortestPath(unit.getX(), unit.getY(), goalX, goalY, map, unit.getId()); lookAtNextNode(unit); } else { unit.setTicksMovingToNextCell(unit.getTicksMovingToNextCell() + 1); } } } if (path.isEmpty()) { unit.removeGoal(null); } }
public void process(Unit unit, Map map) { if (path == null) { path = aStarCache.calcShortestPath(unit.getX(), unit.getY(), goalX, goalY, map, unit.getId()); lookAtNextNode(unit); } if (path.isEmpty()) { unit.removeGoal(this); unit.setTicksMovingToNextCell(0); return; } int ticksToNextCell = unit.getUnitType().getSpeed(); if (unit.getTicksMovingToNextCell() >= ticksToNextCell-1) { // moved to new cell unit.setTicksMovingToNextCell(0); Node next = path.get(0); unit.setX(next.getX()); unit.setY(next.getY()); path.remove(next); if (!(path.isEmpty())) { next = path.get(0); // recalc path if we hit an obstacle if (map.isObstacle(next, unit.getId())) { path = aStarCache.calcShortestPath(unit.getX(), unit.getY(), goalX, goalY, map, unit.getId()); } lookAtNextNode(unit); } } else { if (!path.isEmpty()) { Node next = path.get(0); if (map.isObstacle(next, unit.getId())) { path = aStarCache.calcShortestPath(unit.getX(), unit.getY(), goalX, goalY, map, unit.getId()); lookAtNextNode(unit); } else { unit.setTicksMovingToNextCell(unit.getTicksMovingToNextCell() + 1); } } } if (path.isEmpty()) { unit.removeGoal(null); unit.setTicksMovingToNextCell(0); } }
diff --git a/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java b/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java index 1bffe6c2..aa5bab1a 100644 --- a/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java +++ b/src/uk/me/parabola/mkgmap/osmstyle/StyledConverter.java @@ -1,938 +1,938 @@ /* * Copyright (C) 2007 Steve Ratcliffe * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * * Author: Steve Ratcliffe * Create date: Feb 17, 2008 */ package uk.me.parabola.mkgmap.osmstyle; import java.util.ArrayList; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import uk.me.parabola.imgfmt.app.Area; import uk.me.parabola.imgfmt.app.Coord; import uk.me.parabola.imgfmt.app.CoordNode; import uk.me.parabola.imgfmt.app.Exit; import uk.me.parabola.log.Logger; import uk.me.parabola.mkgmap.general.AreaClipper; import uk.me.parabola.mkgmap.general.Clipper; import uk.me.parabola.mkgmap.general.LineAdder; import uk.me.parabola.mkgmap.general.LineClipper; import uk.me.parabola.mkgmap.general.MapCollector; import uk.me.parabola.mkgmap.general.MapElement; import uk.me.parabola.mkgmap.general.MapExitPoint; import uk.me.parabola.mkgmap.general.MapLine; import uk.me.parabola.mkgmap.general.MapPoint; import uk.me.parabola.mkgmap.general.MapRoad; import uk.me.parabola.mkgmap.general.MapShape; import uk.me.parabola.mkgmap.general.RoadNetwork; import uk.me.parabola.mkgmap.reader.osm.Element; import uk.me.parabola.mkgmap.reader.osm.GType; import uk.me.parabola.mkgmap.reader.osm.Node; import uk.me.parabola.mkgmap.reader.osm.OsmConverter; import uk.me.parabola.mkgmap.reader.osm.Relation; import uk.me.parabola.mkgmap.reader.osm.RestrictionRelation; import uk.me.parabola.mkgmap.reader.osm.Rule; import uk.me.parabola.mkgmap.reader.osm.Style; import uk.me.parabola.mkgmap.reader.osm.Way; /** * Convert from OSM to the mkgmap intermediate format using a style. * A style is a collection of files that describe the mappings to be used * when converting. * * @author Steve Ratcliffe */ public class StyledConverter implements OsmConverter { private static final Logger log = Logger.getLogger(StyledConverter.class); private final String[] nameTagList; private final MapCollector collector; private Clipper clipper = Clipper.NULL_CLIPPER; private Area bbox; private Set<Coord> boundaryCoords = new HashSet<Coord>(); // restrictions associates lists of turn restrictions with the // Coord corresponding to the restrictions' 'via' node private final Map<Coord, List<RestrictionRelation>> restrictions = new IdentityHashMap<Coord, List<RestrictionRelation>>(); // originalWay associates Ways that have been created due to // splitting or clipping with the Ways that they were derived // from private final Map<Way, Way> originalWay = new HashMap<Way, Way>(); // limit arc lengths to what can currently be handled by RouteArc private final int MAX_ARC_LENGTH = 75000; private final int MAX_POINTS_IN_WAY = 200; private final int MAX_NODES_IN_WAY = 16; private final double MIN_DISTANCE_BETWEEN_NODES = 5.5; // nodeIdMap maps a Coord into a nodeId private final Map<Coord, Integer> nodeIdMap = new IdentityHashMap<Coord, Integer>(); private int nextNodeId = 1; private final Rule wayRules; private final Rule nodeRules; private final Rule relationRules; private boolean ignoreMaxspeeds; class AccessMapping { private final String type; private final int index; AccessMapping(String type, int index) { this.type = type; this.index = index; } } private final AccessMapping[] accessMap = { new AccessMapping("access", RoadNetwork.NO_MAX), // must be first in list new AccessMapping("bicycle", RoadNetwork.NO_BIKE), new AccessMapping("foot", RoadNetwork.NO_FOOT), new AccessMapping("hgv", RoadNetwork.NO_TRUCK), new AccessMapping("motorcar", RoadNetwork.NO_CAR), new AccessMapping("motorcycle", RoadNetwork.NO_CAR), new AccessMapping("psv", RoadNetwork.NO_BUS), new AccessMapping("taxi", RoadNetwork.NO_TAXI), new AccessMapping("emergency", RoadNetwork.NO_EMERGENCY), new AccessMapping("delivery", RoadNetwork.NO_DELIVERY), new AccessMapping("goods", RoadNetwork.NO_DELIVERY), }; private LineAdder lineAdder = new LineAdder() { public void add(MapLine element) { if (element instanceof MapRoad) collector.addRoad((MapRoad) element); else collector.addLine(element); } }; public StyledConverter(Style style, MapCollector collector, Properties props) { this.collector = collector; nameTagList = style.getNameTagList(); wayRules = style.getWayRules(); nodeRules = style.getNodeRules(); relationRules = style.getRelationRules(); ignoreMaxspeeds = props.getProperty("ignore-maxspeeds") != null; LineAdder overlayAdder = style.getOverlays(lineAdder); if (overlayAdder != null) lineAdder = overlayAdder; } /** * This takes the way and works out what kind of map feature it is and makes * the relevant call to the mapper callback. * <p> * As a few examples we might want to check for the 'highway' tag, work out * if it is an area of a park etc. * * @param way The OSM way. */ public void convertWay(Way way) { if (way.getPoints().size() < 2) return; preConvertRules(way); GType foundType = wayRules.resolveType(way); if (foundType == null) return; postConvertRules(way, foundType); if (foundType.getFeatureKind() == GType.POLYLINE) { if(foundType.isRoad()) addRoad(way, foundType); else addLine(way, foundType); } else addShape(way, foundType); } /** * Takes a node (that has its own identity) and converts it from the OSM * type to the Garmin map type. * * @param node The node to convert. */ public void convertNode(Node node) { preConvertRules(node); GType foundType = nodeRules.resolveType(node); if (foundType == null) return; postConvertRules(node, foundType); addPoint(node, foundType); } /** * Rules to run before converting the element. */ private void preConvertRules(Element el) { if (nameTagList == null) return; for (String t : nameTagList) { String val = el.getTag(t); if (val != null) { el.addTag("name", val); break; } } } /** * Built in rules to run after converting the element. */ private void postConvertRules(Element el, GType type) { // Set the name from the 'name' tag or failing that from // the default_name. el.setName(el.getTag("name")); if (el.getName() == null) el.setName(type.getDefaultName()); } /** * Set the bounding box for this map. This should be set before any other * elements are converted if you want to use it. All elements that are added * are clipped to this box, new points are added as needed at the boundry. * * If a node or a way falls completely outside the boundry then it would be * ommited. This would not normally happen in the way this option is typically * used however. * * @param bbox The bounding area. */ public void setBoundingBox(Area bbox) { this.clipper = new AreaClipper(bbox); this.bbox = bbox; } /** * Run the rules for this relation. As this is not an end object, then * the only useful rules are action rules that set tags on the contained * ways or nodes. Every rule should probably start with 'type=".."'. * * @param relation The relation to convert. */ public void convertRelation(Relation relation) { // Relations never resolve to a GType and so we ignore the return // value. relationRules.resolveType(relation); if(relation instanceof RestrictionRelation) { RestrictionRelation rr = (RestrictionRelation)relation; if(rr.isValid()) { List<RestrictionRelation> lrr = restrictions.get(rr.getViaCoord()); if(lrr == null) { lrr = new ArrayList<RestrictionRelation>(); restrictions.put(rr.getViaCoord(), lrr); } lrr.add(rr); } } } private void addLine(Way way, GType gt) { MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(way.getPoints()); if (way.isBoolTag("oneway")) line.setDirection(true); clipper.clipLine(line, lineAdder); } private void addShape(Way way, GType gt) { MapShape shape = new MapShape(); elementSetup(shape, gt, way); shape.setPoints(way.getPoints()); clipper.clipShape(shape, collector); GType pointType = nodeRules.resolveType(way); if(pointType != null) shape.setPoiType(pointType.getType()); } private void addPoint(Node node, GType gt) { if (!clipper.contains(node.getLocation())) return; // to handle exit points we use a subclass of MapPoint // to carry some extra info (a reference to the // motorway associated with the exit) MapPoint mp; int type = gt.getType(); if(type >= 0x2000 && type < 0x2800) { String ref = node.getTag(Exit.TAG_ROAD_REF); String id = node.getTag("osm:id"); if(ref != null) { String to = node.getTag(Exit.TAG_TO); MapExitPoint mep = new MapExitPoint(ref, to); String fd = node.getTag(Exit.TAG_FACILITY); if(fd != null) mep.setFacilityDescription(fd); if(id != null) mep.setOSMId(id); mp = mep; } else { mp = new MapPoint(); log.warn("Motorway exit " + node.getName() + " (OSM id " + id + ") located at " + node.getLocation().toDegreeString() + " has no motorway! (either make the exit share a node with the motorway or specify the motorway ref with a " + Exit.TAG_ROAD_REF + " tag)"); } } else { mp = new MapPoint(); } elementSetup(mp, gt, node); mp.setLocation(node.getLocation()); collector.addPoint(mp); } private String combineRefs(Element element) { String ref = element.getTag("ref"); String int_ref = element.getTag("int_ref"); if(int_ref != null) { if(ref == null) ref = int_ref; else ref += ";" + int_ref; } String nat_ref = element.getTag("nat_ref"); if(nat_ref != null) { if(ref == null) ref = nat_ref; else ref += ";" + nat_ref; } String reg_ref = element.getTag("reg_ref"); if(reg_ref != null) { if(ref == null) ref = reg_ref; else ref += ";" + reg_ref; } return ref; } private void elementSetup(MapElement ms, GType gt, Element element) { String name = element.getName(); String refs = combineRefs(element); if(name == null && refs != null) { // use first ref as name name = refs.split(";")[0].trim(); } if(name != null) ms.setName(name); if(refs != null) ms.setRef(refs); ms.setType(gt.getType()); ms.setMinResolution(gt.getMinResolution()); ms.setMaxResolution(gt.getMaxResolution()); // Now try to get some address info for POIs String city = element.getTag("addr:city"); String zip = element.getTag("addr:postcode"); String street = element.getTag("addr:street"); String houseNumber = element.getTag("addr:housenumber"); String phone = element.getTag("phone"); String isIn = element.getTag("is_in"); String country = element.getTag("is_in:country"); String region = element.getTag("is_in:county"); if(country != null) country = element.getTag("addr:country"); if(zip == null) zip = element.getTag("openGeoDB:postal_codes"); if(city == null) city = element.getTag("openGeoDB:sort_name"); if(city != null) ms.setCity(city); if(zip != null) ms.setZip(zip); if(street != null) ms.setStreet(street); if(houseNumber != null) ms.setHouseNumber(houseNumber); if(isIn != null) ms.setIsIn(isIn); if(phone != null) ms.setPhone(phone); if(country != null) ms.setCountry(country); if(region != null) ms.setRegion(region); } void addRoad(Way way, GType gt) { if("roundabout".equals(way.getTag("junction"))) { String frigFactorTag = way.getTag("mkgmap:frig_roundabout"); if(frigFactorTag != null) { // do special roundabout frigging to make gps // routing prompt use the correct exit number double frigFactor = 0.25; // default try { frigFactor = Double.parseDouble(frigFactorTag); } catch (NumberFormatException nfe) { // relax, tag was probably not a number anyway } frigRoundabout(way, frigFactor); } } // if there is a bounding box, clip the way with it List<Way> clippedWays = null; if(bbox != null) { List<List<Coord>> lineSegs = LineClipper.clip(bbox, way.getPoints()); boundaryCoords = new HashSet<Coord>(); if (lineSegs != null) { clippedWays = new ArrayList<Way>(); for (List<Coord> lco : lineSegs) { Way nWay = new Way(way.getId()); nWay.setName(way.getName()); nWay.copyTags(way); for(Coord co : lco) { nWay.addPoint(co); if(co.getHighwayCount() == 0) { boundaryCoords.add(co); co.incHighwayCount(); } } clippedWays.add(nWay); // associate the original Way // to the new Way Way origWay = originalWay.get(way); if(origWay == null) origWay = way; originalWay.put(nWay, origWay); } } } if(clippedWays != null) { for(Way cw : clippedWays) { while(cw.getPoints().size() > MAX_POINTS_IN_WAY) { Way tail = splitWayAt(cw, MAX_POINTS_IN_WAY - 1); addRoadAfterSplittingLoops(cw, gt); cw = tail; } addRoadAfterSplittingLoops(cw, gt); } } else { // no bounding box or way was not clipped while(way.getPoints().size() > MAX_POINTS_IN_WAY) { Way tail = splitWayAt(way, MAX_POINTS_IN_WAY - 1); addRoadAfterSplittingLoops(way, gt); way = tail; } addRoadAfterSplittingLoops(way, gt); } } void addRoadAfterSplittingLoops(Way way, GType gt) { // check if the way is a loop or intersects with itself boolean wayWasSplit = true; // aka rescan required while(wayWasSplit) { List<Coord> wayPoints = way.getPoints(); int numPointsInWay = wayPoints.size(); wayWasSplit = false; // assume way won't be split // check each point in the way to see if it is the same // point as a following point in the way (actually the // same object not just the same coordinates) for(int p1I = 0; !wayWasSplit && p1I < (numPointsInWay - 1); p1I++) { Coord p1 = wayPoints.get(p1I); for(int p2I = p1I + 1; !wayWasSplit && p2I < numPointsInWay; p2I++) { if(p1 == wayPoints.get(p2I)) { // way is a loop or intersects itself // attempt to split it into two ways // start at point before intersection point // check that splitting there will not produce // a zero length arc - if it does try the // previous point(s) int splitI = p2I - 1; while(splitI > p1I && p1.equals(wayPoints.get(splitI))) --splitI; if(splitI == p1I) { log.warn("Looped way " + getDebugName(way) + " has zero length arc - deleting node[" + p2I + "] to remove it"); wayPoints.remove(p2I); // next point to inspect has same index --p2I; // but number of points has reduced --numPointsInWay; } else { // split the way before the second point log.info("Splitting looped way " + getDebugName(way) + " at node[" + splitI + "] - it has " + (numPointsInWay - splitI - 1 ) + " following segment(s)."); Way loopTail = splitWayAt(way, splitI); // recursively check (shortened) head for // more loops addRoadAfterSplittingLoops(way, gt); // now process the tail of the way way = loopTail; wayWasSplit = true; } } } } if(!wayWasSplit) { // no split required so make road from way addRoadWithoutLoops(way, gt); } } } String getDebugName(Way way) { String name = way.getName(); if(name == null) name = way.getTag("ref"); if(name == null) name = ""; else name += " "; return name + "(OSM id " + way.getId() + ")"; } void addRoadWithoutLoops(Way way, GType gt) { List<Integer> nodeIndices = new ArrayList<Integer>(); List<Coord> points = way.getPoints(); Way trailingWay = null; String debugWayName = getDebugName(way); // make sure the way has nodes at each end points.get(0).incHighwayCount(); points.get(points.size() - 1).incHighwayCount(); // collect the Way's nodes and also split the way if any // inter-node arc length becomes excessive double arcLength = 0; for(int i = 0; i < points.size(); ++i) { Coord p = points.get(i); // check if we should split the way at this point to limit // the arc length between nodes if((i + 1) < points.size()) { double d = p.distance(points.get(i + 1)); if(d > MAX_ARC_LENGTH) { - double fraction = MAX_ARC_LENGTH / d; + double fraction = 0.99 * MAX_ARC_LENGTH / d; Coord extrap = p.makeBetweenPoint(points.get(i + 1), fraction); extrap.incHighwayCount(); points.add(i + 1, extrap); double newD = p.distance(extrap); log.warn("Way " + debugWayName + " contains a segment that is " + (int)d + "m long so I am adding a point to reduce its length to " + (int)newD + "m"); d = newD; } if((arcLength + d) > MAX_ARC_LENGTH) { assert i > 0; trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.warn("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " to limit arc length to " + (long)arcLength + "m"); } else { if(p.getHighwayCount() > 1) // point is a node so zero arc length arcLength = 0; arcLength += d; } } if(p.getHighwayCount() > 1) { // this point is a node connecting highways Integer nodeId = nodeIdMap.get(p); if(nodeId == null) { // assign a node id nodeIdMap.put(p, nextNodeId++); } nodeIndices.add(i); if((i + 1) < points.size() && nodeIndices.size() == MAX_NODES_IN_WAY) { // this isn't the last point in the way so split // it here to avoid exceeding the max nodes in way // limit trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.info("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes"); } } } MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(points); MapRoad road = new MapRoad(way.getId(), line); // set road parameters. road.setRoadClass(gt.getRoadClass()); if (way.isBoolTag("oneway")) { road.setDirection(true); road.setOneway(); } int speedIdx = -1; if(!ignoreMaxspeeds) { // maxspeed attribute overrides default for road type String maxSpeed = way.getTag("maxspeed"); if(maxSpeed != null) { speedIdx = getSpeedIdx(maxSpeed); log.info(debugWayName + " maxspeed=" + maxSpeed + ", speedIndex=" + speedIdx); } } road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed()); boolean[] noAccess = new boolean[RoadNetwork.NO_MAX]; String highwayType = way.getTag("highway"); if(highwayType == null) { // it's a routable way but not a highway (e.g. a ferry) // use the value of the route tag as the highwayType for // the purpose of testing for access restrictions highwayType = way.getTag("route"); } for (AccessMapping anAccessMap : accessMap) { int index = anAccessMap.index; String type = anAccessMap.type; String accessTagValue = way.getTag(type); if (accessTagValue == null) continue; if (accessExplicitlyDenied(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is denied access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = true; } else { // just the specific vehicle class is denied // access noAccess[index] = true; } log.info(type + " is not allowed in " + highwayType + " " + debugWayName); } else if (accessExplicitlyAllowed(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is allowed access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = false; } else { // just the specific vehicle class is allowed // access noAccess[index] = false; } log.info(type + " is allowed in " + highwayType + " " + debugWayName); } else if (accessTagValue.equalsIgnoreCase("destination")) { if (type.equals("motorcar") || type.equals("motorcycle")) { road.setNoThroughRouting(); } else if (type.equals("access")) { log.warn("access=destination only affects routing for cars in " + highwayType + " " + debugWayName); road.setNoThroughRouting(); } else { log.warn(type + "=destination ignored in " + highwayType + " " + debugWayName); } } else if (accessTagValue.equalsIgnoreCase("unknown")) { // implicitly allow access } else { log.warn("Ignoring unsupported access tag value " + type + "=" + accessTagValue + " in " + highwayType + " " + debugWayName); } } road.setAccess(noAccess); if(way.isBoolTag("toll")) road.setToll(); Way origWay = originalWay.get(way); if(origWay == null) origWay = way; int numNodes = nodeIndices.size(); road.setNumNodes(numNodes); if(numNodes > 0) { // replace Coords that are nodes with CoordNodes boolean hasInternalNodes = false; CoordNode lastCoordNode = null; List<RestrictionRelation> lastRestrictions = null; for(int i = 0; i < numNodes; ++i) { int n = nodeIndices.get(i); if(n > 0 && n < points.size() - 1) hasInternalNodes = true; Coord coord = points.get(n); Integer nodeId = nodeIdMap.get(coord); boolean boundary = boundaryCoords.contains(coord); if(boundary) { log.info("Way " + debugWayName + "'s point #" + n + " at " + points.get(n).toDegreeString() + " is a boundary node"); } CoordNode thisCoordNode = new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary); points.set(n, thisCoordNode); // see if this node plays a role in any turn // restrictions if(lastRestrictions != null) { // the previous node was the location of one or // more restrictions for(RestrictionRelation rr : lastRestrictions) { if(rr.getToWay().equals(origWay)) { rr.setToNode(thisCoordNode); } else if(rr.getFromWay().equals(origWay)) { rr.setFromNode(thisCoordNode); } else { rr.addOtherNode(thisCoordNode); } } } List<RestrictionRelation> theseRestrictions = restrictions.get(coord); if(theseRestrictions != null) { // this node is the location of one or more // restrictions for(RestrictionRelation rr : theseRestrictions) { rr.setViaNode(thisCoordNode); if(rr.getToWay().equals(origWay)) { if(lastCoordNode != null) rr.setToNode(lastCoordNode); } else if(rr.getFromWay().equals(origWay)) { if(lastCoordNode != null) rr.setFromNode(lastCoordNode); } else if(lastCoordNode != null) { rr.addOtherNode(lastCoordNode); } } } lastRestrictions = theseRestrictions; lastCoordNode = thisCoordNode; } road.setStartsWithNode(nodeIndices.get(0) == 0); road.setInternalNodes(hasInternalNodes); } lineAdder.add(road); if(trailingWay != null) addRoadWithoutLoops(trailingWay, gt); } // split a Way at the specified point and return the new Way (the // original Way is truncated) Way splitWayAt(Way way, int index) { Way trailingWay = new Way(way.getId()); List<Coord> wayPoints = way.getPoints(); int numPointsInWay = wayPoints.size(); for(int i = index; i < numPointsInWay; ++i) trailingWay.addPoint(wayPoints.get(i)); // ensure split point becomes a node wayPoints.get(index).incHighwayCount(); // copy the way's name and tags to the new way trailingWay.setName(way.getName()); trailingWay.copyTags(way); // remove the points after the split from the original way // it's probably more efficient to remove from the end first for(int i = numPointsInWay - 1; i > index; --i) wayPoints.remove(i); // associate the original Way to the new Way Way origWay = originalWay.get(way); if(origWay == null) origWay = way; originalWay.put(trailingWay, origWay); return trailingWay; } // function to add points between adjacent nodes in a roundabout // to make gps use correct exit number in routing instructions void frigRoundabout(Way way, double frigFactor) { List<Coord> wayPoints = way.getPoints(); int origNumPoints = wayPoints.size(); if(origNumPoints < 3) { // forget it! return; } int[] highWayCounts = new int[origNumPoints]; int middleLat = 0; int middleLon = 0; highWayCounts[0] = wayPoints.get(0).getHighwayCount(); for(int i = 1; i < origNumPoints; ++i) { Coord p = wayPoints.get(i); middleLat += p.getLatitude(); middleLon += p.getLongitude(); highWayCounts[i] = p.getHighwayCount(); } middleLat /= origNumPoints - 1; middleLon /= origNumPoints - 1; Coord middleCoord = new Coord(middleLat, middleLon); // account for fact that roundabout joins itself --highWayCounts[0]; --highWayCounts[origNumPoints - 1]; for(int i = origNumPoints - 2; i >= 0; --i) { Coord p1 = wayPoints.get(i); Coord p2 = wayPoints.get(i + 1); if(highWayCounts[i] > 1 && highWayCounts[i + 1] > 1) { // both points will be nodes so insert a new point // between them that (approximately) falls on the // roundabout's perimeter int newLat = (p1.getLatitude() + p2.getLatitude()) / 2; int newLon = (p1.getLongitude() + p2.getLongitude()) / 2; // new point has to be "outside" of existing line // joining p1 and p2 - how far outside is determined // by the ratio of the distance between p1 and p2 // compared to the distance of p1 from the "middle" of // the roundabout (aka, the approx radius of the // roundabout) - the higher the value of frigFactor, // the further out the point will be double scale = 1 + frigFactor * p1.distance(p2) / p1.distance(middleCoord); newLat = (int)((newLat - middleLat) * scale) + middleLat; newLon = (int)((newLon - middleLon) * scale) + middleLon; Coord newPoint = new Coord(newLat, newLon); double d1 = p1.distance(newPoint); double d2 = p2.distance(newPoint); double maxDistance = 100; if(d1 >= MIN_DISTANCE_BETWEEN_NODES && d1 <= maxDistance && d2 >= MIN_DISTANCE_BETWEEN_NODES && d2 <= maxDistance) { newPoint.incHighwayCount(); wayPoints.add(i + 1, newPoint); } } } } int getSpeedIdx(String tag) { double kmh; double factor = 1.0; String speedTag = tag.toLowerCase().trim(); if(speedTag.matches(".*mph")) // Check if it is a limit in mph { speedTag = speedTag.replaceFirst("mph", ""); factor = 1.61; } else speedTag = speedTag.replaceFirst("kmh", ""); // get rid of kmh just in case try { kmh = Integer.parseInt(speedTag) * factor; } catch (Exception e) { return -1; } if(kmh > 110) return 7; if(kmh > 90) return 6; if(kmh > 80) return 5; if(kmh > 60) return 4; if(kmh > 40) return 3; if(kmh > 20) return 2; if(kmh > 10) return 1; else return 0; } protected boolean accessExplicitlyAllowed(String val) { if (val == null) return false; return (val.equalsIgnoreCase("yes") || val.equalsIgnoreCase("designated") || val.equalsIgnoreCase("permissive")); } protected boolean accessExplicitlyDenied(String val) { if (val == null) return false; return (val.equalsIgnoreCase("no") || val.equalsIgnoreCase("private")); } }
true
true
void addRoadWithoutLoops(Way way, GType gt) { List<Integer> nodeIndices = new ArrayList<Integer>(); List<Coord> points = way.getPoints(); Way trailingWay = null; String debugWayName = getDebugName(way); // make sure the way has nodes at each end points.get(0).incHighwayCount(); points.get(points.size() - 1).incHighwayCount(); // collect the Way's nodes and also split the way if any // inter-node arc length becomes excessive double arcLength = 0; for(int i = 0; i < points.size(); ++i) { Coord p = points.get(i); // check if we should split the way at this point to limit // the arc length between nodes if((i + 1) < points.size()) { double d = p.distance(points.get(i + 1)); if(d > MAX_ARC_LENGTH) { double fraction = MAX_ARC_LENGTH / d; Coord extrap = p.makeBetweenPoint(points.get(i + 1), fraction); extrap.incHighwayCount(); points.add(i + 1, extrap); double newD = p.distance(extrap); log.warn("Way " + debugWayName + " contains a segment that is " + (int)d + "m long so I am adding a point to reduce its length to " + (int)newD + "m"); d = newD; } if((arcLength + d) > MAX_ARC_LENGTH) { assert i > 0; trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.warn("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " to limit arc length to " + (long)arcLength + "m"); } else { if(p.getHighwayCount() > 1) // point is a node so zero arc length arcLength = 0; arcLength += d; } } if(p.getHighwayCount() > 1) { // this point is a node connecting highways Integer nodeId = nodeIdMap.get(p); if(nodeId == null) { // assign a node id nodeIdMap.put(p, nextNodeId++); } nodeIndices.add(i); if((i + 1) < points.size() && nodeIndices.size() == MAX_NODES_IN_WAY) { // this isn't the last point in the way so split // it here to avoid exceeding the max nodes in way // limit trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.info("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes"); } } } MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(points); MapRoad road = new MapRoad(way.getId(), line); // set road parameters. road.setRoadClass(gt.getRoadClass()); if (way.isBoolTag("oneway")) { road.setDirection(true); road.setOneway(); } int speedIdx = -1; if(!ignoreMaxspeeds) { // maxspeed attribute overrides default for road type String maxSpeed = way.getTag("maxspeed"); if(maxSpeed != null) { speedIdx = getSpeedIdx(maxSpeed); log.info(debugWayName + " maxspeed=" + maxSpeed + ", speedIndex=" + speedIdx); } } road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed()); boolean[] noAccess = new boolean[RoadNetwork.NO_MAX]; String highwayType = way.getTag("highway"); if(highwayType == null) { // it's a routable way but not a highway (e.g. a ferry) // use the value of the route tag as the highwayType for // the purpose of testing for access restrictions highwayType = way.getTag("route"); } for (AccessMapping anAccessMap : accessMap) { int index = anAccessMap.index; String type = anAccessMap.type; String accessTagValue = way.getTag(type); if (accessTagValue == null) continue; if (accessExplicitlyDenied(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is denied access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = true; } else { // just the specific vehicle class is denied // access noAccess[index] = true; } log.info(type + " is not allowed in " + highwayType + " " + debugWayName); } else if (accessExplicitlyAllowed(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is allowed access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = false; } else { // just the specific vehicle class is allowed // access noAccess[index] = false; } log.info(type + " is allowed in " + highwayType + " " + debugWayName); } else if (accessTagValue.equalsIgnoreCase("destination")) { if (type.equals("motorcar") || type.equals("motorcycle")) { road.setNoThroughRouting(); } else if (type.equals("access")) { log.warn("access=destination only affects routing for cars in " + highwayType + " " + debugWayName); road.setNoThroughRouting(); } else { log.warn(type + "=destination ignored in " + highwayType + " " + debugWayName); } } else if (accessTagValue.equalsIgnoreCase("unknown")) { // implicitly allow access } else { log.warn("Ignoring unsupported access tag value " + type + "=" + accessTagValue + " in " + highwayType + " " + debugWayName); } } road.setAccess(noAccess); if(way.isBoolTag("toll")) road.setToll(); Way origWay = originalWay.get(way); if(origWay == null) origWay = way; int numNodes = nodeIndices.size(); road.setNumNodes(numNodes); if(numNodes > 0) { // replace Coords that are nodes with CoordNodes boolean hasInternalNodes = false; CoordNode lastCoordNode = null; List<RestrictionRelation> lastRestrictions = null; for(int i = 0; i < numNodes; ++i) { int n = nodeIndices.get(i); if(n > 0 && n < points.size() - 1) hasInternalNodes = true; Coord coord = points.get(n); Integer nodeId = nodeIdMap.get(coord); boolean boundary = boundaryCoords.contains(coord); if(boundary) { log.info("Way " + debugWayName + "'s point #" + n + " at " + points.get(n).toDegreeString() + " is a boundary node"); } CoordNode thisCoordNode = new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary); points.set(n, thisCoordNode); // see if this node plays a role in any turn // restrictions if(lastRestrictions != null) { // the previous node was the location of one or // more restrictions for(RestrictionRelation rr : lastRestrictions) { if(rr.getToWay().equals(origWay)) { rr.setToNode(thisCoordNode); } else if(rr.getFromWay().equals(origWay)) { rr.setFromNode(thisCoordNode); } else { rr.addOtherNode(thisCoordNode); } } } List<RestrictionRelation> theseRestrictions = restrictions.get(coord); if(theseRestrictions != null) { // this node is the location of one or more // restrictions for(RestrictionRelation rr : theseRestrictions) { rr.setViaNode(thisCoordNode); if(rr.getToWay().equals(origWay)) { if(lastCoordNode != null) rr.setToNode(lastCoordNode); } else if(rr.getFromWay().equals(origWay)) { if(lastCoordNode != null) rr.setFromNode(lastCoordNode); } else if(lastCoordNode != null) { rr.addOtherNode(lastCoordNode); } } } lastRestrictions = theseRestrictions; lastCoordNode = thisCoordNode; } road.setStartsWithNode(nodeIndices.get(0) == 0); road.setInternalNodes(hasInternalNodes); } lineAdder.add(road); if(trailingWay != null) addRoadWithoutLoops(trailingWay, gt); }
void addRoadWithoutLoops(Way way, GType gt) { List<Integer> nodeIndices = new ArrayList<Integer>(); List<Coord> points = way.getPoints(); Way trailingWay = null; String debugWayName = getDebugName(way); // make sure the way has nodes at each end points.get(0).incHighwayCount(); points.get(points.size() - 1).incHighwayCount(); // collect the Way's nodes and also split the way if any // inter-node arc length becomes excessive double arcLength = 0; for(int i = 0; i < points.size(); ++i) { Coord p = points.get(i); // check if we should split the way at this point to limit // the arc length between nodes if((i + 1) < points.size()) { double d = p.distance(points.get(i + 1)); if(d > MAX_ARC_LENGTH) { double fraction = 0.99 * MAX_ARC_LENGTH / d; Coord extrap = p.makeBetweenPoint(points.get(i + 1), fraction); extrap.incHighwayCount(); points.add(i + 1, extrap); double newD = p.distance(extrap); log.warn("Way " + debugWayName + " contains a segment that is " + (int)d + "m long so I am adding a point to reduce its length to " + (int)newD + "m"); d = newD; } if((arcLength + d) > MAX_ARC_LENGTH) { assert i > 0; trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.warn("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " to limit arc length to " + (long)arcLength + "m"); } else { if(p.getHighwayCount() > 1) // point is a node so zero arc length arcLength = 0; arcLength += d; } } if(p.getHighwayCount() > 1) { // this point is a node connecting highways Integer nodeId = nodeIdMap.get(p); if(nodeId == null) { // assign a node id nodeIdMap.put(p, nextNodeId++); } nodeIndices.add(i); if((i + 1) < points.size() && nodeIndices.size() == MAX_NODES_IN_WAY) { // this isn't the last point in the way so split // it here to avoid exceeding the max nodes in way // limit trailingWay = splitWayAt(way, i); // this will have truncated the current Way's // points so the loop will now terminate log.info("Splitting way " + debugWayName + " at " + points.get(i).toDegreeString() + " as it has at least " + MAX_NODES_IN_WAY + " nodes"); } } } MapLine line = new MapLine(); elementSetup(line, gt, way); line.setPoints(points); MapRoad road = new MapRoad(way.getId(), line); // set road parameters. road.setRoadClass(gt.getRoadClass()); if (way.isBoolTag("oneway")) { road.setDirection(true); road.setOneway(); } int speedIdx = -1; if(!ignoreMaxspeeds) { // maxspeed attribute overrides default for road type String maxSpeed = way.getTag("maxspeed"); if(maxSpeed != null) { speedIdx = getSpeedIdx(maxSpeed); log.info(debugWayName + " maxspeed=" + maxSpeed + ", speedIndex=" + speedIdx); } } road.setSpeed(speedIdx >= 0? speedIdx : gt.getRoadSpeed()); boolean[] noAccess = new boolean[RoadNetwork.NO_MAX]; String highwayType = way.getTag("highway"); if(highwayType == null) { // it's a routable way but not a highway (e.g. a ferry) // use the value of the route tag as the highwayType for // the purpose of testing for access restrictions highwayType = way.getTag("route"); } for (AccessMapping anAccessMap : accessMap) { int index = anAccessMap.index; String type = anAccessMap.type; String accessTagValue = way.getTag(type); if (accessTagValue == null) continue; if (accessExplicitlyDenied(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is denied access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = true; } else { // just the specific vehicle class is denied // access noAccess[index] = true; } log.info(type + " is not allowed in " + highwayType + " " + debugWayName); } else if (accessExplicitlyAllowed(accessTagValue)) { if (index == RoadNetwork.NO_MAX) { // everything is allowed access for (int j = 1; j < accessMap.length; ++j) noAccess[accessMap[j].index] = false; } else { // just the specific vehicle class is allowed // access noAccess[index] = false; } log.info(type + " is allowed in " + highwayType + " " + debugWayName); } else if (accessTagValue.equalsIgnoreCase("destination")) { if (type.equals("motorcar") || type.equals("motorcycle")) { road.setNoThroughRouting(); } else if (type.equals("access")) { log.warn("access=destination only affects routing for cars in " + highwayType + " " + debugWayName); road.setNoThroughRouting(); } else { log.warn(type + "=destination ignored in " + highwayType + " " + debugWayName); } } else if (accessTagValue.equalsIgnoreCase("unknown")) { // implicitly allow access } else { log.warn("Ignoring unsupported access tag value " + type + "=" + accessTagValue + " in " + highwayType + " " + debugWayName); } } road.setAccess(noAccess); if(way.isBoolTag("toll")) road.setToll(); Way origWay = originalWay.get(way); if(origWay == null) origWay = way; int numNodes = nodeIndices.size(); road.setNumNodes(numNodes); if(numNodes > 0) { // replace Coords that are nodes with CoordNodes boolean hasInternalNodes = false; CoordNode lastCoordNode = null; List<RestrictionRelation> lastRestrictions = null; for(int i = 0; i < numNodes; ++i) { int n = nodeIndices.get(i); if(n > 0 && n < points.size() - 1) hasInternalNodes = true; Coord coord = points.get(n); Integer nodeId = nodeIdMap.get(coord); boolean boundary = boundaryCoords.contains(coord); if(boundary) { log.info("Way " + debugWayName + "'s point #" + n + " at " + points.get(n).toDegreeString() + " is a boundary node"); } CoordNode thisCoordNode = new CoordNode(coord.getLatitude(), coord.getLongitude(), nodeId, boundary); points.set(n, thisCoordNode); // see if this node plays a role in any turn // restrictions if(lastRestrictions != null) { // the previous node was the location of one or // more restrictions for(RestrictionRelation rr : lastRestrictions) { if(rr.getToWay().equals(origWay)) { rr.setToNode(thisCoordNode); } else if(rr.getFromWay().equals(origWay)) { rr.setFromNode(thisCoordNode); } else { rr.addOtherNode(thisCoordNode); } } } List<RestrictionRelation> theseRestrictions = restrictions.get(coord); if(theseRestrictions != null) { // this node is the location of one or more // restrictions for(RestrictionRelation rr : theseRestrictions) { rr.setViaNode(thisCoordNode); if(rr.getToWay().equals(origWay)) { if(lastCoordNode != null) rr.setToNode(lastCoordNode); } else if(rr.getFromWay().equals(origWay)) { if(lastCoordNode != null) rr.setFromNode(lastCoordNode); } else if(lastCoordNode != null) { rr.addOtherNode(lastCoordNode); } } } lastRestrictions = theseRestrictions; lastCoordNode = thisCoordNode; } road.setStartsWithNode(nodeIndices.get(0) == 0); road.setInternalNodes(hasInternalNodes); } lineAdder.add(road); if(trailingWay != null) addRoadWithoutLoops(trailingWay, gt); }
diff --git a/svnkit/src/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java b/svnkit/src/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java index f626b36e6..6d318f7e2 100644 --- a/svnkit/src/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java +++ b/svnkit/src/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java @@ -1,850 +1,849 @@ /* * ==================================================================== * Copyright (c) 2004-2007 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://svnkit.com/license.html * If newer versions of this license are posted there, you may use a * newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.io.dav.http; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.text.ParseException; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.zip.GZIPInputStream; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.TrustManager; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.tmatesoft.svn.core.SVNErrorCode; import org.tmatesoft.svn.core.SVNErrorMessage; import org.tmatesoft.svn.core.SVNException; import org.tmatesoft.svn.core.SVNURL; import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager; import org.tmatesoft.svn.core.auth.ISVNProxyManager; import org.tmatesoft.svn.core.auth.SVNAuthentication; import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication; import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVErrorHandler; import org.tmatesoft.svn.core.internal.util.SVNHashMap; import org.tmatesoft.svn.core.internal.util.SVNSSLUtil; import org.tmatesoft.svn.core.internal.util.SVNSocketFactory; import org.tmatesoft.svn.core.internal.wc.IOExceptionWrapper; import org.tmatesoft.svn.core.internal.wc.SVNCancellableOutputStream; import org.tmatesoft.svn.core.internal.wc.SVNErrorManager; import org.tmatesoft.svn.core.internal.wc.SVNFileUtil; import org.tmatesoft.svn.core.io.SVNRepository; import org.tmatesoft.svn.util.SVNDebugLog; import org.tmatesoft.svn.util.SVNLogType; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import org.xml.sax.helpers.DefaultHandler; /** * @version 1.1.1 * @author TMate Software Ltd. */ class HTTPConnection implements IHTTPConnection { private static final DefaultHandler DEFAULT_SAX_HANDLER = new DefaultHandler(); private static EntityResolver NO_ENTITY_RESOLVER = new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new ByteArrayInputStream(new byte[0])); } }; private static final int DEFAULT_HTTP_TIMEOUT = 3600*1000; private static SAXParserFactory ourSAXParserFactory; private byte[] myBuffer; private SAXParser mySAXParser; private SVNURL myHost; private OutputStream myOutputStream; private InputStream myInputStream; private Socket mySocket; private SVNRepository myRepository; private boolean myIsSecured; private boolean myIsProxied; private SVNAuthentication myLastValidAuth; private HTTPAuthentication myChallengeCredentials; private HTTPAuthentication myProxyAuthentication; private boolean myIsSpoolResponse; private TrustManager myTrustManager; private HTTPSSLKeyManager myKeyManager; private String myCharset; private boolean myIsSpoolAll; private File mySpoolDirectory; private long myNextRequestTimeout; public HTTPConnection(SVNRepository repository, String charset, File spoolDirectory, boolean spoolAll) throws SVNException { myRepository = repository; myCharset = charset; myHost = repository.getLocation().setPath("", false); myIsSecured = "https".equalsIgnoreCase(myHost.getProtocol()); myIsSpoolAll = spoolAll; mySpoolDirectory = spoolDirectory; myNextRequestTimeout = -1; } public SVNURL getHost() { return myHost; } private void connect(HTTPSSLKeyManager keyManager, TrustManager trustManager) throws IOException, SVNException { SVNURL location = myRepository.getLocation(); if (mySocket == null || SVNSocketFactory.isSocketStale(mySocket)) { close(); String host = location.getHost(); int port = location.getPort(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); ISVNProxyManager proxyAuth = authManager != null ? authManager.getProxyManager(location) : null; int connectTimeout = authManager != null ? authManager.getConnectTimeout(myRepository) : 0; int readTimeout = authManager != null ? authManager.getReadTimeout(myRepository) : DEFAULT_HTTP_TIMEOUT; if (readTimeout < 0) { readTimeout = DEFAULT_HTTP_TIMEOUT; } if (proxyAuth != null && proxyAuth.getProxyHost() != null) { myRepository.getDebugLog().logFine("Using proxy " + proxyAuth.getProxyHost() + " (secured=" + myIsSecured + ")"); mySocket = SVNSocketFactory.createPlainSocket(proxyAuth.getProxyHost(), proxyAuth.getProxyPort(), connectTimeout, readTimeout); if (myProxyAuthentication == null) { myProxyAuthentication = new HTTPBasicAuthentication(proxyAuth.getProxyUserName(), proxyAuth.getProxyPassword(), myCharset); } myIsProxied = true; if (myIsSecured) { HTTPRequest connectRequest = new HTTPRequest(myCharset); connectRequest.setConnection(this); connectRequest.initCredentials(myProxyAuthentication, "CONNECT", host + ":" + port); connectRequest.setProxyAuthentication(myProxyAuthentication.authenticate()); connectRequest.setForceProxyAuth(true); connectRequest.dispatch("CONNECT", host + ":" + port, null, 0, 0, null); HTTPStatus status = connectRequest.getStatus(); if (status.getCode() == HttpURLConnection.HTTP_OK) { myInputStream = null; myOutputStream = null; mySocket = SVNSocketFactory.createSSLSocket(keyManager != null ? new KeyManager[] { keyManager } : new KeyManager[0], trustManager, host, port, mySocket, readTimeout); proxyAuth.acknowledgeProxyContext(true, null); return; } SVNURL proxyURL = SVNURL.parseURIEncoded("http://" + proxyAuth.getProxyHost() + ":" + proxyAuth.getProxyPort()); SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {"CONNECT", proxyURL}); proxyAuth.acknowledgeProxyContext(false, err); SVNErrorManager.error(err, connectRequest.getErrorMessage()); } } else { myIsProxied = false; myProxyAuthentication = null; mySocket = myIsSecured ? SVNSocketFactory.createSSLSocket(keyManager != null ? new KeyManager[] { keyManager } : new KeyManager[0], trustManager, host, port, connectTimeout, readTimeout) : SVNSocketFactory.createPlainSocket(host, port, connectTimeout, readTimeout); } } } public void readHeader(HTTPRequest request) throws IOException { InputStream is = myRepository.getDebugLog().createLogStream(getInputStream()); try { // may throw EOF exception. HTTPStatus status = HTTPParser.parseStatus(is, myCharset); HTTPHeader header = HTTPHeader.parseHeader(is, myCharset); request.setStatus(status); request.setResponseHeader(header); } catch (ParseException e) { // in case of parse exception: // try to read remaining and log it. String line = HTTPParser.readLine(is, myCharset); while(line != null && line.length() > 0) { line = HTTPParser.readLine(is, myCharset); } throw new IOException(e.getMessage()); } finally { myRepository.getDebugLog().flushStream(is); } } public SVNErrorMessage readError(HTTPRequest request, String method, String path) { DAVErrorHandler errorHandler = new DAVErrorHandler(); try { readData(request, method, path, errorHandler); } catch (IOException e) { return null; } return errorHandler.getErrorMessage(); } public void sendData(byte[] body) throws IOException { try { getOutputStream().write(body, 0, body.length); getOutputStream().flush(); } finally { myRepository.getDebugLog().flushStream(getOutputStream()); } } public void sendData(InputStream source, long length) throws IOException { try { byte[] buffer = getBuffer(); while(length > 0) { int read = source.read(buffer, 0, (int) Math.min(buffer.length, length)); length -= read; if (read > 0) { getOutputStream().write(buffer, 0, read); } else { break; } } getOutputStream().flush(); } finally { myRepository.getDebugLog().flushStream(getOutputStream()); } } public SVNAuthentication getLastValidCredentials() { return myLastValidAuth; } public void clearAuthenticationCache() { myLastValidAuth = null; myTrustManager = null; myKeyManager = null; } public HTTPStatus request(String method, String path, HTTPHeader header, StringBuffer body, int ok1, int ok2, OutputStream dst, DefaultHandler handler) throws SVNException { return request(method, path, header, body, ok1, ok2, dst, handler, null); } public HTTPStatus request(String method, String path, HTTPHeader header, StringBuffer body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException { byte[] buffer = null; if (body != null) { try { buffer = body.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { buffer = body.toString().getBytes(); } } return request(method, path, header, buffer != null ? new ByteArrayInputStream(buffer) : null, ok1, ok2, dst, handler, context); } public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler) throws SVNException { return request(method, path, header, body, ok1, ok2, dst, handler, null); } public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException { if ("".equals(path) || path == null) { path = "/"; } // 1. prompt for ssl client cert if needed, if cancelled - throw cancellation exception. HTTPSSLKeyManager keyManager = myKeyManager == null && myRepository.getAuthenticationManager() != null ? createKeyManager() : myKeyManager; TrustManager trustManager = myTrustManager == null && myRepository.getAuthenticationManager() != null ? myRepository.getAuthenticationManager().getTrustManager(myRepository.getLocation()) : myTrustManager; String sslRealm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">"; SVNAuthentication httpAuth = myLastValidAuth; boolean isAuthForced = myRepository.getAuthenticationManager() != null ? myRepository.getAuthenticationManager().isAuthenticationForced() : false; if (httpAuth == null && isAuthForced) { httpAuth = myRepository.getAuthenticationManager().getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, sslRealm, null); myChallengeCredentials = new HTTPBasicAuthentication((SVNPasswordAuthentication)httpAuth, myCharset); } String realm = null; // 2. create request instance. HTTPRequest request = new HTTPRequest(myCharset); request.setConnection(this); request.setKeepAlive(true); request.setRequestBody(body); request.setResponseHandler(handler); request.setResponseStream(dst); SVNErrorMessage err = null; while (true) { HTTPStatus status = null; if (myNextRequestTimeout < 0 || System.currentTimeMillis() >= myNextRequestTimeout) { SVNDebugLog.getLog(SVNLogType.NETWORK).logFine("Keep-Alive timeout detected"); close(); } int retryCount = 1; try { err = null; String httpAuthResponse = null; String proxyAuthResponse = null; while(retryCount >= 0) { connect(keyManager, trustManager); request.reset(); request.setProxied(myIsProxied); request.setSecured(myIsSecured); if (myProxyAuthentication != null) { if (proxyAuthResponse == null) { request.initCredentials(myProxyAuthentication, method, path); proxyAuthResponse = myProxyAuthentication.authenticate(); } request.setProxyAuthentication(proxyAuthResponse); } if (httpAuth != null && myChallengeCredentials != null) { if (httpAuthResponse == null) { request.initCredentials(myChallengeCredentials, method, path); httpAuthResponse = myChallengeCredentials.authenticate(); } request.setAuthentication(httpAuthResponse); } try { request.dispatch(method, path, header, ok1, ok2, context); break; } catch (EOFException pe) { // retry, EOF always means closed connection. if (retryCount > 0) { close(); continue; } throw (IOException) new IOException(pe.getMessage()).initCause(pe); } finally { retryCount--; } } myNextRequestTimeout = request.getNextRequestTimeout(); status = request.getStatus(); } catch (SSLHandshakeException ssl) { myRepository.getDebugLog().logFine(ssl); close(); if (ssl.getCause() instanceof SVNSSLUtil.CertificateNotTrustedException) { SVNErrorManager.cancel(ssl.getCause().getMessage()); } SVNErrorMessage sslErr = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "SSL handshake failed: ''{0}''", new Object[] { ssl.getMessage() }, SVNErrorMessage.TYPE_ERROR, ssl); if (keyManager != null) { keyManager.acknowledgeAndClearAuthentication(sslErr); } err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, ssl); continue; } catch (IOException e) { myRepository.getDebugLog().logFine(e); if (e instanceof SocketTimeoutException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "timed out waiting for server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof UnknownHostException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "unknown host", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof ConnectException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "connection refused by the server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof SVNCancellableOutputStream.IOCancelException) { SVNErrorManager.cancel(e.getMessage()); } else if (e instanceof SSLException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e.getMessage()); } else { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e.getMessage()); } } catch (SVNException e) { myRepository.getDebugLog().logFine(e); // force connection close on SVNException // (could be thrown by user's auth manager methods). close(); throw e; } finally { finishResponse(request); } if (err != null) { close(); break; } if (keyManager != null) { myKeyManager = keyManager; myTrustManager = trustManager; keyManager.acknowledgeAndClearAuthentication(null); } if (status.getCode() == HttpURLConnection.HTTP_FORBIDDEN) { myLastValidAuth = null; close(); err = request.getErrorMessage(); } else if (myIsProxied && status.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) { Collection proxyAuthHeaders = request.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER); try { myProxyAuthentication = HTTPAuthentication.parseAuthParameters(proxyAuthHeaders, myProxyAuthentication, myCharset); } catch (SVNException svne) { myRepository.getDebugLog().logFine(svne); err = svne.getErrorMessage(); break; } if (myProxyAuthentication instanceof HTTPNTLMAuthentication) { HTTPNTLMAuthentication ntlmProxyAuth = (HTTPNTLMAuthentication)myProxyAuthentication; if (ntlmProxyAuth.isInType3State()) { continue; } } err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed"); SVNURL location = myRepository.getLocation(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(location) : null; if (proxyManager != null) { proxyManager.acknowledgeProxyContext(false, err); } close(); break; } else if (status.getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { Collection authHeaderValues = request.getResponseHeader().getHeaderValues(HTTPHeader.AUTHENTICATE_HEADER); if (authHeaderValues == null || authHeaderValues.size() == 0) { err = request.getErrorMessage(); status.setError(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, err.getMessageTemplate(), err.getRelatedObjects())); if ("LOCK".equalsIgnoreCase(method)) { status.getError().setChildErrorMessage(SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Probably you are trying to lock file in repository that only allows anonymous access")); } SVNErrorManager.error(status.getError()); return status; } //we should work around a situation when a server //does not support Basic authentication while we're //forcing it, credentials should not be immediately //thrown away boolean skip = false; isAuthForced = myRepository.getAuthenticationManager() != null ? myRepository.getAuthenticationManager().isAuthenticationForced() : false; if (isAuthForced) { if (httpAuth != null && myChallengeCredentials != null && !HTTPAuthentication.isSchemeSupportedByServer(myChallengeCredentials.getAuthenticationScheme(), authHeaderValues)) { skip = true; } } try { myChallengeCredentials = HTTPAuthentication.parseAuthParameters(authHeaderValues, myChallengeCredentials, myCharset); } catch (SVNException svne) { err = svne.getErrorMessage(); break; } myChallengeCredentials.setChallengeParameter("methodname", method); myChallengeCredentials.setChallengeParameter("uri", path); if (skip) { close(); continue; } if (myChallengeCredentials instanceof HTTPNTLMAuthentication) { HTTPNTLMAuthentication ntlmAuth = (HTTPNTLMAuthentication)myChallengeCredentials; if (ntlmAuth.isInType3State()) { continue; } } else if (myChallengeCredentials instanceof HTTPDigestAuthentication) { // continue (retry once) if previous request was acceppted? if (myLastValidAuth != null) { myLastValidAuth = null; continue; } } myLastValidAuth = null; - close(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); if (authManager == null) { err = request.getErrorMessage(); break; } realm = myChallengeCredentials.getChallengeParameter("realm"); realm = realm == null ? "" : " " + realm; realm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">" + realm; if (httpAuth == null) { httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } else { authManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth); httpAuth = authManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } if (httpAuth == null) { err = SVNErrorMessage.create(SVNErrorCode.CANCELLED, "HTTP authorization cancelled"); break; } myChallengeCredentials.setCredentials((SVNPasswordAuthentication)httpAuth); continue; } else if (status.getCode() == HttpURLConnection.HTTP_MOVED_PERM || status.getCode() == HttpURLConnection.HTTP_MOVED_TEMP) { close(); String newLocation = request.getResponseHeader().getFirstHeaderValue(HTTPHeader.LOCATION_HEADER); if (newLocation == null) { err = request.getErrorMessage(); break; } int hostIndex = newLocation.indexOf("://"); if (hostIndex > 0) { hostIndex += 3; hostIndex = newLocation.indexOf("/", hostIndex); } if (hostIndex > 0 && hostIndex < newLocation.length()) { String newPath = newLocation.substring(hostIndex); if (newPath.endsWith("/") && !newPath.endsWith("//") && !path.endsWith("/") && newPath.substring(0, newPath.length() - 1).equals(path)) { path += "//"; continue; } } err = request.getErrorMessage(); } else if (request.getErrorMessage() != null) { err = request.getErrorMessage(); } if (err != null) { break; } if (myIsProxied) { SVNURL location = myRepository.getLocation(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(location) : null; if (proxyManager != null) { proxyManager.acknowledgeProxyContext(true, null); } } if (httpAuth != null && realm != null && myRepository.getAuthenticationManager() != null) { myRepository.getAuthenticationManager().acknowledgeAuthentication(true, ISVNAuthenticationManager.PASSWORD, realm, null, httpAuth); } myLastValidAuth = httpAuth; status.setHeader(request.getResponseHeader()); return status; } // force close on error that was not processed before. // these are errors that has no relation to http status (processing error or cancellation). close(); if (err != null && err.getErrorCode().getCategory() != SVNErrorCode.RA_DAV_CATEGORY && err.getErrorCode() != SVNErrorCode.UNSUPPORTED_FEATURE) { SVNErrorManager.error(err); } // err2 is another default context... // myRepository.getDebugLog().info(err.getMessage()); myRepository.getDebugLog().logFine(new Exception(err.getMessage())); SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {method, path}, err.getType(), err.getCause()); SVNErrorManager.error(err, err2); return null; } private HTTPSSLKeyManager createKeyManager() { if (!myIsSecured) { return null; } SVNURL location = myRepository.getLocation(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); String sslRealm = "<" + location.getProtocol() + "://" + location.getHost() + ":" + location.getPort() + ">"; return new HTTPSSLKeyManager(authManager, sslRealm, location); } public SVNErrorMessage readData(HTTPRequest request, OutputStream dst) throws IOException { InputStream stream = createInputStream(request.getResponseHeader(), getInputStream()); byte[] buffer = getBuffer(); boolean willCloseConnection = false; try { while (true) { int count = stream.read(buffer); if (count < 0) { break; } if (dst != null) { dst.write(buffer, 0, count); } } } catch (IOException e) { willCloseConnection = true; if (e instanceof IOExceptionWrapper) { IOExceptionWrapper wrappedException = (IOExceptionWrapper) e; return wrappedException.getOriginalException().getErrorMessage(); } if (e.getCause() instanceof SVNException) { return ((SVNException) e.getCause()).getErrorMessage(); } throw e; } finally { if (!willCloseConnection) { SVNFileUtil.closeFile(stream); } myRepository.getDebugLog().flushStream(stream); } return null; } public SVNErrorMessage readData(HTTPRequest request, String method, String path, DefaultHandler handler) throws IOException { InputStream is = null; SpoolFile tmpFile = null; SVNErrorMessage err = null; try { if (myIsSpoolResponse || myIsSpoolAll) { OutputStream dst = null; try { tmpFile = new SpoolFile(mySpoolDirectory); dst = tmpFile.openForWriting(); dst = new SVNCancellableOutputStream(dst, myRepository.getCanceller()); // this will exhaust http stream anyway. err = readData(request, dst); SVNFileUtil.closeFile(dst); dst = null; if (err != null) { return err; } // this stream always have to be closed. is = tmpFile.openForReading(); } finally { SVNFileUtil.closeFile(dst); } } else { is = createInputStream(request.getResponseHeader(), getInputStream()); } // this will not close is stream. err = readData(is, method, path, handler); } catch (IOException e) { throw e; } finally { if (myIsSpoolResponse || myIsSpoolAll) { // always close spooled stream. SVNFileUtil.closeFile(is); } else if (err == null && !hasToCloseConnection(request.getResponseHeader())) { // exhaust stream if connection is not about to be closed. SVNFileUtil.closeFile(is); } if (tmpFile != null) { try { tmpFile.delete(); } catch (SVNException e) { throw new IOException(e.getMessage()); } } myIsSpoolResponse = false; } return err; } private SVNErrorMessage readData(InputStream is, String method, String path, DefaultHandler handler) throws FactoryConfigurationError, UnsupportedEncodingException, IOException { try { if (mySAXParser == null) { mySAXParser = getSAXParserFactory().newSAXParser(); } XMLReader reader = new XMLReader(is); while (!reader.isClosed()) { org.xml.sax.XMLReader xmlReader = mySAXParser.getXMLReader(); xmlReader.setContentHandler(handler); xmlReader.setDTDHandler(handler); xmlReader.setErrorHandler(handler); xmlReader.setEntityResolver(NO_ENTITY_RESOLVER); xmlReader.parse(new InputSource(reader)); } } catch (SAXException e) { if (e instanceof SAXParseException) { if (handler instanceof DAVErrorHandler) { // failed to read svn-specific error, return null. return null; } } else if (e.getException() instanceof SVNException) { return ((SVNException) e.getException()).getErrorMessage(); } else if (e.getCause() instanceof SVNException) { return ((SVNException) e.getCause()).getErrorMessage(); } return SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Processing {0} request response failed: {1} ({2}) ", new Object[] {method, e.getMessage(), path}); } catch (ParserConfigurationException e) { return SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "XML parser configuration error while processing {0} request response: {1} ({2}) ", new Object[] {method, e.getMessage(), path}); } catch (EOFException e) { // skip it. } finally { if (mySAXParser != null) { // to avoid memory leaks when connection is cached. org.xml.sax.XMLReader xmlReader = null; try { xmlReader = mySAXParser.getXMLReader(); } catch (SAXException e) { } if (xmlReader != null) { xmlReader.setContentHandler(DEFAULT_SAX_HANDLER); xmlReader.setDTDHandler(DEFAULT_SAX_HANDLER); xmlReader.setErrorHandler(DEFAULT_SAX_HANDLER); xmlReader.setEntityResolver(NO_ENTITY_RESOLVER); } } myRepository.getDebugLog().flushStream(is); } return null; } public void skipData(HTTPRequest request) throws IOException { if (hasToCloseConnection(request.getResponseHeader())) { return; } InputStream is = createInputStream(request.getResponseHeader(), getInputStream()); while(is.skip(2048) > 0); } public void close() { if (mySocket != null) { if (myInputStream != null) { try { myInputStream.close(); } catch (IOException e) {} } if (myOutputStream != null) { try { myOutputStream.flush(); } catch (IOException e) {} } if (myOutputStream != null) { try { myOutputStream.close(); } catch (IOException e) {} } try { mySocket.close(); } catch (IOException e) {} mySocket = null; myOutputStream = null; myInputStream = null; } } private byte[] getBuffer() { if (myBuffer == null) { myBuffer = new byte[32*1024]; } return myBuffer; } private InputStream getInputStream() throws IOException { if (myInputStream == null) { if (mySocket == null) { return null; } myInputStream = new BufferedInputStream(mySocket.getInputStream(), 2048); } return myInputStream; } private OutputStream getOutputStream() throws IOException { if (myOutputStream == null) { if (mySocket == null) { return null; } myOutputStream = new BufferedOutputStream(mySocket.getOutputStream(), 2048); myOutputStream = myRepository.getDebugLog().createLogStream(myOutputStream); } return myOutputStream; } private void finishResponse(HTTPRequest request) { if (myOutputStream != null) { try { myOutputStream.flush(); } catch (IOException ex) { } } HTTPHeader header = request != null ? request.getResponseHeader() : null; if (hasToCloseConnection(header)) { close(); } } private static boolean hasToCloseConnection(HTTPHeader header) { if (header == null || "close".equalsIgnoreCase(header.getFirstHeaderValue(HTTPHeader.CONNECTION_HEADER)) || "close".equalsIgnoreCase(header.getFirstHeaderValue(HTTPHeader.PROXY_CONNECTION_HEADER))) { return true; } return false; } private InputStream createInputStream(HTTPHeader readHeader, InputStream is) throws IOException { if ("chunked".equalsIgnoreCase(readHeader.getFirstHeaderValue(HTTPHeader.TRANSFER_ENCODING_HEADER))) { is = new ChunkedInputStream(is, myCharset); } else if (readHeader.getFirstHeaderValue(HTTPHeader.CONTENT_LENGTH_HEADER) != null) { is = new FixedSizeInputStream(is, Long.parseLong(readHeader.getFirstHeaderValue(HTTPHeader.CONTENT_LENGTH_HEADER).toString())); } else if (!hasToCloseConnection(readHeader)) { // no content length and no valid transfer-encoding! // consider as empty response. // but only when there is no "Connection: close" or "Proxy-Connection: close" header, // in that case just return "is". // skipData will not read that as it should also analyze "close" instruction. // return empty stream. // and force connection close? (not to read garbage on the next request). is = new FixedSizeInputStream(is, 0); // this will force connection to close. readHeader.setHeaderValue(HTTPHeader.CONNECTION_HEADER, "close"); } if ("gzip".equals(readHeader.getFirstHeaderValue(HTTPHeader.CONTENT_ENCODING_HEADER))) { is = new GZIPInputStream(is); } return myRepository.getDebugLog().createLogStream(is); } private static synchronized SAXParserFactory getSAXParserFactory() throws FactoryConfigurationError { if (ourSAXParserFactory == null) { ourSAXParserFactory = SAXParserFactory.newInstance(); Map supportedFeatures = new SVNHashMap(); try { ourSAXParserFactory.setFeature("http://xml.org/sax/features/namespaces", true); supportedFeatures.put("http://xml.org/sax/features/namespaces", Boolean.TRUE); } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } catch (ParserConfigurationException e) { } try { ourSAXParserFactory.setFeature("http://xml.org/sax/features/validation", false); supportedFeatures.put("http://xml.org/sax/features/validation", Boolean.FALSE); } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } catch (ParserConfigurationException e) { } try { ourSAXParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); supportedFeatures.put("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE); } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } catch (ParserConfigurationException e) { } if (supportedFeatures.size() < 3) { ourSAXParserFactory = SAXParserFactory.newInstance(); for (Iterator names = supportedFeatures.keySet().iterator(); names.hasNext();) { String name = (String) names.next(); try { ourSAXParserFactory.setFeature(name, supportedFeatures.get(name) == Boolean.TRUE); } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } catch (ParserConfigurationException e) { } } } ourSAXParserFactory.setNamespaceAware(true); ourSAXParserFactory.setValidating(false); } return ourSAXParserFactory; } public void setSpoolResponse(boolean spoolResponse) { myIsSpoolResponse = spoolResponse; } }
true
true
public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException { if ("".equals(path) || path == null) { path = "/"; } // 1. prompt for ssl client cert if needed, if cancelled - throw cancellation exception. HTTPSSLKeyManager keyManager = myKeyManager == null && myRepository.getAuthenticationManager() != null ? createKeyManager() : myKeyManager; TrustManager trustManager = myTrustManager == null && myRepository.getAuthenticationManager() != null ? myRepository.getAuthenticationManager().getTrustManager(myRepository.getLocation()) : myTrustManager; String sslRealm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">"; SVNAuthentication httpAuth = myLastValidAuth; boolean isAuthForced = myRepository.getAuthenticationManager() != null ? myRepository.getAuthenticationManager().isAuthenticationForced() : false; if (httpAuth == null && isAuthForced) { httpAuth = myRepository.getAuthenticationManager().getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, sslRealm, null); myChallengeCredentials = new HTTPBasicAuthentication((SVNPasswordAuthentication)httpAuth, myCharset); } String realm = null; // 2. create request instance. HTTPRequest request = new HTTPRequest(myCharset); request.setConnection(this); request.setKeepAlive(true); request.setRequestBody(body); request.setResponseHandler(handler); request.setResponseStream(dst); SVNErrorMessage err = null; while (true) { HTTPStatus status = null; if (myNextRequestTimeout < 0 || System.currentTimeMillis() >= myNextRequestTimeout) { SVNDebugLog.getLog(SVNLogType.NETWORK).logFine("Keep-Alive timeout detected"); close(); } int retryCount = 1; try { err = null; String httpAuthResponse = null; String proxyAuthResponse = null; while(retryCount >= 0) { connect(keyManager, trustManager); request.reset(); request.setProxied(myIsProxied); request.setSecured(myIsSecured); if (myProxyAuthentication != null) { if (proxyAuthResponse == null) { request.initCredentials(myProxyAuthentication, method, path); proxyAuthResponse = myProxyAuthentication.authenticate(); } request.setProxyAuthentication(proxyAuthResponse); } if (httpAuth != null && myChallengeCredentials != null) { if (httpAuthResponse == null) { request.initCredentials(myChallengeCredentials, method, path); httpAuthResponse = myChallengeCredentials.authenticate(); } request.setAuthentication(httpAuthResponse); } try { request.dispatch(method, path, header, ok1, ok2, context); break; } catch (EOFException pe) { // retry, EOF always means closed connection. if (retryCount > 0) { close(); continue; } throw (IOException) new IOException(pe.getMessage()).initCause(pe); } finally { retryCount--; } } myNextRequestTimeout = request.getNextRequestTimeout(); status = request.getStatus(); } catch (SSLHandshakeException ssl) { myRepository.getDebugLog().logFine(ssl); close(); if (ssl.getCause() instanceof SVNSSLUtil.CertificateNotTrustedException) { SVNErrorManager.cancel(ssl.getCause().getMessage()); } SVNErrorMessage sslErr = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "SSL handshake failed: ''{0}''", new Object[] { ssl.getMessage() }, SVNErrorMessage.TYPE_ERROR, ssl); if (keyManager != null) { keyManager.acknowledgeAndClearAuthentication(sslErr); } err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, ssl); continue; } catch (IOException e) { myRepository.getDebugLog().logFine(e); if (e instanceof SocketTimeoutException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "timed out waiting for server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof UnknownHostException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "unknown host", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof ConnectException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "connection refused by the server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof SVNCancellableOutputStream.IOCancelException) { SVNErrorManager.cancel(e.getMessage()); } else if (e instanceof SSLException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e.getMessage()); } else { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e.getMessage()); } } catch (SVNException e) { myRepository.getDebugLog().logFine(e); // force connection close on SVNException // (could be thrown by user's auth manager methods). close(); throw e; } finally { finishResponse(request); } if (err != null) { close(); break; } if (keyManager != null) { myKeyManager = keyManager; myTrustManager = trustManager; keyManager.acknowledgeAndClearAuthentication(null); } if (status.getCode() == HttpURLConnection.HTTP_FORBIDDEN) { myLastValidAuth = null; close(); err = request.getErrorMessage(); } else if (myIsProxied && status.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) { Collection proxyAuthHeaders = request.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER); try { myProxyAuthentication = HTTPAuthentication.parseAuthParameters(proxyAuthHeaders, myProxyAuthentication, myCharset); } catch (SVNException svne) { myRepository.getDebugLog().logFine(svne); err = svne.getErrorMessage(); break; } if (myProxyAuthentication instanceof HTTPNTLMAuthentication) { HTTPNTLMAuthentication ntlmProxyAuth = (HTTPNTLMAuthentication)myProxyAuthentication; if (ntlmProxyAuth.isInType3State()) { continue; } } err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed"); SVNURL location = myRepository.getLocation(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(location) : null; if (proxyManager != null) { proxyManager.acknowledgeProxyContext(false, err); } close(); break; } else if (status.getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { Collection authHeaderValues = request.getResponseHeader().getHeaderValues(HTTPHeader.AUTHENTICATE_HEADER); if (authHeaderValues == null || authHeaderValues.size() == 0) { err = request.getErrorMessage(); status.setError(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, err.getMessageTemplate(), err.getRelatedObjects())); if ("LOCK".equalsIgnoreCase(method)) { status.getError().setChildErrorMessage(SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Probably you are trying to lock file in repository that only allows anonymous access")); } SVNErrorManager.error(status.getError()); return status; } //we should work around a situation when a server //does not support Basic authentication while we're //forcing it, credentials should not be immediately //thrown away boolean skip = false; isAuthForced = myRepository.getAuthenticationManager() != null ? myRepository.getAuthenticationManager().isAuthenticationForced() : false; if (isAuthForced) { if (httpAuth != null && myChallengeCredentials != null && !HTTPAuthentication.isSchemeSupportedByServer(myChallengeCredentials.getAuthenticationScheme(), authHeaderValues)) { skip = true; } } try { myChallengeCredentials = HTTPAuthentication.parseAuthParameters(authHeaderValues, myChallengeCredentials, myCharset); } catch (SVNException svne) { err = svne.getErrorMessage(); break; } myChallengeCredentials.setChallengeParameter("methodname", method); myChallengeCredentials.setChallengeParameter("uri", path); if (skip) { close(); continue; } if (myChallengeCredentials instanceof HTTPNTLMAuthentication) { HTTPNTLMAuthentication ntlmAuth = (HTTPNTLMAuthentication)myChallengeCredentials; if (ntlmAuth.isInType3State()) { continue; } } else if (myChallengeCredentials instanceof HTTPDigestAuthentication) { // continue (retry once) if previous request was acceppted? if (myLastValidAuth != null) { myLastValidAuth = null; continue; } } myLastValidAuth = null; close(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); if (authManager == null) { err = request.getErrorMessage(); break; } realm = myChallengeCredentials.getChallengeParameter("realm"); realm = realm == null ? "" : " " + realm; realm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">" + realm; if (httpAuth == null) { httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } else { authManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth); httpAuth = authManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } if (httpAuth == null) { err = SVNErrorMessage.create(SVNErrorCode.CANCELLED, "HTTP authorization cancelled"); break; } myChallengeCredentials.setCredentials((SVNPasswordAuthentication)httpAuth); continue; } else if (status.getCode() == HttpURLConnection.HTTP_MOVED_PERM || status.getCode() == HttpURLConnection.HTTP_MOVED_TEMP) { close(); String newLocation = request.getResponseHeader().getFirstHeaderValue(HTTPHeader.LOCATION_HEADER); if (newLocation == null) { err = request.getErrorMessage(); break; } int hostIndex = newLocation.indexOf("://"); if (hostIndex > 0) { hostIndex += 3; hostIndex = newLocation.indexOf("/", hostIndex); } if (hostIndex > 0 && hostIndex < newLocation.length()) { String newPath = newLocation.substring(hostIndex); if (newPath.endsWith("/") && !newPath.endsWith("//") && !path.endsWith("/") && newPath.substring(0, newPath.length() - 1).equals(path)) { path += "//"; continue; } } err = request.getErrorMessage(); } else if (request.getErrorMessage() != null) { err = request.getErrorMessage(); } if (err != null) { break; } if (myIsProxied) { SVNURL location = myRepository.getLocation(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(location) : null; if (proxyManager != null) { proxyManager.acknowledgeProxyContext(true, null); } } if (httpAuth != null && realm != null && myRepository.getAuthenticationManager() != null) { myRepository.getAuthenticationManager().acknowledgeAuthentication(true, ISVNAuthenticationManager.PASSWORD, realm, null, httpAuth); } myLastValidAuth = httpAuth; status.setHeader(request.getResponseHeader()); return status; } // force close on error that was not processed before. // these are errors that has no relation to http status (processing error or cancellation). close(); if (err != null && err.getErrorCode().getCategory() != SVNErrorCode.RA_DAV_CATEGORY && err.getErrorCode() != SVNErrorCode.UNSUPPORTED_FEATURE) { SVNErrorManager.error(err); } // err2 is another default context... // myRepository.getDebugLog().info(err.getMessage()); myRepository.getDebugLog().logFine(new Exception(err.getMessage())); SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {method, path}, err.getType(), err.getCause()); SVNErrorManager.error(err, err2); return null; }
public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException { if ("".equals(path) || path == null) { path = "/"; } // 1. prompt for ssl client cert if needed, if cancelled - throw cancellation exception. HTTPSSLKeyManager keyManager = myKeyManager == null && myRepository.getAuthenticationManager() != null ? createKeyManager() : myKeyManager; TrustManager trustManager = myTrustManager == null && myRepository.getAuthenticationManager() != null ? myRepository.getAuthenticationManager().getTrustManager(myRepository.getLocation()) : myTrustManager; String sslRealm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">"; SVNAuthentication httpAuth = myLastValidAuth; boolean isAuthForced = myRepository.getAuthenticationManager() != null ? myRepository.getAuthenticationManager().isAuthenticationForced() : false; if (httpAuth == null && isAuthForced) { httpAuth = myRepository.getAuthenticationManager().getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, sslRealm, null); myChallengeCredentials = new HTTPBasicAuthentication((SVNPasswordAuthentication)httpAuth, myCharset); } String realm = null; // 2. create request instance. HTTPRequest request = new HTTPRequest(myCharset); request.setConnection(this); request.setKeepAlive(true); request.setRequestBody(body); request.setResponseHandler(handler); request.setResponseStream(dst); SVNErrorMessage err = null; while (true) { HTTPStatus status = null; if (myNextRequestTimeout < 0 || System.currentTimeMillis() >= myNextRequestTimeout) { SVNDebugLog.getLog(SVNLogType.NETWORK).logFine("Keep-Alive timeout detected"); close(); } int retryCount = 1; try { err = null; String httpAuthResponse = null; String proxyAuthResponse = null; while(retryCount >= 0) { connect(keyManager, trustManager); request.reset(); request.setProxied(myIsProxied); request.setSecured(myIsSecured); if (myProxyAuthentication != null) { if (proxyAuthResponse == null) { request.initCredentials(myProxyAuthentication, method, path); proxyAuthResponse = myProxyAuthentication.authenticate(); } request.setProxyAuthentication(proxyAuthResponse); } if (httpAuth != null && myChallengeCredentials != null) { if (httpAuthResponse == null) { request.initCredentials(myChallengeCredentials, method, path); httpAuthResponse = myChallengeCredentials.authenticate(); } request.setAuthentication(httpAuthResponse); } try { request.dispatch(method, path, header, ok1, ok2, context); break; } catch (EOFException pe) { // retry, EOF always means closed connection. if (retryCount > 0) { close(); continue; } throw (IOException) new IOException(pe.getMessage()).initCause(pe); } finally { retryCount--; } } myNextRequestTimeout = request.getNextRequestTimeout(); status = request.getStatus(); } catch (SSLHandshakeException ssl) { myRepository.getDebugLog().logFine(ssl); close(); if (ssl.getCause() instanceof SVNSSLUtil.CertificateNotTrustedException) { SVNErrorManager.cancel(ssl.getCause().getMessage()); } SVNErrorMessage sslErr = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "SSL handshake failed: ''{0}''", new Object[] { ssl.getMessage() }, SVNErrorMessage.TYPE_ERROR, ssl); if (keyManager != null) { keyManager.acknowledgeAndClearAuthentication(sslErr); } err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, ssl); continue; } catch (IOException e) { myRepository.getDebugLog().logFine(e); if (e instanceof SocketTimeoutException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "timed out waiting for server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof UnknownHostException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "unknown host", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof ConnectException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "connection refused by the server", null, SVNErrorMessage.TYPE_ERROR, e); } else if (e instanceof SVNCancellableOutputStream.IOCancelException) { SVNErrorManager.cancel(e.getMessage()); } else if (e instanceof SSLException) { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e.getMessage()); } else { err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e.getMessage()); } } catch (SVNException e) { myRepository.getDebugLog().logFine(e); // force connection close on SVNException // (could be thrown by user's auth manager methods). close(); throw e; } finally { finishResponse(request); } if (err != null) { close(); break; } if (keyManager != null) { myKeyManager = keyManager; myTrustManager = trustManager; keyManager.acknowledgeAndClearAuthentication(null); } if (status.getCode() == HttpURLConnection.HTTP_FORBIDDEN) { myLastValidAuth = null; close(); err = request.getErrorMessage(); } else if (myIsProxied && status.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) { Collection proxyAuthHeaders = request.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER); try { myProxyAuthentication = HTTPAuthentication.parseAuthParameters(proxyAuthHeaders, myProxyAuthentication, myCharset); } catch (SVNException svne) { myRepository.getDebugLog().logFine(svne); err = svne.getErrorMessage(); break; } if (myProxyAuthentication instanceof HTTPNTLMAuthentication) { HTTPNTLMAuthentication ntlmProxyAuth = (HTTPNTLMAuthentication)myProxyAuthentication; if (ntlmProxyAuth.isInType3State()) { continue; } } err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed"); SVNURL location = myRepository.getLocation(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(location) : null; if (proxyManager != null) { proxyManager.acknowledgeProxyContext(false, err); } close(); break; } else if (status.getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { Collection authHeaderValues = request.getResponseHeader().getHeaderValues(HTTPHeader.AUTHENTICATE_HEADER); if (authHeaderValues == null || authHeaderValues.size() == 0) { err = request.getErrorMessage(); status.setError(SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, err.getMessageTemplate(), err.getRelatedObjects())); if ("LOCK".equalsIgnoreCase(method)) { status.getError().setChildErrorMessage(SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE, "Probably you are trying to lock file in repository that only allows anonymous access")); } SVNErrorManager.error(status.getError()); return status; } //we should work around a situation when a server //does not support Basic authentication while we're //forcing it, credentials should not be immediately //thrown away boolean skip = false; isAuthForced = myRepository.getAuthenticationManager() != null ? myRepository.getAuthenticationManager().isAuthenticationForced() : false; if (isAuthForced) { if (httpAuth != null && myChallengeCredentials != null && !HTTPAuthentication.isSchemeSupportedByServer(myChallengeCredentials.getAuthenticationScheme(), authHeaderValues)) { skip = true; } } try { myChallengeCredentials = HTTPAuthentication.parseAuthParameters(authHeaderValues, myChallengeCredentials, myCharset); } catch (SVNException svne) { err = svne.getErrorMessage(); break; } myChallengeCredentials.setChallengeParameter("methodname", method); myChallengeCredentials.setChallengeParameter("uri", path); if (skip) { close(); continue; } if (myChallengeCredentials instanceof HTTPNTLMAuthentication) { HTTPNTLMAuthentication ntlmAuth = (HTTPNTLMAuthentication)myChallengeCredentials; if (ntlmAuth.isInType3State()) { continue; } } else if (myChallengeCredentials instanceof HTTPDigestAuthentication) { // continue (retry once) if previous request was acceppted? if (myLastValidAuth != null) { myLastValidAuth = null; continue; } } myLastValidAuth = null; ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); if (authManager == null) { err = request.getErrorMessage(); break; } realm = myChallengeCredentials.getChallengeParameter("realm"); realm = realm == null ? "" : " " + realm; realm = "<" + myHost.getProtocol() + "://" + myHost.getHost() + ":" + myHost.getPort() + ">" + realm; if (httpAuth == null) { httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } else { authManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth); httpAuth = authManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation()); } if (httpAuth == null) { err = SVNErrorMessage.create(SVNErrorCode.CANCELLED, "HTTP authorization cancelled"); break; } myChallengeCredentials.setCredentials((SVNPasswordAuthentication)httpAuth); continue; } else if (status.getCode() == HttpURLConnection.HTTP_MOVED_PERM || status.getCode() == HttpURLConnection.HTTP_MOVED_TEMP) { close(); String newLocation = request.getResponseHeader().getFirstHeaderValue(HTTPHeader.LOCATION_HEADER); if (newLocation == null) { err = request.getErrorMessage(); break; } int hostIndex = newLocation.indexOf("://"); if (hostIndex > 0) { hostIndex += 3; hostIndex = newLocation.indexOf("/", hostIndex); } if (hostIndex > 0 && hostIndex < newLocation.length()) { String newPath = newLocation.substring(hostIndex); if (newPath.endsWith("/") && !newPath.endsWith("//") && !path.endsWith("/") && newPath.substring(0, newPath.length() - 1).equals(path)) { path += "//"; continue; } } err = request.getErrorMessage(); } else if (request.getErrorMessage() != null) { err = request.getErrorMessage(); } if (err != null) { break; } if (myIsProxied) { SVNURL location = myRepository.getLocation(); ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager(); ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(location) : null; if (proxyManager != null) { proxyManager.acknowledgeProxyContext(true, null); } } if (httpAuth != null && realm != null && myRepository.getAuthenticationManager() != null) { myRepository.getAuthenticationManager().acknowledgeAuthentication(true, ISVNAuthenticationManager.PASSWORD, realm, null, httpAuth); } myLastValidAuth = httpAuth; status.setHeader(request.getResponseHeader()); return status; } // force close on error that was not processed before. // these are errors that has no relation to http status (processing error or cancellation). close(); if (err != null && err.getErrorCode().getCategory() != SVNErrorCode.RA_DAV_CATEGORY && err.getErrorCode() != SVNErrorCode.UNSUPPORTED_FEATURE) { SVNErrorManager.error(err); } // err2 is another default context... // myRepository.getDebugLog().info(err.getMessage()); myRepository.getDebugLog().logFine(new Exception(err.getMessage())); SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {method, path}, err.getType(), err.getCause()); SVNErrorManager.error(err, err2); return null; }
diff --git a/modules/datatable/org/molgenis/datatable/model/AbstractTupleTable.java b/modules/datatable/org/molgenis/datatable/model/AbstractTupleTable.java index 524c64df3..993a94083 100644 --- a/modules/datatable/org/molgenis/datatable/model/AbstractTupleTable.java +++ b/modules/datatable/org/molgenis/datatable/model/AbstractTupleTable.java @@ -1,171 +1,171 @@ package org.molgenis.datatable.model; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.molgenis.framework.db.Database; import org.molgenis.framework.db.DatabaseException; import org.molgenis.model.elements.Field; import org.molgenis.util.Tuple; import app.DatabaseFactory; public abstract class AbstractTupleTable implements TupleTable { private int limit = 0; private int offset = 0; private int colOffset = 0; private int colLimit = 0; private Database db; @Override public void reset() { limit = 0; offset = 0; colOffset = 0; colLimit = 0; } @Override public int getLimit() { return limit; } @Override public void setLimit(int limit) { if (limit < 0) throw new RuntimeException("limit cannot be < 0"); this.limit = limit; } @Override public int getOffset() { return offset; } @Override public void setOffset(int offset) { if (offset < 0) throw new RuntimeException("offset cannot be < 0"); this.offset = offset; } @Override public abstract List<Field> getAllColumns() throws TableException; @Override public List<Field> getColumns() throws TableException { List<Field> columns = getAllColumns(); if (getColOffset() > 0) { if (getColLimit() > 0) { - return columns.subList(getColOffset(), getColOffset() + getColLimit()); + return columns.subList(getColOffset(), Math.min(getColOffset() + getColLimit(), columns.size())); } else { return columns.subList(getColOffset(), columns.size()); } } else { if (getColLimit() > 0) { return columns.subList(0, getColLimit()); } else { return columns; } } } @Override public List<Tuple> getRows() throws TableException { List<Tuple> result = new ArrayList<Tuple>(); for (Tuple t : this) { result.add(t); } return result; } @Override public abstract Iterator<Tuple> iterator(); @Override public void close() throws TableException { // close resources if applicable } @Override public abstract int getCount() throws TableException; @Override public int getColCount() throws TableException { return this.getColumns().size(); } @Override public void setColLimit(int limit) { if (limit < 0) throw new RuntimeException("colLimit cannot be < 0"); this.colLimit = limit; } @Override public int getColLimit() { return this.colLimit; } @Override public int getColOffset() { return this.colOffset; } @Override public void setColOffset(int offset) { if (offset < 0) throw new RuntimeException("colOffset cannot be < 0"); this.colOffset = offset; } @Override public void setDb(Database db) { if (db == null) throw new NullPointerException("database cannot be null in setDb(db)"); this.db = db; } @Override public void setLimitOffset(int limit, int offset) { this.setLimit(limit); this.setOffset(offset); } public Database getDb() { try { db = DatabaseFactory.create(); } catch (DatabaseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return this.db; } }
true
true
public List<Field> getColumns() throws TableException { List<Field> columns = getAllColumns(); if (getColOffset() > 0) { if (getColLimit() > 0) { return columns.subList(getColOffset(), getColOffset() + getColLimit()); } else { return columns.subList(getColOffset(), columns.size()); } } else { if (getColLimit() > 0) { return columns.subList(0, getColLimit()); } else { return columns; } } }
public List<Field> getColumns() throws TableException { List<Field> columns = getAllColumns(); if (getColOffset() > 0) { if (getColLimit() > 0) { return columns.subList(getColOffset(), Math.min(getColOffset() + getColLimit(), columns.size())); } else { return columns.subList(getColOffset(), columns.size()); } } else { if (getColLimit() > 0) { return columns.subList(0, getColLimit()); } else { return columns; } } }
diff --git a/src/main/java/si/mazi/rescu/HttpTemplate.java b/src/main/java/si/mazi/rescu/HttpTemplate.java index 7985812..e7a97a0 100644 --- a/src/main/java/si/mazi/rescu/HttpTemplate.java +++ b/src/main/java/si/mazi/rescu/HttpTemplate.java @@ -1,290 +1,285 @@ /** * Copyright (C) 2012 - 2013 Xeiam LLC http://xeiam.com * Copyright (C) 2012 - 2013 Matija Mazi [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 si.mazi.rescu; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import si.mazi.rescu.utils.Assert; import javax.xml.ws.http.HTTPException; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; /** * Various HTTP utility methods */ class HttpTemplate { public final static String CHARSET_UTF_8 = "UTF-8"; private final Logger log = LoggerFactory.getLogger(HttpTemplate.class); private ObjectMapper objectMapper; /** * Default request header fields */ private Map<String, String> defaultHttpHeaders = new HashMap<String, String>(); private final int readTimeout = Config.getHttpReadTimeout(); /** * Constructor */ public HttpTemplate() { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // Always use UTF8 defaultHttpHeaders.put("Accept-Charset", CHARSET_UTF_8); // Assume form encoding by default (typically becomes application/json or application/xml) defaultHttpHeaders.put("Content-Type", "application/x-www-form-urlencoded"); // Accept text/plain by default (typically becomes application/json or application/xml) defaultHttpHeaders.put("Accept", "text/plain"); // User agent provides statistics for servers, but some use it for content negotiation so fake good agents defaultHttpHeaders.put("User-Agent", "ResCU JDK/6 AppleWebKit/535.7 Chrome/16.0.912.36 Safari/535.7"); // custom User-Agent } /** * Requests JSON via an HTTP POST * * @param urlString A string representation of a URL * @param returnType The required return type * @param requestBody The contents of the request body * @param httpHeaders Any custom header values (application/json is provided automatically) * @param method Http method (usually GET or POST) * @param contentType the mime type to be set as the value of the Content-Type header * @return String - the fetched JSON String */ public <T> T executeRequest(String urlString, Class<T> returnType, String requestBody, Map<String, String> httpHeaders, HttpMethod method, String contentType) { Assert.notNull(httpHeaders, "httpHeaders should not be null"); httpHeaders.put("Accept", "application/json"); if (contentType != null) { httpHeaders.put("Content-Type", contentType); } String response = executeRequest(urlString, requestBody, httpHeaders, method); return JSONUtils.getJsonObject(response, returnType, objectMapper); } /** * Provides an internal convenience method to allow easy overriding by test classes * * @param method The HTTP method (e.g. GET, POST etc) * @param urlString A string representation of a URL * @param httpHeaders The HTTP headers (will override the defaults) * @param contentLength * @return An HttpURLConnection based on the given parameters * @throws IOException If something goes wrong */ private HttpURLConnection configureURLConnection(HttpMethod method, String urlString, Map<String, String> httpHeaders, int contentLength) throws IOException { Assert.notNull(method, "method cannot be null"); Assert.notNull(urlString, "urlString cannot be null"); Assert.notNull(httpHeaders, "httpHeaders cannot be null"); HttpURLConnection connection = getHttpURLConnection(urlString); connection.setRequestMethod(method.name()); // Copy default HTTP headers Map<String, String> headerKeyValues = new HashMap<String, String>(defaultHttpHeaders); // Merge defaultHttpHeaders with httpHeaders headerKeyValues.putAll(httpHeaders); // Add HTTP headers to the request for (Map.Entry<String, String> entry : headerKeyValues.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); log.trace("Header request property: key='{}', value='{}'", entry.getKey(), entry.getValue()); } // Perform additional configuration for POST if (contentLength > 0) { connection.setDoOutput(true); connection.setDoInput(true); // Add content length to header connection.setRequestProperty("Content-Length", Integer.toString(contentLength)); } return connection; } /** * @param urlString * @return a HttpURLConnection instance * @throws IOException */ protected HttpURLConnection getHttpURLConnection(String urlString) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(urlString).openConnection(); if (readTimeout > 0) { connection.setReadTimeout(readTimeout); } return connection; } /** * Executes an HTTP request with the given parameters. * * @param method The HTTP method (e.g. GET, POST etc) * @param urlString A string representation of a URL * @param httpHeaders The HTTP headers (will override the defaults) * @param requestBody The request body (typically only for POST method) * @return The contents of the response body as String */ private String executeRequest(String urlString, String requestBody, Map<String, String> httpHeaders, HttpMethod method) { Assert.notNull(urlString, "urlString cannot be null"); Assert.notNull(httpHeaders, "httpHeaders cannot be null"); log.debug("Executing {} request at {}", method, urlString); log.trace("Request body = {}", requestBody); log.trace("Request headers = {}", httpHeaders); String responseString = ""; HttpURLConnection connection = null; try { int contentLength = requestBody == null ? 0 : requestBody.length(); connection = configureURLConnection(method, urlString, httpHeaders, contentLength); if (contentLength > 0) { // Write the request body connection.getOutputStream().write(requestBody.getBytes(CHARSET_UTF_8)); } // Begin reading the response checkHttpStatusCode(connection); // Minimize the impact of the HttpURLConnection on the job of getting the data String responseEncoding = getResponseEncoding(connection); InputStream inputStream = connection.getInputStream(); // Get the data responseString = readInputStreamAsEncodedString(inputStream, responseEncoding); } catch (MalformedURLException e) { throw new HttpException("Problem " + method + "ing -- malformed URL: " + urlString, e); } catch (IOException e) { throw new HttpException("Problem " + method + "ing (IO)", e); - } finally { - // This is a bit messy - if (connection != null) { - connection.disconnect(); - } } log.trace("Response body: {}", responseString); return responseString; } protected int checkHttpStatusCode(HttpURLConnection connection) throws IOException, HTTPException { int httpStatus = connection.getResponseCode(); log.debug("Request http status = {}", httpStatus); if (httpStatus != 200) { throw new HttpStatusException("Status code not OK", httpStatus, connection.getErrorStream()); } return httpStatus; } /** * <p> * Reads an InputStream as a String allowing for different encoding types * </p> * * @param inputStream The input stream * @param responseEncoding The encoding to use when converting to a String * @return A String representation of the input stream * @throws IOException If something goes wrong */ String readInputStreamAsEncodedString(InputStream inputStream, String responseEncoding) throws IOException { String responseString; if (responseEncoding != null) { // Have an encoding so use it StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, responseEncoding)); for (String line; (line = reader.readLine()) != null; ) { sb.append(line); } responseString = sb.toString(); } else { // No encoding specified so use a BufferedInputStream StringBuilder sb = new StringBuilder(); BufferedInputStream bis = new BufferedInputStream(inputStream); byte[] byteContents = new byte[4096]; int bytesRead; String strContents; while ((bytesRead = bis.read(byteContents)) != -1) { strContents = new String(byteContents, 0, bytesRead); sb.append(strContents); } responseString = sb.toString(); } // System.out.println("responseString: " + responseString); return responseString; } /** * Determine the response encoding if specified * * @param connection The HTTP connection * @return The response encoding as a string (taken from "Content-Type") */ private String getResponseEncoding(URLConnection connection) { String charset = null; String contentType = connection.getHeaderField("Content-Type"); if (contentType != null) { for (String param : contentType.replace(" ", "").split(";")) { if (param.startsWith("charset=")) { charset = param.split("=", 2)[1]; break; } } } return charset; } }
true
true
private String executeRequest(String urlString, String requestBody, Map<String, String> httpHeaders, HttpMethod method) { Assert.notNull(urlString, "urlString cannot be null"); Assert.notNull(httpHeaders, "httpHeaders cannot be null"); log.debug("Executing {} request at {}", method, urlString); log.trace("Request body = {}", requestBody); log.trace("Request headers = {}", httpHeaders); String responseString = ""; HttpURLConnection connection = null; try { int contentLength = requestBody == null ? 0 : requestBody.length(); connection = configureURLConnection(method, urlString, httpHeaders, contentLength); if (contentLength > 0) { // Write the request body connection.getOutputStream().write(requestBody.getBytes(CHARSET_UTF_8)); } // Begin reading the response checkHttpStatusCode(connection); // Minimize the impact of the HttpURLConnection on the job of getting the data String responseEncoding = getResponseEncoding(connection); InputStream inputStream = connection.getInputStream(); // Get the data responseString = readInputStreamAsEncodedString(inputStream, responseEncoding); } catch (MalformedURLException e) { throw new HttpException("Problem " + method + "ing -- malformed URL: " + urlString, e); } catch (IOException e) { throw new HttpException("Problem " + method + "ing (IO)", e); } finally { // This is a bit messy if (connection != null) { connection.disconnect(); } } log.trace("Response body: {}", responseString); return responseString; }
private String executeRequest(String urlString, String requestBody, Map<String, String> httpHeaders, HttpMethod method) { Assert.notNull(urlString, "urlString cannot be null"); Assert.notNull(httpHeaders, "httpHeaders cannot be null"); log.debug("Executing {} request at {}", method, urlString); log.trace("Request body = {}", requestBody); log.trace("Request headers = {}", httpHeaders); String responseString = ""; HttpURLConnection connection = null; try { int contentLength = requestBody == null ? 0 : requestBody.length(); connection = configureURLConnection(method, urlString, httpHeaders, contentLength); if (contentLength > 0) { // Write the request body connection.getOutputStream().write(requestBody.getBytes(CHARSET_UTF_8)); } // Begin reading the response checkHttpStatusCode(connection); // Minimize the impact of the HttpURLConnection on the job of getting the data String responseEncoding = getResponseEncoding(connection); InputStream inputStream = connection.getInputStream(); // Get the data responseString = readInputStreamAsEncodedString(inputStream, responseEncoding); } catch (MalformedURLException e) { throw new HttpException("Problem " + method + "ing -- malformed URL: " + urlString, e); } catch (IOException e) { throw new HttpException("Problem " + method + "ing (IO)", e); } log.trace("Response body: {}", responseString); return responseString; }
diff --git a/src/main/java/im/mctop/bot/DataObject.java b/src/main/java/im/mctop/bot/DataObject.java index 32e3659..101809d 100644 --- a/src/main/java/im/mctop/bot/DataObject.java +++ b/src/main/java/im/mctop/bot/DataObject.java @@ -1,51 +1,54 @@ package im.mctop.bot; import java.util.HashMap; import java.util.Map; public class DataObject { private Map<String, Object> m = new HashMap<>(); public void set( String k, String v ) { m.put(k, v); } public void set( String k, Boolean v ) { m.put(k, v); } public void set( String k, int v ) { m.put(k, v); } public void set( String k, float v ) { m.put(k, v); } public String getString( String k ) { return m.get(k).toString(); } public Boolean getBoolean( String k ) { return Boolean.valueOf(m.get(k).toString()); } public int getInt( String k ) { return Integer.valueOf(m.get(k).toString()); } public float getFloat( String k ) { return Float.valueOf(m.get(k).toString()); } @Override public String toString() { StringBuilder data = new StringBuilder(); data.append("DataObject ["); + int i = 0; for (Map.Entry<String, Object> entry : m.entrySet()) { data.append(entry.getKey()).append("=").append(entry.getValue().toString()); + if (++i < m.size()) + data.append(", "); } data.append("]"); return data.toString(); } }
false
true
public String toString() { StringBuilder data = new StringBuilder(); data.append("DataObject ["); for (Map.Entry<String, Object> entry : m.entrySet()) { data.append(entry.getKey()).append("=").append(entry.getValue().toString()); } data.append("]"); return data.toString(); }
public String toString() { StringBuilder data = new StringBuilder(); data.append("DataObject ["); int i = 0; for (Map.Entry<String, Object> entry : m.entrySet()) { data.append(entry.getKey()).append("=").append(entry.getValue().toString()); if (++i < m.size()) data.append(", "); } data.append("]"); return data.toString(); }
diff --git a/ini/trakem2/imaging/StitchingTEM.java b/ini/trakem2/imaging/StitchingTEM.java index f18d53bd..5a65a843 100644 --- a/ini/trakem2/imaging/StitchingTEM.java +++ b/ini/trakem2/imaging/StitchingTEM.java @@ -1,719 +1,722 @@ /** TrakEM2 plugin for ImageJ(C). Copyright (C) 2005, 2006, 2007 Albert Cardona and Rodney Douglas. 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 (http://www.gnu.org/licenses/gpl.txt ) 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. You may contact Albert Cardona at acardona at ini.phys.ethz.ch Institute of Neuroinformatics, University of Zurich / ETH, Switzerland. **/ package ini.trakem2.imaging; import ij.gui.Roi; import ij.process.ImageProcessor; import ij.process.ByteProcessor; import ij.process.FloatProcessor; import ij.ImagePlus; import ij.gui.GenericDialog; import ini.trakem2.utils.IJError; import ini.trakem2.utils.Utils; import ini.trakem2.display.Patch; import ini.trakem2.display.Display; import ini.trakem2.display.Displayable; import ini.trakem2.display.Layer; import ini.trakem2.display.Selection; import ini.trakem2.ControlWindow; import ini.trakem2.utils.Worker; import ini.trakem2.utils.Bureaucrat; import ini.trakem2.persistence.Loader; import mpi.fruitfly.registration.PhaseCorrelation2D; import mpi.fruitfly.registration.CrossCorrelation2D; import mpi.fruitfly.registration.ImageFilter; import mpi.fruitfly.math.datastructures.FloatArray2D; import mpi.fruitfly.math.General; import mpi.fruitfly.registration.Tile; import mpi.fruitfly.registration.Optimize; import mpi.fruitfly.registration.PointMatch; import mpi.fruitfly.registration.Point; import mpi.fruitfly.registration.TModel2D; import mpi.fruitfly.registration.TRModel2D; import java.awt.Rectangle; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Vector; import java.awt.geom.AffineTransform; /** Given: * - list of images * - grid width * - known percent overlap * * This class will attempt to find the optimal montage, * by applying phase-correlation, and/or cross-correlation, and/or SIFT-based correlation) between neighboring images. * * The method is oriented to images acquired with Transmission Electron Miscrospy, * where the acquistion of each image elastically deforms the sample, and thus * earlier images are regarded as better than later ones. * * It is assumed that images were acquired from 0 to n, as in the grid. * */ public class StitchingTEM { static public final int WORKING = -1; static public final int DONE = 0; static public final int ERROR = 1; static public final int INTERRUPTED = 2; static public final int SUCCESS = 3; static public final int TOP_BOTTOM = 4; static public final int LEFT_RIGHT = 5; static public final int TOP_LEFT_RULE = 0; static public final int FREE_RULE = 1; static public final float DEFAULT_MIN_R = 0.4f; static public void addStitchingRuleChoice(GenericDialog gd) { final String[] rules = new String[]{"Top left", "Free"}; gd.addChoice("stitching_rule: ", rules, rules[0]); } /** Returns the same Patch instances with their coordinates modified; the top-left image is assumed to be the first one, and thus serves as reference; so, after the first image, coordinates are ignored for each specific Patch. * * The cross-correlation is done always with the image to the left, and on its absence, with the image above. * If the cross-correlation returns values that would mean a depart larger than the known percent overlap, the image will be cross-correlated with its second option (i.e. the one above in almost all cases). In the absence of a second option to compare with, the percent overlap is applied as the least damaging option in the montage. * * The Patch[] array is unidimensional to allow for missing images in the last row not to interfere. * * The stitching runs in a separate thread; interested parties can query the status of the processing by calling the method getStatus(). * * The scale is used to make the images smaller when doing cross-correlation. If larger than 1, it gets put back to 1. * * Rotation of the images is NOT considered by the TOP_LEFT_RULE (phase- and cross-correlation), * but it can be for the FREE_RULE (SIFT). * * @return A new Bureaucrat Thread, or null if the initialization didn't pass the tests (all tiles have to have the same dimensions, for example). */ static public Bureaucrat stitch(final Patch[] patch, final int grid_width, final float percent_overlap, final float scale, final double default_bottom_top_overlap, final double default_left_right_overlap, final boolean optimize, final int stitching_rule) { // check preconditions if (null == patch || grid_width < 1 || percent_overlap <= 0) { return null; } if (patch.length < 2) { return null; } // compare Patch dimensions: later code needs all to be equal Rectangle b0 = patch[0].getBoundingBox(null); for (int i=1; i<patch.length; i++) { Rectangle bi = patch[i].getBoundingBox(null); if (bi.width != b0.width || bi.height != b0.height) { Utils.log2("Stitching: dimensions' missmatch.\n\tAll images MUST have the same dimensions."); // i.e. all Patches, actually (meaning, all Patch objects must have the same width and the same height). return null; } } Utils.log2("patch layer: " + patch[0].getLayer()); patch[0].getLayerSet().createUndoStep(patch[0].getLayer()); switch (stitching_rule) { case StitchingTEM.TOP_LEFT_RULE: return StitchingTEM.stitchTopLeft(patch, grid_width, percent_overlap, (scale > 1 ? 1 : scale), default_bottom_top_overlap, default_left_right_overlap, optimize); case StitchingTEM.FREE_RULE: HashSet<Patch> hs = new HashSet<Patch>(); for (int i=0; i<patch.length; i++) hs.add(patch[i]); return Registration.registerTilesSIFT(hs, patch[0], null, true); } return null; } static private Bureaucrat stitchTopLeft(final Patch[] patch, final int grid_width, final float percent_overlap, final float scale, final double default_bottom_top_overlap, final double default_left_right_overlap, final boolean optimize) { final Worker worker = new Worker("Stitching") { public void run() { + startedWorking(); try { final int LEFT = 0, TOP = 1; int prev_i = 0; int prev = LEFT; double[] R1=null, R2=null; // for scoring phase- and cross-correlation final float min_R = patch[0].getProject().getProperty("min_R", DEFAULT_MIN_R); // for minimization: ArrayList<Tile> al_tiles = new ArrayList<Tile>(); // first patch-tile: TModel2D first_tile_model = new TModel2D(); first_tile_model.getAffine().setTransform( patch[ 0 ].getAffineTransform() ); al_tiles.add(new Tile((float)patch[0].getWidth(), (float)patch[0].getHeight(), first_tile_model )); for (int i=1; i<patch.length; i++) { if (hasQuitted()) { return; } // boundary checks: don't allow displacements beyond these values final double default_dx = default_left_right_overlap; final double default_dy = default_bottom_top_overlap; // for minimization: Tile tile_left = null; Tile tile_top = null; TModel2D tile_model = new TModel2D(); tile_model.getAffine().setTransform( patch[ i ].getAffineTransform() ); Tile tile = new Tile((float)patch[i].getWidth(), (float)patch[i].getHeight(), tile_model ); al_tiles.add(tile); // stitch with the one above if starting row if (0 == i % grid_width) { prev_i = i - grid_width; prev = TOP; } else { prev_i = i -1; prev = LEFT; } if (TOP == prev) { // compare with top only R1 = correlate(patch[prev_i], patch[i], percent_overlap, scale, TOP_BOTTOM, default_dx, default_dy, min_R); R2 = null; tile_top = al_tiles.get(i - grid_width); } else { // the one on the left R2 = correlate(patch[prev_i], patch[i], percent_overlap, scale, LEFT_RIGHT, default_dx, default_dy, min_R); tile_left = al_tiles.get(i - 1); // the one above if (i - grid_width > -1) { R1 = correlate(patch[i - grid_width], patch[i], percent_overlap, scale, TOP_BOTTOM, default_dx, default_dy, min_R); tile_top = al_tiles.get(i - grid_width); } else { R1 = null; } } // boundary limits: don't move by more than the small dimension of the stripe int max_abs_delta; // TODO: only the dx for left (and the dy for top) should be compared and found to be smaller or equal; the other dimension should be unbounded -for example, for manually acquired, grossly out-of-grid tiles. final Rectangle box = new Rectangle(); final Rectangle box2 = new Rectangle(); // check and apply: falls back to default overlaps when getting bad results if (TOP == prev) { if (SUCCESS == R1[2]) { // trust top if (optimize) addMatches(tile_top, tile, R1[0], R1[1]); else { patch[i - grid_width].getBoundingBox(box); patch[i].setLocation(box.x + R1[0], box.y + R1[1]); } } else { final Rectangle b2 = patch[i - grid_width].getBoundingBox(null); // don't move: use default overlap if (optimize) addMatches(tile_top, tile, 0, b2.height - default_bottom_top_overlap); else { patch[i - grid_width].getBoundingBox(box); patch[i].setLocation(box.x, box.y + b2.height - default_bottom_top_overlap); } } } else { // LEFT // the one on top, if any if (i - grid_width > -1) { if (SUCCESS == R1[2]) { // top is good if (SUCCESS == R2[2]) { // combine left and top if (optimize) { addMatches(tile_left, tile, R2[0], R2[1]); addMatches(tile_top, tile, R1[0], R1[1]); } else { patch[i-1].getBoundingBox(box); patch[i - grid_width].getBoundingBox(box2); patch[i].setLocation((box.x + R1[0] + box2.x + R2[0]) / 2, (box.y + R1[1] + box2.y + R2[1]) / 2); } } else { // use top alone if (optimize) addMatches(tile_top, tile, R1[0], R1[1]); else { patch[i - grid_width].getBoundingBox(box); patch[i].setLocation(box.x + R1[0], box.y + R1[1]); } } } else { // ignore top if (SUCCESS == R2[2]) { // use left alone if (optimize) addMatches(tile_left, tile, R2[0], R2[1]); else { patch[i-1].getBoundingBox(box); patch[i].setLocation(box.x + R2[0], box.y + R2[1]); } } else { patch[prev_i].getBoundingBox(box); patch[i - grid_width].getBoundingBox(box2); // left not trusted, top not trusted: use a combination of defaults for both if (optimize) { addMatches(tile_left, tile, box.width - default_left_right_overlap, 0); addMatches(tile_top, tile, 0, box2.height - default_bottom_top_overlap); } else { patch[i].setLocation(box.x + box.width - default_left_right_overlap, box2.y + box2.height - default_bottom_top_overlap); } } } } else if (SUCCESS == R2[2]) { // use left alone (top not applicable in top row) if (optimize) addMatches(tile_left, tile, R2[0], R2[1]); else { patch[i-1].getBoundingBox(box); patch[i].setLocation(box.x + R2[0], box.y + R2[1]); } } else { patch[prev_i].getBoundingBox(box); // left not trusted, and top not applicable: use default overlap with left tile if (optimize) addMatches(tile_left, tile, box.width - default_left_right_overlap, 0); else { patch[i].setLocation(box.x + box.width - default_left_right_overlap, box.y); } } } if (!optimize) Display.repaint(patch[i].getLayer(), patch[i], null, 0, false); Utils.log2(i + ": Done patch " + patch[i]); } if (optimize) { // run optimization ArrayList<Patch> al_patches = new ArrayList<Patch>(); for (int i=0; i<patch.length; i++) al_patches.add(patch[i]); ArrayList<Tile> al_fixed_tiles = new ArrayList<Tile>(); al_fixed_tiles.add(al_tiles.get(0)); // ready for montage-wise minimization Optimize.minimizeAll(al_tiles, al_patches, al_fixed_tiles, 50); } Display.repaint(patch[0].getLayer(), null, 0, true); // all // } catch (Exception e) { IJError.print(e); + } finally { + finishedWorking(); } } }; Bureaucrat burro = new Bureaucrat(worker, patch[0].getProject()); burro.goHaveBreakfast(); return burro; } /** dx, dy is the position of t2 relative to the 0,0 of t1. */ static private final void addMatches(Tile t1, Tile t2, double dx, double dy) { Point p1 = new Point(new float[]{0f, 0f}); Point p2 = new Point(new float[]{(float)dx, (float)dy}); t1.addMatch(new PointMatch(p2, p1, 1.0f)); t2.addMatch(new PointMatch(p1, p2, 1.0f)); t1.addConnectedTile(t2); t2.addConnectedTile(t1); } static public ImageProcessor makeStripe(final Patch p, final Roi roi, final float scale) { return makeStripe(p, roi, scale, false); } static public ImageProcessor makeStripe(final Patch p, final float scale, final boolean ignore_patch_transform) { return makeStripe(p, null, scale, ignore_patch_transform); } /** @return FloatProcessor. * @param ignore_patch_transform will prevent resizing of the ImageProcessor in the event of the Patch having a transform different than identity. */ // TODO 2: there is a combination of options that ends up resulting in the actual ImageProcessor of the Patch being returned as is, which is DANGEROUS because it can potentially result in changes in the data. static public ImageProcessor makeStripe(final Patch p, final Roi roi, final float scale, boolean ignore_patch_transform) { ImagePlus imp = null; ImageProcessor ip = null; Loader loader = p.getProject().getLoader(); // check if using mipmaps and if there is a file for it. If there isn't, most likely this method is being called in an import sequence as grid procedure. if (loader.isMipMapsEnabled() && loader.checkMipMapFileExists(p, scale)) { Image image = p.getProject().getLoader().fetchImage(p, scale); // check that dimensions are correct. If anything, they'll be larger //Utils.log2("patch w,h " + p.getWidth() + ", " + p.getHeight() + " fetched image w,h: " + image.getWidth(null) + ", " + image.getHeight(null)); if (Math.abs(p.getWidth() * scale - image.getWidth(null)) > 0.001 || Math.abs(p.getHeight() * scale - image.getHeight(null)) > 0.001) { image = image.getScaledInstance((int)(p.getWidth() * scale), (int)(p.getHeight() * scale), Image.SCALE_AREA_AVERAGING); // slow but good quality. Makes an RGB image, but it doesn't matter. //Utils.log2(" resizing, now image w,h: " + image.getWidth(null) + ", " + image.getHeight(null)); } try { imp = new ImagePlus("s", image); ip = imp.getProcessor(); } catch (Exception e) { IJError.print(e); } // cut if (null != roi) { // scale ROI! Rectangle rb = roi.getBounds(); Roi roi2 = new Roi((int)(rb.x * scale), (int)(rb.y * scale), (int)(rb.width * scale), (int)(rb.height * scale)); rb = roi2.getBounds(); if (ip.getWidth() != rb.width || ip.getHeight() != rb.height) { ip.setRoi(roi2); ip = ip.crop(); } } //Utils.log2("scale: " + scale + " ip w,h: " + ip.getWidth() + ", " + ip.getHeight()); } else { imp = loader.fetchImagePlus(p); ip = imp.getProcessor(); // compare and adjust if (!ignore_patch_transform && p.getAffineTransform().getType() != AffineTransform.TYPE_TRANSLATION) { // if it's not only a translation: final Rectangle b = p.getBoundingBox(); ip = ip.resize(b.width, b.height); //Utils.log2("resizing stripe for patch: " + p); // the above is only meant to correct for improperly acquired images at the microscope, the scale only. } // cut if (null != roi) { final Rectangle rb = roi.getBounds(); if (ip.getWidth() != rb.width || ip.getHeight() != rb.height) { ip.setRoi(roi); ip = ip.crop(); } } // scale if (scale < 1) { p.getProject().getLoader().releaseToFit((long)(ip.getWidth() * ip.getHeight() * 4 * 1.2)); // floats have 4 bytes, plus some java peripherals correction factor ip = ip.convertToFloat(); ip.setPixels(ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip.getPixels(), ip.getWidth(), ip.getHeight()), (float)Math.sqrt(0.25 / scale / scale - 0.25)).data); // scaling with area averaging is the same as a gaussian of sigma 0.5/scale and then resize with nearest neightbor So this line does the gaussian, and line below does the neares-neighbor scaling ip = ip.resize((int)(ip.getWidth() * scale)); // scale mantaining aspect ratio } } //Utils.log2("makeStripe: w,h " + ip.getWidth() + ", " + ip.getHeight()); // return a FloatProcessor if (imp.getType() != ImagePlus.GRAY32) return ip.convertToFloat(); return ip; } /** @param scale For optimizing the speed of phase- and cross-correlation.<br /> * @param percent_overlap The minimum chunk of adjacent images to compare with, will automatically and gradually increase to 100% if no good matches are found.<br /> * @Return a double[4] array containing:<br /> * - x2: relative X position of the second Patch<br /> * - y2: relative Y position of the second Patch<br /> * - flag: ERROR or SUCCESS<br /> * - R: cross-correlation coefficient<br /> */ static public double[] correlate(final Patch base, final Patch moving, final float percent_overlap, final float scale, final int direction, final double default_dx, final double default_dy, final float min_R) { PhaseCorrelation2D pc = null; double R = -2; final int limit = 5; // number of peaks to check in the PhaseCorrelation results //final float min_R = 0.40f; // minimum R for phase-correlation to be considered good // half this min_R will be considered good for cross-correlation // Iterate until PhaseCorrelation correlation coeficient R is over 0.5, or there's no more // image overlap to feed Utils.log2("min_R: " + min_R); ImageProcessor ip1, ip2; final Rectangle b1 = base.getBoundingBox(null); final Rectangle b2 = moving.getBoundingBox(null); final int w1 = b1.width, h1 = b1.height, w2 = b2.width, h2 = b2.height; Roi roi1=null, roi2=null; float overlap = percent_overlap; double dx = default_dx, dy = default_dy; do { // create rois for the stripes switch(direction) { case TOP_BOTTOM: roi1 = new Roi(0, h1 - (int)(h1 * overlap), w1, (int)(h1 * overlap)); // bottom roi2 = new Roi(0, 0, w2, (int)(h2 * overlap)); // top break; case LEFT_RIGHT: roi1 = new Roi(w1 - (int)(w1 * overlap), 0, (int)(w1 * overlap), h1); // right roi2 = new Roi(0, 0, (int)(w2 * overlap), h2); // left break; } //Utils.log2("roi1: " + roi1); //Utils.log2("roi2: " + roi2); ip1 = makeStripe(base, roi1, scale); // will apply the transform if necessary ip2 = makeStripe(moving, roi2, scale); //new ImagePlus("roi1", ip1).show(); //new ImagePlus("roi2", ip2).show(); ip1.setPixels(ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip1.getPixels(), ip1.getWidth(), ip1.getHeight()), 1f).data); ip2.setPixels(ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip2.getPixels(), ip2.getWidth(), ip2.getHeight()), 1f).data); // pc = new PhaseCorrelation2D(ip1, ip2, limit, true, false, false); // with windowing final java.awt.Point shift = pc.computePhaseCorrelation(); final PhaseCorrelation2D.CrossCorrelationResult result = pc.getResult(); Utils.log2("overlap: " + overlap + " R: " + result.R + " shift: " + shift + " dx,dy: " + dx + ", " + dy); if (result.R >= min_R) { // success int success = SUCCESS; switch(direction) { case TOP_BOTTOM: // boundary checks: //if (shift.y/scale > default_dy) success = ERROR; dx = shift.x/scale; dy = roi1.getBounds().y + shift.y/scale; break; case LEFT_RIGHT: // boundary checks: //if (shift.x/scale > default_dx) success = ERROR; dx = roi1.getBounds().x + shift.x/scale; dy = shift.y/scale; break; } Utils.log2("R: " + result.R + " shift: " + shift + " dx,dy: " + dx + ", " + dy); return new double[]{dx, dy, success, result.R}; } //new ImagePlus("roi1", ip1.duplicate()).show(); //new ImagePlus("roi2", ip2.duplicate()).show(); //try { Thread.sleep(1000000000); } catch (Exception e) {} // increase for next iteration overlap += 0.10; // increments of 10% } while (R < min_R && Math.abs(overlap - 1.0f) < 0.001f); // Phase-correlation failed, fall back to cross-correlation with a safe overlap overlap = percent_overlap * 2; if (overlap > 1.0f) overlap = 1.0f; switch(direction) { case TOP_BOTTOM: roi1 = new Roi(0, h1 - (int)(h1 * overlap), w1, (int)(h1 * overlap)); // bottom roi2 = new Roi(0, 0, w2, (int)(h2 * overlap)); // top break; case LEFT_RIGHT: roi1 = new Roi(w1 - (int)(w1 * overlap), 0, (int)(w1 * overlap), h1); // right roi2 = new Roi(0, 0, (int)(w2 * overlap), h2); // left break; } // use one third of the size used for phase-correlation though! Otherwise, it may take FOREVER float scale_cc = (float)(scale / 3f); ip1 = makeStripe(base, roi1, scale_cc); ip2 = makeStripe(moving, roi2, scale_cc); // gaussian blur them before cross-correlation ip1.setPixels(ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip1.getPixels(), ip1.getWidth(), ip1.getHeight()), 1f).data); ip2.setPixels(ImageFilter.computeGaussianFastMirror(new FloatArray2D((float[])ip2.getPixels(), ip2.getWidth(), ip2.getHeight()), 1f).data); //new ImagePlus("CC roi1", ip1).show(); //new ImagePlus("CC roi2", ip2).show(); final CrossCorrelation2D cc = new CrossCorrelation2D(ip1, ip2, false); double[] cc_result = null; switch (direction) { case TOP_BOTTOM: cc_result = cc.computeCrossCorrelationMT(0.9, 0.3, false); break; case LEFT_RIGHT: cc_result = cc.computeCrossCorrelationMT(0.3, 0.9, false); break; } if (cc_result[2] > min_R/2) { //accepting if R is above half the R accepted for Phase Correlation // success int success = SUCCESS; switch(direction) { case TOP_BOTTOM: // boundary checks: //if (cc_result[1]/scale_cc > default_dy) success = ERROR; dx = cc_result[0]/scale_cc; dy = roi1.getBounds().y + cc_result[1]/scale_cc; break; case LEFT_RIGHT: // boundary checks: //if (cc_result[0]/scale_cc > default_dx) success = ERROR; dx = roi1.getBounds().x + cc_result[0]/scale_cc; dy = cc_result[1]/scale_cc; break; } Utils.log2("CC R: " + cc_result[2] + " dx, dy: " + cc_result[0] + ", " + cc_result[1]); //Utils.log2("\trois: \t" + roi1 + "\n\t\t" + roi2); return new double[]{dx, dy, success, cc_result[2]}; } // else both failed: return default values Utils.log2("Using default"); return new double[]{default_dx, default_dy, ERROR, 0}; /// ABOVE: boundary checks don't work if default_dx,dy are zero! And may actually be harmful in anycase } /** For Patch class only at the moment; if the given Displayable is not a Patch this function return null. */ static public Bureaucrat snap(final Displayable d, Display display) { if (!(d instanceof Patch)) return null; return snap(d, null, display); } /** Works only for Patch instances at the moment. * Will snap against the best matching Patch in ArrayList al. * If the given list of patches to match against is null, it will look for intersecting patches * within the same layer. * Any Patch objects linked to the given Patch 'd' will be removed from the list. * The Display can be null; if not, the selection will be updated. */ static public Bureaucrat snap(final Displayable d, final ArrayList<Patch> al_, final Display display) { final Worker worker = new Worker("Snapping") { public void run() { startedWorking(); try { Utils.log2("snapping..."); // snap patches only if (null == d || !(d instanceof Patch)) { finishedWorking(); return; } //Utils.log("Snapping " + d); Collection al = al_; if (null == al) { al = d.getLayer().getIntersecting(d, Patch.class); if (null == al || 0 == al.size()) { finishedWorking(); return; } // remove from the intersecting group those Patch objects that are linked in the same layer (those linked that do not intersect simply return false on the al.remove(..) ) HashSet hs_linked = d.getLinkedGroup(new HashSet()); //Utils.log2("linked patches: " + hs_linked.size()); Layer layer = d.getLayer(); for (Iterator it = hs_linked.iterator(); it.hasNext(); ) { Displayable dob = (Displayable)it.next(); if (Patch.class == dob.getClass() && dob.getLayer() == layer) { al.remove(dob); } } } // dragged Patch final Patch p_dragged = (Patch)d; // make a reasonable guess for the scale float cc_scale = (float)(512.0 / (p_dragged.getWidth() > p_dragged.getHeight() ? p_dragged.getWidth() : p_dragged.getHeight())); cc_scale = ((float)((int)(cc_scale * 10000))) / 10000; // rounding if (cc_scale > 1.0f) cc_scale = 1.0f; // With Phase-correlation (thus limited to non-rotated Patch instances) // start: double[] best_pc = null; Patch best = null; final float min_R = d.getProject().getProperty("min_R", DEFAULT_MIN_R); try { // for (Iterator it = al.iterator(); it.hasNext(); ) { Patch base = (Patch)it.next(); final double[] pc = StitchingTEM.correlate(base, p_dragged, 1f, cc_scale, StitchingTEM.TOP_BOTTOM, 0, 0, min_R); if (null == best_pc) { best_pc = pc; best = base; } else { // compare R: choose largest if (pc[3] > best_pc[3]) { best_pc = pc; best = base; } } } } catch (Exception e) { IJError.print(e); finishedWorking(); return; } // now, relocate the Patch double x2 = best.getX() + best_pc[0]; double y2 = best.getY() + best_pc[1]; Rectangle box = p_dragged.getLinkedBox(true); //Utils.log2("box is " + box); //p_dragged.setLocation(x2, y2); // wrong, does not consider linked objects double dx = x2 - p_dragged.getX(); double dy = y2 - p_dragged.getY(); p_dragged.translate(dx, dy, true); // translates entire linked group // With SIFT (free) fix rotation if (! best.getAffineTransform().isIdentity() && best.getAffineTransform().getType() != AffineTransform.TYPE_TRANSLATION) { Registration.SIFTParameters sp = new Registration.SIFTParameters(p_dragged.getProject()); sp.scale = cc_scale; Object[] result = Registration.registerWithSIFTLandmarks(best, p_dragged, sp, null); if (null != result) { AffineTransform at_result = (AffineTransform)result[2]; // subtract the transform of the dragged patch to all in the linked group p_dragged.transform(p_dragged.getAffineTransformCopy().createInverse()); // apply the new trasform to all in the linked group at_result.preConcatenate(best.getAffineTransformCopy()); p_dragged.transform(at_result); } } // repaint: Rectangle r = p_dragged.getLinkedBox(true); //Utils.log2("dragged box is " + r); box.add(r); if (null != display) { Selection selection = display.getSelection(); if (selection.contains(p_dragged)) { //Utils.log2("going to update selection"); Display.updateSelection(display); } } Display.repaint(p_dragged.getLayer().getParent()/*, box*/); Utils.log2("Done snapping."); } catch (Exception e) { IJError.print(e); } finishedWorking(); } }; Bureaucrat burro = new Bureaucrat(worker, d.getProject()); burro.goHaveBreakfast(); return burro; } /** Transforms the given point @param po by the AffineTransform of the given @param patch .*/ static private mpi.fruitfly.registration.Point transform(final Patch patch, final mpi.fruitfly.registration.Point po) { float[] local = po.getL(); Point2D.Double pd = patch.transformPoint(local[0], local[1]); return new mpi.fruitfly.registration.Point(new float[]{(float)pd.x, (float)pd.y}); } static private mpi.fruitfly.registration.Point inverseTransform(final Patch patch, final mpi.fruitfly.registration.Point po) { float[] l = po.getL(); Point2D.Double pd = patch.inverseTransformPoint(l[0], l[1]); return new mpi.fruitfly.registration.Point(new float[]{(float)pd.x, (float)pd.y}); } /** Figure out from which direction is the dragged object approaching the object being overlapped. 0=left, 1=top, 2=right, 3=bottom. This method by Stephan Nufer. */ /* private int getClosestOverlapLocation(Patch dragging_ob, Patch overlapping_ob) { Rectangle x_rect = dragging_ob.getBoundingBox(); Rectangle y_rect = overlapping_ob.getBoundingBox(); Rectangle overlap = x_rect.intersection(y_rect); if (overlap.width / (double)overlap.height > 1) { // horizontal stitch if (y_rect.y < x_rect.y) return 3; else return 1; } else { // vertical stitch if (y_rect.x < x_rect.x) return 2; else return 0; } } */ }
false
true
static private Bureaucrat stitchTopLeft(final Patch[] patch, final int grid_width, final float percent_overlap, final float scale, final double default_bottom_top_overlap, final double default_left_right_overlap, final boolean optimize) { final Worker worker = new Worker("Stitching") { public void run() { try { final int LEFT = 0, TOP = 1; int prev_i = 0; int prev = LEFT; double[] R1=null, R2=null; // for scoring phase- and cross-correlation final float min_R = patch[0].getProject().getProperty("min_R", DEFAULT_MIN_R); // for minimization: ArrayList<Tile> al_tiles = new ArrayList<Tile>(); // first patch-tile: TModel2D first_tile_model = new TModel2D(); first_tile_model.getAffine().setTransform( patch[ 0 ].getAffineTransform() ); al_tiles.add(new Tile((float)patch[0].getWidth(), (float)patch[0].getHeight(), first_tile_model )); for (int i=1; i<patch.length; i++) { if (hasQuitted()) { return; } // boundary checks: don't allow displacements beyond these values final double default_dx = default_left_right_overlap; final double default_dy = default_bottom_top_overlap; // for minimization: Tile tile_left = null; Tile tile_top = null; TModel2D tile_model = new TModel2D(); tile_model.getAffine().setTransform( patch[ i ].getAffineTransform() ); Tile tile = new Tile((float)patch[i].getWidth(), (float)patch[i].getHeight(), tile_model ); al_tiles.add(tile); // stitch with the one above if starting row if (0 == i % grid_width) { prev_i = i - grid_width; prev = TOP; } else { prev_i = i -1; prev = LEFT; } if (TOP == prev) { // compare with top only R1 = correlate(patch[prev_i], patch[i], percent_overlap, scale, TOP_BOTTOM, default_dx, default_dy, min_R); R2 = null; tile_top = al_tiles.get(i - grid_width); } else { // the one on the left R2 = correlate(patch[prev_i], patch[i], percent_overlap, scale, LEFT_RIGHT, default_dx, default_dy, min_R); tile_left = al_tiles.get(i - 1); // the one above if (i - grid_width > -1) { R1 = correlate(patch[i - grid_width], patch[i], percent_overlap, scale, TOP_BOTTOM, default_dx, default_dy, min_R); tile_top = al_tiles.get(i - grid_width); } else { R1 = null; } } // boundary limits: don't move by more than the small dimension of the stripe int max_abs_delta; // TODO: only the dx for left (and the dy for top) should be compared and found to be smaller or equal; the other dimension should be unbounded -for example, for manually acquired, grossly out-of-grid tiles. final Rectangle box = new Rectangle(); final Rectangle box2 = new Rectangle(); // check and apply: falls back to default overlaps when getting bad results if (TOP == prev) { if (SUCCESS == R1[2]) { // trust top if (optimize) addMatches(tile_top, tile, R1[0], R1[1]); else { patch[i - grid_width].getBoundingBox(box); patch[i].setLocation(box.x + R1[0], box.y + R1[1]); } } else { final Rectangle b2 = patch[i - grid_width].getBoundingBox(null); // don't move: use default overlap if (optimize) addMatches(tile_top, tile, 0, b2.height - default_bottom_top_overlap); else { patch[i - grid_width].getBoundingBox(box); patch[i].setLocation(box.x, box.y + b2.height - default_bottom_top_overlap); } } } else { // LEFT // the one on top, if any if (i - grid_width > -1) { if (SUCCESS == R1[2]) { // top is good if (SUCCESS == R2[2]) { // combine left and top if (optimize) { addMatches(tile_left, tile, R2[0], R2[1]); addMatches(tile_top, tile, R1[0], R1[1]); } else { patch[i-1].getBoundingBox(box); patch[i - grid_width].getBoundingBox(box2); patch[i].setLocation((box.x + R1[0] + box2.x + R2[0]) / 2, (box.y + R1[1] + box2.y + R2[1]) / 2); } } else { // use top alone if (optimize) addMatches(tile_top, tile, R1[0], R1[1]); else { patch[i - grid_width].getBoundingBox(box); patch[i].setLocation(box.x + R1[0], box.y + R1[1]); } } } else { // ignore top if (SUCCESS == R2[2]) { // use left alone if (optimize) addMatches(tile_left, tile, R2[0], R2[1]); else { patch[i-1].getBoundingBox(box); patch[i].setLocation(box.x + R2[0], box.y + R2[1]); } } else { patch[prev_i].getBoundingBox(box); patch[i - grid_width].getBoundingBox(box2); // left not trusted, top not trusted: use a combination of defaults for both if (optimize) { addMatches(tile_left, tile, box.width - default_left_right_overlap, 0); addMatches(tile_top, tile, 0, box2.height - default_bottom_top_overlap); } else { patch[i].setLocation(box.x + box.width - default_left_right_overlap, box2.y + box2.height - default_bottom_top_overlap); } } } } else if (SUCCESS == R2[2]) { // use left alone (top not applicable in top row) if (optimize) addMatches(tile_left, tile, R2[0], R2[1]); else { patch[i-1].getBoundingBox(box); patch[i].setLocation(box.x + R2[0], box.y + R2[1]); } } else { patch[prev_i].getBoundingBox(box); // left not trusted, and top not applicable: use default overlap with left tile if (optimize) addMatches(tile_left, tile, box.width - default_left_right_overlap, 0); else { patch[i].setLocation(box.x + box.width - default_left_right_overlap, box.y); } } } if (!optimize) Display.repaint(patch[i].getLayer(), patch[i], null, 0, false); Utils.log2(i + ": Done patch " + patch[i]); } if (optimize) { // run optimization ArrayList<Patch> al_patches = new ArrayList<Patch>(); for (int i=0; i<patch.length; i++) al_patches.add(patch[i]); ArrayList<Tile> al_fixed_tiles = new ArrayList<Tile>(); al_fixed_tiles.add(al_tiles.get(0)); // ready for montage-wise minimization Optimize.minimizeAll(al_tiles, al_patches, al_fixed_tiles, 50); } Display.repaint(patch[0].getLayer(), null, 0, true); // all // } catch (Exception e) { IJError.print(e); } } }; Bureaucrat burro = new Bureaucrat(worker, patch[0].getProject()); burro.goHaveBreakfast(); return burro; }
static private Bureaucrat stitchTopLeft(final Patch[] patch, final int grid_width, final float percent_overlap, final float scale, final double default_bottom_top_overlap, final double default_left_right_overlap, final boolean optimize) { final Worker worker = new Worker("Stitching") { public void run() { startedWorking(); try { final int LEFT = 0, TOP = 1; int prev_i = 0; int prev = LEFT; double[] R1=null, R2=null; // for scoring phase- and cross-correlation final float min_R = patch[0].getProject().getProperty("min_R", DEFAULT_MIN_R); // for minimization: ArrayList<Tile> al_tiles = new ArrayList<Tile>(); // first patch-tile: TModel2D first_tile_model = new TModel2D(); first_tile_model.getAffine().setTransform( patch[ 0 ].getAffineTransform() ); al_tiles.add(new Tile((float)patch[0].getWidth(), (float)patch[0].getHeight(), first_tile_model )); for (int i=1; i<patch.length; i++) { if (hasQuitted()) { return; } // boundary checks: don't allow displacements beyond these values final double default_dx = default_left_right_overlap; final double default_dy = default_bottom_top_overlap; // for minimization: Tile tile_left = null; Tile tile_top = null; TModel2D tile_model = new TModel2D(); tile_model.getAffine().setTransform( patch[ i ].getAffineTransform() ); Tile tile = new Tile((float)patch[i].getWidth(), (float)patch[i].getHeight(), tile_model ); al_tiles.add(tile); // stitch with the one above if starting row if (0 == i % grid_width) { prev_i = i - grid_width; prev = TOP; } else { prev_i = i -1; prev = LEFT; } if (TOP == prev) { // compare with top only R1 = correlate(patch[prev_i], patch[i], percent_overlap, scale, TOP_BOTTOM, default_dx, default_dy, min_R); R2 = null; tile_top = al_tiles.get(i - grid_width); } else { // the one on the left R2 = correlate(patch[prev_i], patch[i], percent_overlap, scale, LEFT_RIGHT, default_dx, default_dy, min_R); tile_left = al_tiles.get(i - 1); // the one above if (i - grid_width > -1) { R1 = correlate(patch[i - grid_width], patch[i], percent_overlap, scale, TOP_BOTTOM, default_dx, default_dy, min_R); tile_top = al_tiles.get(i - grid_width); } else { R1 = null; } } // boundary limits: don't move by more than the small dimension of the stripe int max_abs_delta; // TODO: only the dx for left (and the dy for top) should be compared and found to be smaller or equal; the other dimension should be unbounded -for example, for manually acquired, grossly out-of-grid tiles. final Rectangle box = new Rectangle(); final Rectangle box2 = new Rectangle(); // check and apply: falls back to default overlaps when getting bad results if (TOP == prev) { if (SUCCESS == R1[2]) { // trust top if (optimize) addMatches(tile_top, tile, R1[0], R1[1]); else { patch[i - grid_width].getBoundingBox(box); patch[i].setLocation(box.x + R1[0], box.y + R1[1]); } } else { final Rectangle b2 = patch[i - grid_width].getBoundingBox(null); // don't move: use default overlap if (optimize) addMatches(tile_top, tile, 0, b2.height - default_bottom_top_overlap); else { patch[i - grid_width].getBoundingBox(box); patch[i].setLocation(box.x, box.y + b2.height - default_bottom_top_overlap); } } } else { // LEFT // the one on top, if any if (i - grid_width > -1) { if (SUCCESS == R1[2]) { // top is good if (SUCCESS == R2[2]) { // combine left and top if (optimize) { addMatches(tile_left, tile, R2[0], R2[1]); addMatches(tile_top, tile, R1[0], R1[1]); } else { patch[i-1].getBoundingBox(box); patch[i - grid_width].getBoundingBox(box2); patch[i].setLocation((box.x + R1[0] + box2.x + R2[0]) / 2, (box.y + R1[1] + box2.y + R2[1]) / 2); } } else { // use top alone if (optimize) addMatches(tile_top, tile, R1[0], R1[1]); else { patch[i - grid_width].getBoundingBox(box); patch[i].setLocation(box.x + R1[0], box.y + R1[1]); } } } else { // ignore top if (SUCCESS == R2[2]) { // use left alone if (optimize) addMatches(tile_left, tile, R2[0], R2[1]); else { patch[i-1].getBoundingBox(box); patch[i].setLocation(box.x + R2[0], box.y + R2[1]); } } else { patch[prev_i].getBoundingBox(box); patch[i - grid_width].getBoundingBox(box2); // left not trusted, top not trusted: use a combination of defaults for both if (optimize) { addMatches(tile_left, tile, box.width - default_left_right_overlap, 0); addMatches(tile_top, tile, 0, box2.height - default_bottom_top_overlap); } else { patch[i].setLocation(box.x + box.width - default_left_right_overlap, box2.y + box2.height - default_bottom_top_overlap); } } } } else if (SUCCESS == R2[2]) { // use left alone (top not applicable in top row) if (optimize) addMatches(tile_left, tile, R2[0], R2[1]); else { patch[i-1].getBoundingBox(box); patch[i].setLocation(box.x + R2[0], box.y + R2[1]); } } else { patch[prev_i].getBoundingBox(box); // left not trusted, and top not applicable: use default overlap with left tile if (optimize) addMatches(tile_left, tile, box.width - default_left_right_overlap, 0); else { patch[i].setLocation(box.x + box.width - default_left_right_overlap, box.y); } } } if (!optimize) Display.repaint(patch[i].getLayer(), patch[i], null, 0, false); Utils.log2(i + ": Done patch " + patch[i]); } if (optimize) { // run optimization ArrayList<Patch> al_patches = new ArrayList<Patch>(); for (int i=0; i<patch.length; i++) al_patches.add(patch[i]); ArrayList<Tile> al_fixed_tiles = new ArrayList<Tile>(); al_fixed_tiles.add(al_tiles.get(0)); // ready for montage-wise minimization Optimize.minimizeAll(al_tiles, al_patches, al_fixed_tiles, 50); } Display.repaint(patch[0].getLayer(), null, 0, true); // all // } catch (Exception e) { IJError.print(e); } finally { finishedWorking(); } } }; Bureaucrat burro = new Bureaucrat(worker, patch[0].getProject()); burro.goHaveBreakfast(); return burro; }
diff --git a/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPScopeMapper.java b/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPScopeMapper.java index 02c3d8d4a..e951dad01 100644 --- a/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPScopeMapper.java +++ b/parser/org/eclipse/cdt/internal/core/dom/parser/cpp/CPPScopeMapper.java @@ -1,308 +1,308 @@ /******************************************************************************* * Copyright (c) 2008, 2009 Wind River Systems, Inc. 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: * Markus Schorn - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.internal.core.dom.parser.cpp; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.eclipse.cdt.core.dom.IName; import org.eclipse.cdt.core.dom.ast.ASTVisitor; import org.eclipse.cdt.core.dom.ast.DOMException; import org.eclipse.cdt.core.dom.ast.EScopeKind; import org.eclipse.cdt.core.dom.ast.IASTASMDeclaration; import org.eclipse.cdt.core.dom.ast.IASTCompositeTypeSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclSpecifier; import org.eclipse.cdt.core.dom.ast.IASTDeclaration; import org.eclipse.cdt.core.dom.ast.IASTFunctionDefinition; import org.eclipse.cdt.core.dom.ast.IASTName; import org.eclipse.cdt.core.dom.ast.IASTSimpleDeclaration; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.IScope; import org.eclipse.cdt.core.dom.ast.cpp.ICPPClassType; import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespace; import org.eclipse.cdt.core.dom.ast.cpp.ICPPNamespaceScope; import org.eclipse.cdt.core.dom.ast.cpp.ICPPUsingDirective; import org.eclipse.cdt.core.index.IIndexBinding; import org.eclipse.cdt.core.index.IIndexFileSet; import org.eclipse.cdt.core.parser.util.ArrayUtil; import org.eclipse.cdt.core.parser.util.CharArrayMap; import org.eclipse.cdt.internal.core.index.IIndexScope; /** * Utility to map index-scopes to scopes from the AST. This is important for * scopes that can be reopened, i.e. namespaces. */ public class CPPScopeMapper { /** * Wrapper for namespace-scopes from the index. */ private class NamespaceScopeWrapper implements ICPPNamespaceScope { private final ICPPNamespaceScope fScope; private ArrayList<ICPPUsingDirective> fUsingDirectives; public NamespaceScopeWrapper(ICPPNamespaceScope scope) { fScope= scope; } public EScopeKind getKind() { return fScope.getKind(); } public IBinding[] find(String name) throws DOMException { return fScope.find(name); } public IBinding getBinding(IASTName name, boolean resolve) throws DOMException { return fScope.getBinding(name, resolve); } public IBinding getBinding(IASTName name, boolean resolve, IIndexFileSet acceptLocalBindings) throws DOMException { return fScope.getBinding(name, resolve, acceptLocalBindings); } public IBinding[] getBindings(IASTName name, boolean resolve, boolean prefixLookup) throws DOMException { return fScope.getBindings(name, resolve, prefixLookup); } public IBinding[] getBindings(IASTName name, boolean resolve, boolean prefixLookup, IIndexFileSet acceptLocalBindings) throws DOMException { return fScope.getBindings(name, resolve, prefixLookup, acceptLocalBindings); } public IScope getParent() throws DOMException { IScope parent= fScope.getParent(); if (parent instanceof IIndexScope) { return mapToASTScope((IIndexScope) parent); } return fTu.getScope(); } public IName getScopeName() throws DOMException { return fScope.getScopeName(); } public void addUsingDirective(ICPPUsingDirective usingDirective) throws DOMException { if (fUsingDirectives == null) { fUsingDirectives= new ArrayList<ICPPUsingDirective>(1); } fUsingDirectives.add(usingDirective); } public ICPPUsingDirective[] getUsingDirectives() throws DOMException { if (fUsingDirectives == null) { return ICPPUsingDirective.EMPTY_ARRAY; } return fUsingDirectives.toArray(new ICPPUsingDirective[fUsingDirectives.size()]); } } /** * Wrapper for using directives from the index. */ private class UsingDirectiveWrapper implements ICPPUsingDirective { private final int fOffset; private final ICPPUsingDirective fDirective; public UsingDirectiveWrapper(int offset, ICPPUsingDirective ud) { fOffset= offset; fDirective= ud; } public IScope getContainingScope() { final IScope scope= fDirective.getContainingScope(); if (scope == null) { return fTu.getScope(); } return scope; } public ICPPNamespaceScope getNominatedScope() throws DOMException { return fDirective.getNominatedScope(); } public int getPointOfDeclaration() { return fOffset; } } /** * Collector for class definitions. */ private class Visitor extends ASTVisitor { Visitor() { shouldVisitDeclarations = true; } @Override public int visit(IASTDeclaration declaration) { if (declaration instanceof IASTSimpleDeclaration) { IASTDeclSpecifier declspec = ((IASTSimpleDeclaration) declaration).getDeclSpecifier(); if (declspec instanceof IASTCompositeTypeSpecifier) { IASTCompositeTypeSpecifier cts = (IASTCompositeTypeSpecifier) declspec; final IASTName name = cts.getName(); - final char[] nameChars = name.toCharArray(); + final char[] nameChars = name.getLookupKey(); if (nameChars.length > 0) { IASTName[] names= fClasses.get(nameChars); names= (IASTName[]) ArrayUtil.append(IASTName.class, names, name); fClasses.put(nameChars, names); } return PROCESS_CONTINUE; } return PROCESS_SKIP; } else if (declaration instanceof IASTASMDeclaration || declaration instanceof IASTFunctionDefinition) { return PROCESS_SKIP; } return PROCESS_CONTINUE; } } private final HashMap<IIndexScope, IScope> fMappedScopes= new HashMap<IIndexScope, IScope>(); private final HashMap<String, NamespaceScopeWrapper> fNamespaceWrappers= new HashMap<String, NamespaceScopeWrapper>(); private final Map<String, List<UsingDirectiveWrapper>> fPerName= new HashMap<String, List<UsingDirectiveWrapper>>(); private final CPPASTTranslationUnit fTu; protected CharArrayMap<IASTName[]> fClasses; public CPPScopeMapper(CPPASTTranslationUnit tu) { fTu= tu; } /** * Register an additional list of using directives to be considered. * @param offset the global offset at which the using directives are provided * @param usingDirectives the list of additional directives. */ public void registerAdditionalDirectives(int offset, List<ICPPUsingDirective> usingDirectives) { if (!usingDirectives.isEmpty()) { for (ICPPUsingDirective ud : usingDirectives) { IScope container= ud.getContainingScope(); try { final String name= getReverseQualifiedName(container); List<UsingDirectiveWrapper> list= fPerName.get(name); if (list == null) { list= new LinkedList<UsingDirectiveWrapper>(); fPerName.put(name, list); } list.add(new UsingDirectiveWrapper(offset, ud)); } catch (DOMException e) { } } } } /** * Adds additional directives previously registered to the given scope. */ public void handleAdditionalDirectives(ICPPNamespaceScope scope) { assert !(scope instanceof IIndexScope); if (fPerName.isEmpty()) { return; } try { String qname = getReverseQualifiedName(scope); List<UsingDirectiveWrapper> candidates= fPerName.remove(qname); if (candidates != null) { for (UsingDirectiveWrapper ud : candidates) { scope.addUsingDirective(ud); } } } catch (DOMException e) { } } private String getReverseQualifiedName(IScope scope) throws DOMException { final CPPNamespaceScope tuscope = fTu.getScope(); if (scope == tuscope || scope == null) { return ""; //$NON-NLS-1$ } StringBuilder buf= new StringBuilder(); IName scopeName = scope.getScopeName(); if (scopeName != null) { buf.append(scopeName.getSimpleID()); } scope= scope.getParent(); while (scope != null && scope != tuscope) { buf.append(':'); scopeName= scope.getScopeName(); if (scopeName != null) { buf.append(scope.getScopeName().getSimpleID()); } scope= scope.getParent(); } return buf.toString(); } /** * Maps namespace scopes from the index back into the AST. */ public IScope mapToASTScope(IIndexScope scope) { if (scope == null) { return fTu.getScope(); } if (scope instanceof ICPPNamespaceScope) { IScope result= fMappedScopes.get(scope); if (result == null) { result= fTu.getScope().findNamespaceScope(scope); if (result == null) { result= wrapNamespaceScope((ICPPNamespaceScope) scope); } fMappedScopes.put(scope, result); } return result; } return scope; } private IScope wrapNamespaceScope(ICPPNamespaceScope scope) { try { String rqname= getReverseQualifiedName(scope); NamespaceScopeWrapper result= fNamespaceWrappers.get(rqname); if (result == null) { result= new NamespaceScopeWrapper(getCompositeNamespaceScope(scope)); fNamespaceWrappers.put(rqname, result); } return result; } catch (DOMException e) { assert false; // index scopes don't throw dom-exceptions return null; } } private ICPPNamespaceScope getCompositeNamespaceScope(ICPPNamespaceScope scope) throws DOMException { if (scope instanceof IIndexScope) { IIndexBinding binding= fTu.getIndex().adaptBinding(((IIndexScope) scope).getScopeBinding()); if (binding instanceof ICPPNamespace) { scope= ((ICPPNamespace) binding).getNamespaceScope(); } } return scope; } public ICPPClassType mapToAST(ICPPClassType type) { if (fClasses == null) { fClasses= new CharArrayMap<IASTName[]>(); fTu.accept(new Visitor()); } IASTName[] names= fClasses.get(type.getNameCharArray()); if (names != null) { for (IASTName name : names) { if (name == null) break; IBinding b= name.resolveBinding(); if (b instanceof ICPPClassType) { final ICPPClassType mapped = (ICPPClassType) b; if (mapped.isSameType(type)) { return mapped; } } } } return type; } }
true
true
public int visit(IASTDeclaration declaration) { if (declaration instanceof IASTSimpleDeclaration) { IASTDeclSpecifier declspec = ((IASTSimpleDeclaration) declaration).getDeclSpecifier(); if (declspec instanceof IASTCompositeTypeSpecifier) { IASTCompositeTypeSpecifier cts = (IASTCompositeTypeSpecifier) declspec; final IASTName name = cts.getName(); final char[] nameChars = name.toCharArray(); if (nameChars.length > 0) { IASTName[] names= fClasses.get(nameChars); names= (IASTName[]) ArrayUtil.append(IASTName.class, names, name); fClasses.put(nameChars, names); } return PROCESS_CONTINUE; } return PROCESS_SKIP; } else if (declaration instanceof IASTASMDeclaration || declaration instanceof IASTFunctionDefinition) { return PROCESS_SKIP; } return PROCESS_CONTINUE; }
public int visit(IASTDeclaration declaration) { if (declaration instanceof IASTSimpleDeclaration) { IASTDeclSpecifier declspec = ((IASTSimpleDeclaration) declaration).getDeclSpecifier(); if (declspec instanceof IASTCompositeTypeSpecifier) { IASTCompositeTypeSpecifier cts = (IASTCompositeTypeSpecifier) declspec; final IASTName name = cts.getName(); final char[] nameChars = name.getLookupKey(); if (nameChars.length > 0) { IASTName[] names= fClasses.get(nameChars); names= (IASTName[]) ArrayUtil.append(IASTName.class, names, name); fClasses.put(nameChars, names); } return PROCESS_CONTINUE; } return PROCESS_SKIP; } else if (declaration instanceof IASTASMDeclaration || declaration instanceof IASTFunctionDefinition) { return PROCESS_SKIP; } return PROCESS_CONTINUE; }
diff --git a/OpenPGP-Keychain/src/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java b/OpenPGP-Keychain/src/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java index ea76d2898..a02bfd678 100644 --- a/OpenPGP-Keychain/src/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java +++ b/OpenPGP-Keychain/src/org/sufficientlysecure/keychain/ui/ImportKeysFileFragment.java @@ -1,124 +1,124 @@ /* * Copyright (C) 2013 Dominik Schürmann <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.sufficientlysecure.keychain.ui; import org.sufficientlysecure.keychain.Constants; import org.sufficientlysecure.keychain.Id; import org.sufficientlysecure.keychain.R; import org.sufficientlysecure.keychain.helper.FileHelper; import org.sufficientlysecure.keychain.util.Log; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import com.beardedhen.androidbootstrap.BootstrapButton; public class ImportKeysFileFragment extends Fragment { public static final String ARG_PATH = "path"; private ImportKeysActivity mImportActivity; private EditText mFilename; private BootstrapButton mBrowse; /** * Creates new instance of this fragment */ public static ImportKeysFileFragment newInstance(String path) { ImportKeysFileFragment frag = new ImportKeysFileFragment(); Bundle args = new Bundle(); args.putString(ARG_PATH, path); frag.setArguments(args); return frag; } /** * Inflate the layout for this fragment */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.import_keys_file_fragment, container, false); mFilename = (EditText) view.findViewById(R.id.import_keys_file_input); mBrowse = (BootstrapButton) view.findViewById(R.id.import_keys_file_browse); mBrowse.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // open .asc or .gpg files // setting it to text/plain prevents Cynaogenmod's file manager from selecting asc // or gpg types! FileHelper.openFile(ImportKeysFileFragment.this, mFilename.getText().toString(), "*/*", Id.request.filename); } }); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mImportActivity = (ImportKeysActivity) getActivity(); // set default path String path = Constants.path.APP_DIR + "/"; if (getArguments() != null && getArguments().containsKey(ARG_PATH)) { path = getArguments().getString(ARG_PATH); } mFilename.setText(path); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { - switch (requestCode) { + switch (requestCode & 0xFFFF) { case Id.request.filename: { if (resultCode == Activity.RESULT_OK && data != null) { String path = null; try { path = data.getData().getPath(); Log.d(Constants.TAG, "path=" + path); // set filename to edittext mFilename.setText(path); } catch (NullPointerException e) { Log.e(Constants.TAG, "Nullpointer while retrieving path!", e); } // load data mImportActivity.loadCallback(null, path); } break; } default: super.onActivityResult(requestCode, resultCode, data); break; } } }
true
true
public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case Id.request.filename: { if (resultCode == Activity.RESULT_OK && data != null) { String path = null; try { path = data.getData().getPath(); Log.d(Constants.TAG, "path=" + path); // set filename to edittext mFilename.setText(path); } catch (NullPointerException e) { Log.e(Constants.TAG, "Nullpointer while retrieving path!", e); } // load data mImportActivity.loadCallback(null, path); } break; } default: super.onActivityResult(requestCode, resultCode, data); break; } }
public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode & 0xFFFF) { case Id.request.filename: { if (resultCode == Activity.RESULT_OK && data != null) { String path = null; try { path = data.getData().getPath(); Log.d(Constants.TAG, "path=" + path); // set filename to edittext mFilename.setText(path); } catch (NullPointerException e) { Log.e(Constants.TAG, "Nullpointer while retrieving path!", e); } // load data mImportActivity.loadCallback(null, path); } break; } default: super.onActivityResult(requestCode, resultCode, data); break; } }
diff --git a/src/main/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java b/src/main/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java index d25b719..489ef6c 100644 --- a/src/main/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java +++ b/src/main/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java @@ -1,327 +1,330 @@ /* * JBoss, Home of Professional Open Source * Copyright 2011, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.jmx.adaptor.snmp.agent; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import javax.management.MBeanServer; import javax.management.ObjectName; import org.jboss.jmx.adaptor.snmp.config.attribute.ManagedBean; import org.jboss.jmx.adaptor.snmp.config.attribute.MappedAttribute; import org.jboss.logging.Logger; import org.snmp4j.smi.OID; import org.snmp4j.smi.OctetString; import org.snmp4j.smi.Variable; /** * @author [email protected] * */ public class AttributeTableMapper { private SortedSet<OID> tables = new TreeSet<OID>(); private SortedSet<OID> tableRowEntrys = new TreeSet<OID>(); /** * keep an index of the OID from attributes.xml */ private SortedMap<OID, BindEntry> tableMappings = new TreeMap<OID, BindEntry>(); private SortedMap<OID, BindEntry> tableRowEntryMappings = new TreeMap<OID, BindEntry>(); private MBeanServer server; private Logger log; public AttributeTableMapper(MBeanServer server, Logger log) { this.server = server; this.log = log; } /** * * @param oid * @return */ public BindEntry getTableBinding(OID oid, boolean isRowEntry) { Set<Entry<OID,BindEntry>> entries = null; if(isRowEntry) { entries = tableRowEntryMappings.entrySet(); } else { entries = tableMappings.entrySet(); } for (Entry<OID,BindEntry> entry : entries) { if (oid.startsWith(entry.getKey())) { BindEntry value = entry.getValue(); BindEntry bindEntry = (BindEntry) value.clone(); int[] oidValue = oid.getValue(); int[] subOid = new int[oid.size() - entry.getKey().size()]; System.arraycopy(oidValue, entry.getKey().size(), subOid, 0, oid.size() - entry.getKey().size()); if(subOid.length > 0) { bindEntry.setTableIndexOID(new OID(subOid)); } return bindEntry; } } return null; } public OID getNextTable(OID oid) { OID currentOID = oid; // means that the oid is the one from the table itself boolean isRowEntry = false; if(tables.contains(oid)) { currentOID = oid.append(1); } if(tableRowEntrys.contains(currentOID)) { currentOID = oid.append(1); isRowEntry = true; } BindEntry be = getTableBinding(currentOID, isRowEntry); if(be == null) { be = getTableBinding(currentOID, true); isRowEntry = true; } + if(be == null) { + return null; // it's not there + } Object val = null; try { val = server.getAttribute(be.getMbean(), be.getAttr().getName()); } catch(Exception e) { log.error("Impossible to fetch " + be.getAttr().getName()); return null; } OID tableIndexOID = be.getTableIndexOID(); if(tableIndexOID == null) { return new OID(currentOID).append(1); } if(val instanceof List) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((List)val).size()) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if(val instanceof Map) { if(tableIndexOID.size() <= 1) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((Map)val).size()) { return new OID(currentOID.trim().append(index)); } else { Set<Object> keySet = ((Map)val).keySet(); if(keySet.size() > 0) { return new OID(currentOID.trim().trim().append(2).append("'" + keySet.iterator().next().toString() + "'")); } else { return null; } } } else { String key = new String(tableIndexOID.toByteArray()); Iterator<Object> keySet = ((Map)val).keySet().iterator(); while (keySet.hasNext()) { Object entryKey = keySet.next(); if(entryKey.equals(key)) { if(keySet.hasNext()) { Object nextKey = keySet.next(); OID nextOID = new OID(currentOID); nextOID.trim(tableIndexOID.size()); nextOID.append("'" + nextKey + "'"); return nextOID; } else { return null; } } } return null; } } if (val instanceof int[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((int[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if (val instanceof long[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((long[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if (val instanceof boolean[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((boolean[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if (val instanceof Object[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((Object[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } return null; } /** * * @param mmb * @param oname */ public void addTableMapping(ManagedBean mmb, MappedAttribute ma) { String oid; String oidPrefix = mmb.getOidPrefix(); if (oidPrefix != null) { oid = oidPrefix + ma.getOid(); } else { oid = ma.getOid(); } OID coid = new OID(oid); BindEntry be = new BindEntry(coid, mmb.getName(), ma.getName()); be.setReadWrite(ma.isReadWrite()); be.setTable(ma.isAttributeTable()); if (log.isTraceEnabled()) log.trace("New bind entry " + be); if (tables.contains(coid)) { log.info("Duplicate oid " + coid + RequestHandlerImpl.SKIP_ENTRY); } if (mmb == null || mmb.equals("")) { log.info("Invalid mbean name for oid " + coid + RequestHandlerImpl.SKIP_ENTRY); } if (ma == null || ma.equals("")) { log.info("Invalid attribute name " + ma + " for oid " + coid + RequestHandlerImpl.SKIP_ENTRY); } tableRowEntrys.add(coid); tables.add(coid.trim()); tableRowEntryMappings.put(new OID(coid).append(1), be); tableMappings.put(new OID(coid).append(2), be); } public boolean belongsToTables(OID oid) { for (OID attributeOID : tables) { if (oid.startsWith(attributeOID)) { return true; } } return false; } public void removeTableMapping(ManagedBean mmb, ObjectName oname) { } public Variable getIndexValue(OID oid) { BindEntry be = getTableBinding(oid, true); Object val = null; try { val = server.getAttribute(be.getMbean(), be.getAttr().getName()); } catch(Exception e) { log.error("Impossible to fetch " + be.getAttr().getName()); return null; } OID tableIndexOID = be.getTableIndexOID(); if(val instanceof List) { return new OctetString("" + oid.get(oid.size()-1)); } if(val instanceof Map) { int index = oid.get(oid.size()-1); int i = 1; for(Object key : ((Map) val).keySet()) { if(i == index) { return new OctetString((String)key); } i++; } } if (val instanceof int[]) { return new OctetString("" + oid.get(oid.size()-1)); } if (val instanceof long[]) { return new OctetString("" + oid.get(oid.size()-1)); } if (val instanceof boolean[]) { return new OctetString("" + oid.get(oid.size()-1)); } if (val instanceof Object[]) { return new OctetString("" + oid.get(oid.size()-1)); } return null; } }
true
true
public OID getNextTable(OID oid) { OID currentOID = oid; // means that the oid is the one from the table itself boolean isRowEntry = false; if(tables.contains(oid)) { currentOID = oid.append(1); } if(tableRowEntrys.contains(currentOID)) { currentOID = oid.append(1); isRowEntry = true; } BindEntry be = getTableBinding(currentOID, isRowEntry); if(be == null) { be = getTableBinding(currentOID, true); isRowEntry = true; } Object val = null; try { val = server.getAttribute(be.getMbean(), be.getAttr().getName()); } catch(Exception e) { log.error("Impossible to fetch " + be.getAttr().getName()); return null; } OID tableIndexOID = be.getTableIndexOID(); if(tableIndexOID == null) { return new OID(currentOID).append(1); } if(val instanceof List) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((List)val).size()) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if(val instanceof Map) { if(tableIndexOID.size() <= 1) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((Map)val).size()) { return new OID(currentOID.trim().append(index)); } else { Set<Object> keySet = ((Map)val).keySet(); if(keySet.size() > 0) { return new OID(currentOID.trim().trim().append(2).append("'" + keySet.iterator().next().toString() + "'")); } else { return null; } } } else { String key = new String(tableIndexOID.toByteArray()); Iterator<Object> keySet = ((Map)val).keySet().iterator(); while (keySet.hasNext()) { Object entryKey = keySet.next(); if(entryKey.equals(key)) { if(keySet.hasNext()) { Object nextKey = keySet.next(); OID nextOID = new OID(currentOID); nextOID.trim(tableIndexOID.size()); nextOID.append("'" + nextKey + "'"); return nextOID; } else { return null; } } } return null; } } if (val instanceof int[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((int[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if (val instanceof long[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((long[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if (val instanceof boolean[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((boolean[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if (val instanceof Object[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((Object[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } return null; }
public OID getNextTable(OID oid) { OID currentOID = oid; // means that the oid is the one from the table itself boolean isRowEntry = false; if(tables.contains(oid)) { currentOID = oid.append(1); } if(tableRowEntrys.contains(currentOID)) { currentOID = oid.append(1); isRowEntry = true; } BindEntry be = getTableBinding(currentOID, isRowEntry); if(be == null) { be = getTableBinding(currentOID, true); isRowEntry = true; } if(be == null) { return null; // it's not there } Object val = null; try { val = server.getAttribute(be.getMbean(), be.getAttr().getName()); } catch(Exception e) { log.error("Impossible to fetch " + be.getAttr().getName()); return null; } OID tableIndexOID = be.getTableIndexOID(); if(tableIndexOID == null) { return new OID(currentOID).append(1); } if(val instanceof List) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((List)val).size()) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if(val instanceof Map) { if(tableIndexOID.size() <= 1) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((Map)val).size()) { return new OID(currentOID.trim().append(index)); } else { Set<Object> keySet = ((Map)val).keySet(); if(keySet.size() > 0) { return new OID(currentOID.trim().trim().append(2).append("'" + keySet.iterator().next().toString() + "'")); } else { return null; } } } else { String key = new String(tableIndexOID.toByteArray()); Iterator<Object> keySet = ((Map)val).keySet().iterator(); while (keySet.hasNext()) { Object entryKey = keySet.next(); if(entryKey.equals(key)) { if(keySet.hasNext()) { Object nextKey = keySet.next(); OID nextOID = new OID(currentOID); nextOID.trim(tableIndexOID.size()); nextOID.append("'" + nextKey + "'"); return nextOID; } else { return null; } } } return null; } } if (val instanceof int[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((int[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if (val instanceof long[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((long[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if (val instanceof boolean[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((boolean[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } if (val instanceof Object[]) { int index = Integer.valueOf(tableIndexOID.toString()); if(index - 1 < 0) { return null; } index++; if(index <= ((Object[])val).length) { return new OID(currentOID.trim().append(index)); } else { if(isRowEntry) { return new OID(currentOID.trim().trim().append(2).append(1)); } else { return null; } } } return null; }
diff --git a/src/java/LandingPage/SubscribersCounterFilter.java b/src/java/LandingPage/SubscribersCounterFilter.java index 464a620..2f90ba9 100644 --- a/src/java/LandingPage/SubscribersCounterFilter.java +++ b/src/java/LandingPage/SubscribersCounterFilter.java @@ -1,296 +1,296 @@ package LandingPage; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.annotation.Resource; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.sql.DataSource; /** * * @author 1 */ public class SubscribersCounterFilter implements Filter { @Resource(name = "jdbc/LPDB") private DataSource jdbcLPDB = null; private static final boolean debug = false; // The filter configuration object we are associated with. If // this value is null, this filter instance is not currently // configured. private FilterConfig filterConfig = null; public SubscribersCounterFilter() { } private void doBeforeProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (debug) { log("SubscribersCounterFilter:DoBeforeProcessing"); } try { if (jdbcLPDB == null) { log("Get DataSource context"); // Obtain our environment naming context Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); // Look up our data source jdbcLPDB = (DataSource) envCtx.lookup("jdbc/LPDB"); if (jdbcLPDB == null) { log("Invalid DataSource context"); throw new ServletException("'jdbc:mysql://localhost:3306/landing_page' is in unknown DataSource"); } else { log("DataSource context -- Complete:" + jdbcLPDB.getClass().toString()); } } } catch (NamingException ne) { throw new ServletException(ne.getMessage()); } Connection conn = null; Statement stmt = null; ResultSet rs; int subscribersCount = 437; String subscribersSuffix = "человек"; try { String selectMaxIdSQL = "select max(subscribers.id) from subscribers"; conn = jdbcLPDB.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(selectMaxIdSQL); if (rs.first()) { subscribersCount = rs.getInt(1); String id = rs.getString(1); String last_symbol = id.substring(id.length() - 1); Integer last_number = Integer.valueOf(last_symbol); String prev_last_symbol = "0"; if (id.length() > 1) { prev_last_symbol = id.substring(id.length() - 2); } Integer prev_last_number = Integer.valueOf(prev_last_symbol); if ((last_number > 1 && last_number < 5) && (prev_last_number != 1)) { subscribersSuffix = "человека"; } else { subscribersSuffix = "человек"; } } } catch (Exception e) { //out.println("Login Failed! Database error! Invalid user login or password!<br/>"); throw new ServletException(e.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException sqle) { } } // try - request.setAttribute("subscribersCount", subscribersCount); + request.setAttribute("subscribersCount", subscribersCount + 100); request.setAttribute("subscribersSuffix", subscribersSuffix); } private void doAfterProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (debug) { log("SubscribersCounterFilter:DoAfterProcessing"); } // Write code here to process the request and/or response after // the rest of the filter chain is invoked. // For example, a logging filter might log the attributes on the // request object after the request has been processed. /* for (Enumeration en = request.getAttributeNames(); en.hasMoreElements(); ) { String name = (String)en.nextElement(); Object value = request.getAttribute(name); log("attribute: " + name + "=" + value.toString()); } */ // For example, a filter might append something to the response. /* PrintWriter respOut = new PrintWriter(response.getWriter()); respOut.println("<P><B>This has been appended by an intrusive filter.</B>"); */ } /** * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (debug) { log("SubscribersCounterFilter:doFilter()"); } doBeforeProcessing(request, response); Throwable problem = null; try { chain.doFilter(request, response); } catch (Throwable t) { // If an exception is thrown somewhere down the filter chain, // we still want to execute our after processing, and then // rethrow the problem after that. problem = t; t.printStackTrace(); } doAfterProcessing(request, response); // If there was a problem, we want to rethrow it if it is // a known type, otherwise log it. if (problem != null) { if (problem instanceof ServletException) { throw (ServletException) problem; } if (problem instanceof IOException) { throw (IOException) problem; } sendProcessingError(problem, response); } } /** * Return the filter configuration object for this filter. */ public FilterConfig getFilterConfig() { return (this.filterConfig); } /** * Set the filter configuration object for this filter. * * @param filterConfig The filter configuration object */ public void setFilterConfig(FilterConfig filterConfig) { this.filterConfig = filterConfig; } /** * Destroy method for this filter */ public void destroy() { } /** * Init method for this filter */ public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; if (filterConfig != null) { if (debug) { log("SubscribersCounterFilter:Initializing filter"); } } } /** * Return a String representation of this object. */ @Override public String toString() { if (filterConfig == null) { return ("SubscribersCounterFilter()"); } StringBuffer sb = new StringBuffer("SubscribersCounterFilter("); sb.append(filterConfig); sb.append(")"); return (sb.toString()); } private void sendProcessingError(Throwable t, ServletResponse response) { String stackTrace = getStackTrace(t); if (stackTrace != null && !stackTrace.equals("")) { try { response.setContentType("text/html"); PrintStream ps = new PrintStream(response.getOutputStream()); PrintWriter pw = new PrintWriter(ps); pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N // PENDING! Localize this for next official release pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n"); pw.print(stackTrace); pw.print("</pre></body>\n</html>"); //NOI18N pw.close(); ps.close(); response.getOutputStream().close(); } catch (Exception ex) { } } else { try { PrintStream ps = new PrintStream(response.getOutputStream()); t.printStackTrace(ps); ps.close(); response.getOutputStream().close(); } catch (Exception ex) { } } } public static String getStackTrace(Throwable t) { String stackTrace = null; try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.close(); sw.close(); stackTrace = sw.getBuffer().toString(); } catch (Exception ex) { } return stackTrace; } public void log(String msg) { filterConfig.getServletContext().log(msg); } }
true
true
private void doBeforeProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (debug) { log("SubscribersCounterFilter:DoBeforeProcessing"); } try { if (jdbcLPDB == null) { log("Get DataSource context"); // Obtain our environment naming context Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); // Look up our data source jdbcLPDB = (DataSource) envCtx.lookup("jdbc/LPDB"); if (jdbcLPDB == null) { log("Invalid DataSource context"); throw new ServletException("'jdbc:mysql://localhost:3306/landing_page' is in unknown DataSource"); } else { log("DataSource context -- Complete:" + jdbcLPDB.getClass().toString()); } } } catch (NamingException ne) { throw new ServletException(ne.getMessage()); } Connection conn = null; Statement stmt = null; ResultSet rs; int subscribersCount = 437; String subscribersSuffix = "человек"; try { String selectMaxIdSQL = "select max(subscribers.id) from subscribers"; conn = jdbcLPDB.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(selectMaxIdSQL); if (rs.first()) { subscribersCount = rs.getInt(1); String id = rs.getString(1); String last_symbol = id.substring(id.length() - 1); Integer last_number = Integer.valueOf(last_symbol); String prev_last_symbol = "0"; if (id.length() > 1) { prev_last_symbol = id.substring(id.length() - 2); } Integer prev_last_number = Integer.valueOf(prev_last_symbol); if ((last_number > 1 && last_number < 5) && (prev_last_number != 1)) { subscribersSuffix = "человека"; } else { subscribersSuffix = "человек"; } } } catch (Exception e) { //out.println("Login Failed! Database error! Invalid user login or password!<br/>"); throw new ServletException(e.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException sqle) { } } // try request.setAttribute("subscribersCount", subscribersCount); request.setAttribute("subscribersSuffix", subscribersSuffix); }
private void doBeforeProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (debug) { log("SubscribersCounterFilter:DoBeforeProcessing"); } try { if (jdbcLPDB == null) { log("Get DataSource context"); // Obtain our environment naming context Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); // Look up our data source jdbcLPDB = (DataSource) envCtx.lookup("jdbc/LPDB"); if (jdbcLPDB == null) { log("Invalid DataSource context"); throw new ServletException("'jdbc:mysql://localhost:3306/landing_page' is in unknown DataSource"); } else { log("DataSource context -- Complete:" + jdbcLPDB.getClass().toString()); } } } catch (NamingException ne) { throw new ServletException(ne.getMessage()); } Connection conn = null; Statement stmt = null; ResultSet rs; int subscribersCount = 437; String subscribersSuffix = "человек"; try { String selectMaxIdSQL = "select max(subscribers.id) from subscribers"; conn = jdbcLPDB.getConnection(); stmt = conn.createStatement(); rs = stmt.executeQuery(selectMaxIdSQL); if (rs.first()) { subscribersCount = rs.getInt(1); String id = rs.getString(1); String last_symbol = id.substring(id.length() - 1); Integer last_number = Integer.valueOf(last_symbol); String prev_last_symbol = "0"; if (id.length() > 1) { prev_last_symbol = id.substring(id.length() - 2); } Integer prev_last_number = Integer.valueOf(prev_last_symbol); if ((last_number > 1 && last_number < 5) && (prev_last_number != 1)) { subscribersSuffix = "человека"; } else { subscribersSuffix = "человек"; } } } catch (Exception e) { //out.println("Login Failed! Database error! Invalid user login or password!<br/>"); throw new ServletException(e.getMessage()); } finally { try { if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException sqle) { } } // try request.setAttribute("subscribersCount", subscribersCount + 100); request.setAttribute("subscribersSuffix", subscribersSuffix); }
diff --git a/MonTransit/src/org/montrealtransit/android/services/nextstop/StmMobileTask.java b/MonTransit/src/org/montrealtransit/android/services/nextstop/StmMobileTask.java index bc48fe98..8f782490 100644 --- a/MonTransit/src/org/montrealtransit/android/services/nextstop/StmMobileTask.java +++ b/MonTransit/src/org/montrealtransit/android/services/nextstop/StmMobileTask.java @@ -1,365 +1,365 @@ package org.montrealtransit.android.services.nextstop; import java.net.HttpURLConnection; import java.net.SocketException; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.montrealtransit.android.AnalyticsUtils; import org.montrealtransit.android.Constant; import org.montrealtransit.android.MyLog; import org.montrealtransit.android.R; import org.montrealtransit.android.Utils; import org.montrealtransit.android.data.BusStopHours; import org.montrealtransit.android.provider.StmStore; import android.content.Context; import android.text.TextUtils; /** * This task retrieve next bus stop from the http://m.stm.info/ web site. * @author Mathieu Méa */ public class StmMobileTask extends AbstractNextStopProvider { /** * The log tag. */ private static final String TAG = StmMobileTask.class.getSimpleName(); /** * @see AbstractNextStopProvider#AbstractNextStopProvider(NextStopListener, Context) */ public StmMobileTask(NextStopListener from, Context context) { super(from, context); } /** * The source name. */ public static final String SOURCE_NAME = "m.stm.info"; /** * The URL part 1 with the bus stop code */ private static final String URL_PART_1_BEFORE_STOP_CODE = "http://m.stm.info/bus/arret/"; /** * The URL part 2 with the UI language. */ private static final String URL_PART_2_BEFORE_LANG = "?lang="; @Override protected Map<String, BusStopHours> doInBackground(StmStore.BusStop... busStops) { String stopCode = busStops[0].getCode(); String lineNumber = busStops[0].getLineNumber(); String urlString = getUrlString(stopCode); String errorMessage = this.context.getString(R.string.error); // set the default error message Map<String, BusStopHours> hours = new HashMap<String, BusStopHours>(); try { publishProgress(context.getString(R.string.downloading_data_from_and_source, StmMobileTask.SOURCE_NAME)); URL url = new URL(urlString); URLConnection urlc = url.openConnection(); MyLog.d(TAG, "URL created: '%s'", url.toString()); HttpURLConnection httpUrlConnection = (HttpURLConnection) urlc; switch (httpUrlConnection.getResponseCode()) { case HttpURLConnection.HTTP_OK: String html = Utils.getInputStreamToString(urlc.getInputStream(), "utf-8"); AnalyticsUtils.dispatch(context); // while we are connected, sent the analytics data publishProgress(this.context.getResources().getString(R.string.processing_data)); // FOR each bus line DO for (String line : findAllBusLines(html)) { hours.put(line, getBusStopHoursFromString(html, line)); } // IF the targeted bus line was there DO if (hours.keySet().contains(lineNumber)) { publishProgress(this.context.getResources().getString(R.string.done)); } else { // no info on m.stm.info about this bus stop errorMessage = this.context .getString(R.string.bus_stop_no_info_and_source, lineNumber, SOURCE_NAME); publishProgress(errorMessage); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, errorMessage)); AnalyticsUtils.trackEvent(context, AnalyticsUtils.CATEGORY_ERROR, AnalyticsUtils.ACTION_BUS_STOP_NO_INFO, busStops[0].getUID(), context.getPackageManager() .getPackageInfo(Constant.PKG, 0).versionCode); } return hours; case HttpURLConnection.HTTP_INTERNAL_ERROR: errorMessage = this.context.getString(R.string.error_http_500_and_source, this.context.getString(R.string.select_next_stop_data_source)); default: MyLog.w(TAG, "Error: HTTP URL-Connection Response Code:%s (Message: %s)", httpUrlConnection.getResponseCode(), httpUrlConnection.getResponseMessage()); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, errorMessage)); return hours; } } catch (UnknownHostException uhe) { MyLog.w(TAG, uhe, "No Internet Connection!"); publishProgress(this.context.getString(R.string.no_internet)); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.no_internet))); return hours; } catch (SocketException se) { MyLog.w(TAG, se, "No Internet Connection!"); publishProgress(this.context.getString(R.string.no_internet)); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.no_internet))); return hours; } catch (Exception e) { MyLog.e(TAG, e, "INTERNAL ERROR: Unknown Exception"); publishProgress(this.context.getString(R.string.error)); hours.put(lineNumber, new BusStopHours(SOURCE_NAME, this.context.getString(R.string.error))); return hours; } } /** * The pattern to extract the bus line number from the HTML source. */ private static final Pattern PATTERN_REGEX_LINE_NUMBER = Pattern.compile("<p class=\"route-desc\">[\\s]*" + "<a href=\"/bus/arrets/(([0-9]{1,3}))\" class=\"stm-link\">"); /** * @param html the HTML source * @return the bus line number included in the HTML source */ private Set<String> findAllBusLines(String html) { MyLog.v(TAG, "findAllBusLines(%s)", html.length()); Set<String> result = new HashSet<String>(); Matcher matcher = PATTERN_REGEX_LINE_NUMBER.matcher(html); while (matcher.find()) { result.add(matcher.group(1)); } return result; } /** * @param stopCode the bus stop code * @return the URL of the bus stop page on m.stm.info */ public static String getUrlString(String stopCode) { String result = URL_PART_1_BEFORE_STOP_CODE + stopCode; if (Utils.getUserLanguage().equals("fr")) { result += URL_PART_2_BEFORE_LANG + "fr"; } else { result += URL_PART_2_BEFORE_LANG + "en"; } return result; } /** * The pattern for the hours. */ private static final Pattern PATTERN_REGEX_FOR_HOURS = Pattern.compile("[0-9]{1,2}[h|:][0-9]{1,2}"); /** * @param html the HTML source * @param lineNumber the bus line number * @return the bus stop hours */ private BusStopHours getBusStopHoursFromString(String html, String lineNumber) { MyLog.v(TAG, "getBusStopHoursFromString(%s, %s)", html.length(), lineNumber); BusStopHours result = new BusStopHours(SOURCE_NAME); String interestingPart = getInterestingPart(html, lineNumber); if (interestingPart != null) { // find hours Matcher matcher = PATTERN_REGEX_FOR_HOURS.matcher(getRouteSchedule(interestingPart)); while (matcher.find()) { // considering 00h00 the standard (instead of the 00:00 provided by m.stm.info in English) result.addSHour(matcher.group().replaceAll(":", "h")); } // find 'notes' String notesPart = findNotesPart(interestingPart, lineNumber); if (!TextUtils.isEmpty(notesPart)) { String noteMessage = findMessage(notesPart); if (!TextUtils.isEmpty(noteMessage)) { String concernedBusStops = findNoteStops(notesPart); if (!TextUtils.isEmpty(concernedBusStops)) { result.addMessageString(this.context.getString(R.string.next_bus_stops_note, concernedBusStops, noteMessage)); } else { result.addMessageString(noteMessage); } } } // find 'mips' String mipsPart = findMipsPart(interestingPart, lineNumber); if (!TextUtils.isEmpty(mipsPart)) { String mipsMessage = findMessage(mipsPart); if (!TextUtils.isEmpty(mipsMessage)) { result.addMessage2String(mipsMessage); } } } else { MyLog.w(TAG, "Can't find the next bus stops for line %s!", lineNumber); } return result; } /** * The pattern for the route schedule. */ private static final Pattern PATTERN_REGEX_FOR_ROUTE_SCHEDULE = Pattern .compile("<p class=\"route-schedules\">[^<]*</p>[\\s]*"); /** * @param interestingPart the bus line part * @return the bus line route schedule part */ private String getRouteSchedule(String interestingPart) { String result = null; Matcher matcher = PATTERN_REGEX_FOR_ROUTE_SCHEDULE.matcher(interestingPart); if (matcher.find()) { result = matcher.group(); } return result; } /** * Find 'notes' part from the HTML code. * @param interestingPart the HTML code * @param lineNumber the concerned line number * @return the 'notes' part or <b>NULL</b> */ private String findNotesPart(String interestingPart, String lineNumber) { MyLog.v(TAG, "findNotesPart(%s)", interestingPart.length(), lineNumber); String result = null; String regex = "<div class=\"notes\">[\\s]*" + "<div class=\"wrapper\">[\\s]*" + "(" + "<div class=\"heure\">[^d]*div>[\\s]*" + "|" + "<div class=\"ligne\">" + lineNumber + "</div>[\\s]*" + ")" + "<div class=\"message\">[^<]*</div>[\\s]*" + "<div class=\"clearfloat\">[^<]*</div>[\\s]*" + "</div>[\\s]*" + "</div>[\\s]*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(interestingPart); while (matcher.find()) { result = matcher.group(0); } return result; } /** * Find the 'mips' part of the HTML code. * @param interestingPart the HTML code * @param lineNumber the line number * @return the 'mips' part or <b>NULL</b> */ private String findMipsPart(String interestingPart, String lineNumber) { MyLog.v(TAG, "findMipsPart(%s)", interestingPart.length(), lineNumber); String result = null; String regex = "<div class=\"mips\">[\\s]*" + "<div class=\"wrapper\">[\\s]*" + "<div class=\"ligne\">" + lineNumber + "</div>[\\s]*" + "<div class=\"message\">[^</]*</div>[\\s]*" + "<div class=\"clearfloat\">[^<]*</div>[\\s]*" + "</div>[\\s]*" + "</div>[\\s]*"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(interestingPart); while (matcher.find()) { result = matcher.group(0); } return result; } /** * The pattern used for stops note. */ private static final Pattern PATTERN_REGEX_NOTE_MESSAGE = Pattern.compile("<div class=\"message\">(([^<])*)</div>"); /** * Find the message * @param interestingPart the HTML code where the message is * @return the message or <b>NULL</b> */ private String findMessage(String interestingPart) { MyLog.v(TAG, "findMessage(%s)", interestingPart.length()); String result = null; Matcher matcher = PATTERN_REGEX_NOTE_MESSAGE.matcher(interestingPart); if (matcher.find()) { result = matcher.group(1); } return result; } /** * Find the stops concerned by the note message. * @param interestingPart the HTML code where note is supposed to be * @return the concerned stop or <B>NULL</b> */ private String findNoteStops(String interestingPart) { MyLog.v(TAG, "findNoteStops(%s)", interestingPart.length()); String result = null; String noteHourPart = findNoteHourPart(interestingPart); if (!TextUtils.isEmpty(noteHourPart)) { Matcher matcher = PATTERN_REGEX_FOR_HOURS.matcher(noteHourPart); while (matcher.find()) { if (result == null) { result = ""; } else { // if (result.length() > 0) { result += " "; } result += Utils.formatHours(context, matcher.group().replaceAll(":", "h")); } } return result; } /** * The pattern used for stops note. */ private static final Pattern PATTERN_REGEX_HOUR_PART = Pattern.compile("<div class=\"heure\">[^\bdiv\b]*"); /** * Find the part of the note containing the stops hours. * @param all the HTML code supposed to contains the stops hours * @return the part of the HTML code containing the stops hours or <B>NULL</B> */ private String findNoteHourPart(String all) { MyLog.v(TAG, "findNoteHourPart(%s)", all.length()); String result = null; Matcher matcher = PATTERN_REGEX_HOUR_PART.matcher(all); while (matcher.find()) { result = matcher.group(); } return result; } /** * @param html the HTML source * @param lineNumber the bus line number * @return the interesting part of the HTML source matching the bus line number */ private String getInterestingPart(String html, String lineNumber) { MyLog.v(TAG, "getInterestingPart(%s, %s)", html.length(), lineNumber); String result = null; String regex = "<div class=\"route\">[\\s]*" + "<p class=\"route-desc\">[\\s]*" + "<a href=\"/bus/arrets/" - + lineNumber + "\" class=\"stm-link\">[^</]*</a>[^<]*" + "</p>[^<]*" + + lineNumber + "\" [^>]*[^<]*</a>[^<]*" + "(<div>[^<]*</div>[^<]*)?" + "</p>[^<]*" + "<p class=\"route-schedules\">[^<]*</p>[\\s]*" + "(" + "<div class=\"notes\">[\\s]*" + "<div class=\"wrapper\">[\\s]*" + "<div class=\"heure\">[^d]*div>[\\s]*" + "<div class=\"message\">[^<]*</div>[\\s]*" + "<div class=\"clearfloat\">[^<]*</div>[\\s]*" + "</div>[\\s]*" + "</div>[\\s]*" + ")?" + "(" + "<div class=\"notes\">[\\s]*" + "<div class=\"wrapper\">[\\s]*" + "<div class=\"ligne\">" + lineNumber + "</div>[\\s]*" + "<div class=\"message\">[^<]*</div>[\\s]*" + "<div class=\"clearfloat\">[^<]*</div>[\\s]*" + "</div>[\\s]*" + "</div>[\\s]*" + ")?" + "(" + "<div class=\"mips\">[\\s]*" + "<div class=\"wrapper\">[\\s]*" + "<div class=\"ligne\">" + lineNumber + "</div>[\\s]*" + "<div class=\"message\">[^</]*</div>[\\s]*" + "<div class=\"clearfloat\">[^<]*</div>[\\s]*" + "</div>[\\s]*" + "</div>[\\s]*" + ")?" + "</div>"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(html); while (matcher.find()) { result = matcher.group(); } return result; } /** * {@inheritDoc} */ @Override public String getTag() { return TAG; } }
true
true
private String findNoteStops(String interestingPart) { MyLog.v(TAG, "findNoteStops(%s)", interestingPart.length()); String result = null; String noteHourPart = findNoteHourPart(interestingPart); if (!TextUtils.isEmpty(noteHourPart)) { Matcher matcher = PATTERN_REGEX_FOR_HOURS.matcher(noteHourPart); while (matcher.find()) { if (result == null) { result = ""; } else { // if (result.length() > 0) { result += " "; } result += Utils.formatHours(context, matcher.group().replaceAll(":", "h")); } } return result; } /** * The pattern used for stops note. */ private static final Pattern PATTERN_REGEX_HOUR_PART = Pattern.compile("<div class=\"heure\">[^\bdiv\b]*"); /** * Find the part of the note containing the stops hours. * @param all the HTML code supposed to contains the stops hours * @return the part of the HTML code containing the stops hours or <B>NULL</B> */ private String findNoteHourPart(String all) { MyLog.v(TAG, "findNoteHourPart(%s)", all.length()); String result = null; Matcher matcher = PATTERN_REGEX_HOUR_PART.matcher(all); while (matcher.find()) { result = matcher.group(); } return result; } /** * @param html the HTML source * @param lineNumber the bus line number * @return the interesting part of the HTML source matching the bus line number */ private String getInterestingPart(String html, String lineNumber) { MyLog.v(TAG, "getInterestingPart(%s, %s)", html.length(), lineNumber); String result = null; String regex = "<div class=\"route\">[\\s]*" + "<p class=\"route-desc\">[\\s]*" + "<a href=\"/bus/arrets/" + lineNumber + "\" class=\"stm-link\">[^</]*</a>[^<]*" + "</p>[^<]*" + "<p class=\"route-schedules\">[^<]*</p>[\\s]*" + "(" + "<div class=\"notes\">[\\s]*" + "<div class=\"wrapper\">[\\s]*" + "<div class=\"heure\">[^d]*div>[\\s]*" + "<div class=\"message\">[^<]*</div>[\\s]*" + "<div class=\"clearfloat\">[^<]*</div>[\\s]*" + "</div>[\\s]*" + "</div>[\\s]*" + ")?" + "(" + "<div class=\"notes\">[\\s]*" + "<div class=\"wrapper\">[\\s]*" + "<div class=\"ligne\">" + lineNumber + "</div>[\\s]*" + "<div class=\"message\">[^<]*</div>[\\s]*" + "<div class=\"clearfloat\">[^<]*</div>[\\s]*" + "</div>[\\s]*" + "</div>[\\s]*" + ")?" + "(" + "<div class=\"mips\">[\\s]*" + "<div class=\"wrapper\">[\\s]*" + "<div class=\"ligne\">" + lineNumber + "</div>[\\s]*" + "<div class=\"message\">[^</]*</div>[\\s]*" + "<div class=\"clearfloat\">[^<]*</div>[\\s]*" + "</div>[\\s]*" + "</div>[\\s]*" + ")?" + "</div>"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(html); while (matcher.find()) { result = matcher.group(); } return result; } /** * {@inheritDoc} */ @Override public String getTag() { return TAG; } }
private String findNoteStops(String interestingPart) { MyLog.v(TAG, "findNoteStops(%s)", interestingPart.length()); String result = null; String noteHourPart = findNoteHourPart(interestingPart); if (!TextUtils.isEmpty(noteHourPart)) { Matcher matcher = PATTERN_REGEX_FOR_HOURS.matcher(noteHourPart); while (matcher.find()) { if (result == null) { result = ""; } else { // if (result.length() > 0) { result += " "; } result += Utils.formatHours(context, matcher.group().replaceAll(":", "h")); } } return result; } /** * The pattern used for stops note. */ private static final Pattern PATTERN_REGEX_HOUR_PART = Pattern.compile("<div class=\"heure\">[^\bdiv\b]*"); /** * Find the part of the note containing the stops hours. * @param all the HTML code supposed to contains the stops hours * @return the part of the HTML code containing the stops hours or <B>NULL</B> */ private String findNoteHourPart(String all) { MyLog.v(TAG, "findNoteHourPart(%s)", all.length()); String result = null; Matcher matcher = PATTERN_REGEX_HOUR_PART.matcher(all); while (matcher.find()) { result = matcher.group(); } return result; } /** * @param html the HTML source * @param lineNumber the bus line number * @return the interesting part of the HTML source matching the bus line number */ private String getInterestingPart(String html, String lineNumber) { MyLog.v(TAG, "getInterestingPart(%s, %s)", html.length(), lineNumber); String result = null; String regex = "<div class=\"route\">[\\s]*" + "<p class=\"route-desc\">[\\s]*" + "<a href=\"/bus/arrets/" + lineNumber + "\" [^>]*[^<]*</a>[^<]*" + "(<div>[^<]*</div>[^<]*)?" + "</p>[^<]*" + "<p class=\"route-schedules\">[^<]*</p>[\\s]*" + "(" + "<div class=\"notes\">[\\s]*" + "<div class=\"wrapper\">[\\s]*" + "<div class=\"heure\">[^d]*div>[\\s]*" + "<div class=\"message\">[^<]*</div>[\\s]*" + "<div class=\"clearfloat\">[^<]*</div>[\\s]*" + "</div>[\\s]*" + "</div>[\\s]*" + ")?" + "(" + "<div class=\"notes\">[\\s]*" + "<div class=\"wrapper\">[\\s]*" + "<div class=\"ligne\">" + lineNumber + "</div>[\\s]*" + "<div class=\"message\">[^<]*</div>[\\s]*" + "<div class=\"clearfloat\">[^<]*</div>[\\s]*" + "</div>[\\s]*" + "</div>[\\s]*" + ")?" + "(" + "<div class=\"mips\">[\\s]*" + "<div class=\"wrapper\">[\\s]*" + "<div class=\"ligne\">" + lineNumber + "</div>[\\s]*" + "<div class=\"message\">[^</]*</div>[\\s]*" + "<div class=\"clearfloat\">[^<]*</div>[\\s]*" + "</div>[\\s]*" + "</div>[\\s]*" + ")?" + "</div>"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(html); while (matcher.find()) { result = matcher.group(); } return result; } /** * {@inheritDoc} */ @Override public String getTag() { return TAG; } }
diff --git a/src/main/java/com/censoredsoftware/demigods/engine/Demigods.java b/src/main/java/com/censoredsoftware/demigods/engine/Demigods.java index bfafb083..1ce0a8a3 100644 --- a/src/main/java/com/censoredsoftware/demigods/engine/Demigods.java +++ b/src/main/java/com/censoredsoftware/demigods/engine/Demigods.java @@ -1,317 +1,316 @@ package com.censoredsoftware.demigods.engine; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.conversations.ConversationFactory; import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import com.censoredsoftware.core.bukkit.ListedConversation; import com.censoredsoftware.core.module.Configs; import com.censoredsoftware.core.module.Messages; import com.censoredsoftware.demigods.DemigodsPlugin; import com.censoredsoftware.demigods.engine.command.DevelopmentCommands; import com.censoredsoftware.demigods.engine.command.GeneralCommands; import com.censoredsoftware.demigods.engine.command.MainCommand; import com.censoredsoftware.demigods.engine.conversation.Required; import com.censoredsoftware.demigods.engine.data.DataManager; import com.censoredsoftware.demigods.engine.data.ThreadManager; import com.censoredsoftware.demigods.engine.element.Ability; import com.censoredsoftware.demigods.engine.element.Deity; import com.censoredsoftware.demigods.engine.element.Structure.MassiveStructurePart; import com.censoredsoftware.demigods.engine.element.Structure.Structure; import com.censoredsoftware.demigods.engine.element.Task; import com.censoredsoftware.demigods.engine.exception.DemigodsStartupException; import com.censoredsoftware.demigods.engine.language.Translation; import com.censoredsoftware.demigods.engine.language.TranslationManager; import com.censoredsoftware.demigods.engine.listener.*; import com.censoredsoftware.demigods.engine.player.DCharacter; import com.censoredsoftware.demigods.engine.util.Structures; import com.google.common.collect.Sets; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; public class Demigods { // Public Static Access public static DemigodsPlugin plugin; public static ConversationFactory conversation; public static Messages message; public static Configs config; // Public Dependency Plugins public static WorldGuardPlugin worldguard; // The Game Data protected static Map<String, Deity> deities; protected static Set<Structure> structures; protected static Set<Task.List> quests; protected static Set<ListedConversation> conversasions; // Disabled Worlds protected static Set<String> disabledWorlds; protected static Set<String> commands; // The engine Default Text public static Translation text; public interface ListedDeity { public Deity getDeity(); } public interface ListedTaskSet { public Task.List getTaskSet(); } public interface ListedStructure { public Structure getStructure(); } public Demigods(DemigodsPlugin instance, final ListedDeity[] deities, final ListedTaskSet[] taskSets, final ListedStructure[] structures, final ListedConversation.ConversationData[] conversations, final Listener EpisodeListener) throws DemigodsStartupException { // Allow static access. plugin = instance; conversation = new ConversationFactory(instance); // Setup utilities. config = new Configs(instance, true); message = new Messages(instance); if(!loadWorlds(instance)) { message.severe("Demigods was unable to load any worlds."); - message.severe("At least 1 world must be enabled."); - message.severe("Configure at least 1 world for Demigods."); + message.severe("Please configure at least 1 world for Demigods."); instance.getServer().getPluginManager().disablePlugin(instance); throw new DemigodsStartupException(); } Demigods.deities = new HashMap<String, Deity>() { { for(ListedDeity deity : deities) put(deity.getDeity().getInfo().getName().toLowerCase(), deity.getDeity()); } }; Demigods.quests = new HashSet<Task.List>() { { for(ListedTaskSet taskSet : taskSets) add(taskSet.getTaskSet()); } }; Demigods.structures = new HashSet<Structure>() { { for(ListedStructure structure : structures) add(structure.getStructure()); } }; Demigods.conversasions = new HashSet<ListedConversation>() { { for(Required conversation : Required.values()) add(conversation.getConversation()); if(conversations != null) for(ListedConversation.ConversationData conversation : conversations) add(conversation.getConversation()); } }; Demigods.text = getTranslation(); // Initialize data new DataManager(); if(!DataManager.isConnected()) { message.severe("Demigods was unable to connect to a Redis server."); message.severe("A Redis server is required for Demigods to run."); message.severe("Please install and configure a Redis server. (" + ChatColor.UNDERLINE + "http://redis.io" + ChatColor.RESET + ")"); instance.getServer().getPluginManager().disablePlugin(instance); throw new DemigodsStartupException(); } // Update usable characters DCharacter.Util.updateUsableCharacters(); // Initialize metrics try { // (new Metrics(instance)).start(); } catch(Exception ignored) {} // Finish loading the plugin based on the game data loadDepends(instance); loadListeners(instance); loadCommands(instance); // Start game threads ThreadManager.startThreads(instance); // Finally, regenerate structures Structures.regenerateStructures(); if(isRunningSpigot()) message.info(("Spigot found, will use extra API features.")); } /** * Get the translation involved. * * @return The translation. */ public Translation getTranslation() { // Default to EnglishCharNames return new TranslationManager.English(); } public static boolean loadWorlds(DemigodsPlugin instance) { disabledWorlds = Sets.newHashSet(); for(String world : config.getSettingArrayListString("restrictions.disabled_worlds")) { if(instance.getServer().getWorld(world) != null) disabledWorlds.add(world); } if(instance.getServer().getWorlds().size() == disabledWorlds.size()) return false; return true; } protected static void loadListeners(DemigodsPlugin instance) { PluginManager register = instance.getServer().getPluginManager(); // engine register.registerEvents(new BattleListener(), instance); register.registerEvents(new CommandListener(), instance); register.registerEvents(new EntityListener(), instance); register.registerEvents(new FlagListener(), instance); register.registerEvents(new GriefListener(), instance); register.registerEvents(new InventoryListener(), instance); register.registerEvents(new PlayerListener(), instance); register.registerEvents(new TributeListener(), instance); // disabled worlds if(!disabledWorlds.isEmpty()) register.registerEvents(new DisabledWorldListener(), instance); // Deities for(Deity deity : getLoadedDeities().values()) { if(deity.getAbilities() == null) continue; for(Ability ability : deity.getAbilities()) { if(ability.getListener() != null) register.registerEvents(ability.getListener(), instance); } } // Tasks for(Task.List quest : getLoadedQuests()) { if(quest.getTasks() == null) continue; for(Task task : quest) { if(task.getListener() != null) register.registerEvents(task.getListener(), instance); } } // Structures for(Structure structure : getLoadedStructures()) { if(structure instanceof MassiveStructurePart || structure.getUniqueListener() == null) continue; register.registerEvents(structure.getUniqueListener(), instance); } // Conversations for(ListedConversation conversation : getLoadedConversations()) { if(conversation.getUniqueListener() == null) continue; register.registerEvents(conversation.getUniqueListener(), instance); } } protected static void loadCommands(DemigodsPlugin instance) { commands = Sets.newHashSet(); MainCommand main = new MainCommand(); GeneralCommands general = new GeneralCommands(); DevelopmentCommands development = new DevelopmentCommands(); main.register(instance, false); general.register(instance, false); development.register(instance, true); commands.addAll(main.getCommands()); commands.addAll(general.getCommands()); commands.addAll(development.getCommands()); commands.add("dg"); commands.add("demigod"); } protected static void loadDepends(DemigodsPlugin instance) { // WorldGuard Plugin depend = instance.getServer().getPluginManager().getPlugin("WorldGuard"); if(depend instanceof WorldGuardPlugin) worldguard = (WorldGuardPlugin) depend; } public static Map<String, Deity> getLoadedDeities() { return Demigods.deities; } public static Set<Task.List> getLoadedQuests() { return Demigods.quests; } public static Set<Structure> getLoadedStructures() { return Demigods.structures; } public static Set<ListedConversation> getLoadedConversations() { return Demigods.conversasions; } public static boolean isRunningSpigot() { try { Bukkit.getServer().getWorlds().get(0).spigot(); return true; } catch(Throwable ignored) {} return false; } public static boolean isDisabledWorld(Location location) { return disabledWorlds.contains(location.getWorld().getName()); } public static boolean isDisabledWorld(World world) { return disabledWorlds.contains(world.getName()); } public static boolean isDemigodsCommand(String command) { return commands.contains(command); } @Override public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } }
true
true
public Demigods(DemigodsPlugin instance, final ListedDeity[] deities, final ListedTaskSet[] taskSets, final ListedStructure[] structures, final ListedConversation.ConversationData[] conversations, final Listener EpisodeListener) throws DemigodsStartupException { // Allow static access. plugin = instance; conversation = new ConversationFactory(instance); // Setup utilities. config = new Configs(instance, true); message = new Messages(instance); if(!loadWorlds(instance)) { message.severe("Demigods was unable to load any worlds."); message.severe("At least 1 world must be enabled."); message.severe("Configure at least 1 world for Demigods."); instance.getServer().getPluginManager().disablePlugin(instance); throw new DemigodsStartupException(); } Demigods.deities = new HashMap<String, Deity>() { { for(ListedDeity deity : deities) put(deity.getDeity().getInfo().getName().toLowerCase(), deity.getDeity()); } }; Demigods.quests = new HashSet<Task.List>() { { for(ListedTaskSet taskSet : taskSets) add(taskSet.getTaskSet()); } }; Demigods.structures = new HashSet<Structure>() { { for(ListedStructure structure : structures) add(structure.getStructure()); } }; Demigods.conversasions = new HashSet<ListedConversation>() { { for(Required conversation : Required.values()) add(conversation.getConversation()); if(conversations != null) for(ListedConversation.ConversationData conversation : conversations) add(conversation.getConversation()); } }; Demigods.text = getTranslation(); // Initialize data new DataManager(); if(!DataManager.isConnected()) { message.severe("Demigods was unable to connect to a Redis server."); message.severe("A Redis server is required for Demigods to run."); message.severe("Please install and configure a Redis server. (" + ChatColor.UNDERLINE + "http://redis.io" + ChatColor.RESET + ")"); instance.getServer().getPluginManager().disablePlugin(instance); throw new DemigodsStartupException(); } // Update usable characters DCharacter.Util.updateUsableCharacters(); // Initialize metrics try { // (new Metrics(instance)).start(); } catch(Exception ignored) {} // Finish loading the plugin based on the game data loadDepends(instance); loadListeners(instance); loadCommands(instance); // Start game threads ThreadManager.startThreads(instance); // Finally, regenerate structures Structures.regenerateStructures(); if(isRunningSpigot()) message.info(("Spigot found, will use extra API features.")); }
public Demigods(DemigodsPlugin instance, final ListedDeity[] deities, final ListedTaskSet[] taskSets, final ListedStructure[] structures, final ListedConversation.ConversationData[] conversations, final Listener EpisodeListener) throws DemigodsStartupException { // Allow static access. plugin = instance; conversation = new ConversationFactory(instance); // Setup utilities. config = new Configs(instance, true); message = new Messages(instance); if(!loadWorlds(instance)) { message.severe("Demigods was unable to load any worlds."); message.severe("Please configure at least 1 world for Demigods."); instance.getServer().getPluginManager().disablePlugin(instance); throw new DemigodsStartupException(); } Demigods.deities = new HashMap<String, Deity>() { { for(ListedDeity deity : deities) put(deity.getDeity().getInfo().getName().toLowerCase(), deity.getDeity()); } }; Demigods.quests = new HashSet<Task.List>() { { for(ListedTaskSet taskSet : taskSets) add(taskSet.getTaskSet()); } }; Demigods.structures = new HashSet<Structure>() { { for(ListedStructure structure : structures) add(structure.getStructure()); } }; Demigods.conversasions = new HashSet<ListedConversation>() { { for(Required conversation : Required.values()) add(conversation.getConversation()); if(conversations != null) for(ListedConversation.ConversationData conversation : conversations) add(conversation.getConversation()); } }; Demigods.text = getTranslation(); // Initialize data new DataManager(); if(!DataManager.isConnected()) { message.severe("Demigods was unable to connect to a Redis server."); message.severe("A Redis server is required for Demigods to run."); message.severe("Please install and configure a Redis server. (" + ChatColor.UNDERLINE + "http://redis.io" + ChatColor.RESET + ")"); instance.getServer().getPluginManager().disablePlugin(instance); throw new DemigodsStartupException(); } // Update usable characters DCharacter.Util.updateUsableCharacters(); // Initialize metrics try { // (new Metrics(instance)).start(); } catch(Exception ignored) {} // Finish loading the plugin based on the game data loadDepends(instance); loadListeners(instance); loadCommands(instance); // Start game threads ThreadManager.startThreads(instance); // Finally, regenerate structures Structures.regenerateStructures(); if(isRunningSpigot()) message.info(("Spigot found, will use extra API features.")); }
diff --git a/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestUtils.java b/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestUtils.java index c76664abd..76fb9b3c7 100644 --- a/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestUtils.java +++ b/java/modules/integration/src/test/java/org/apache/synapse/samples/framework/SynapseTestUtils.java @@ -1,131 +1,131 @@ /* * 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.synapse.samples.framework; import org.apache.axiom.om.OMElement; import org.apache.synapse.SynapseException; import org.apache.synapse.samples.framework.config.SampleConfigConstants; import javax.xml.namespace.QName; import java.io.File; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; public class SynapseTestUtils { static String replace(String str, String pattern, String replace) { int s = 0; int e; StringBuilder result = new StringBuilder(); while ((e = str.indexOf(pattern, s)) >= 0) { result.append(str.substring(s, e)); result.append(replace); s = e + pattern.length(); } result.append(str.substring(s)); return result.toString(); } static String getIPAddress() throws Exception { List<InetAddress> ipAddresses = new ArrayList<InetAddress>(); String ipAddress = null; - Enumeration e = NetworkInterface.getNetworkInterfaces(); + Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { - NetworkInterface ni = (NetworkInterface) e.nextElement(); + NetworkInterface ni = e.nextElement(); // Clustering doesn't work for loop-back addresses, so we are not interested // we are not interested in inactive interfaces either - // if (ni.isLoopback() || !ni.isUp()) continue; TODO: Find Java 5 alternative + if (ni.isLoopback() || !ni.isUp()) continue; - Enumeration e2 = ni.getInetAddresses(); + Enumeration<InetAddress> e2 = ni.getInetAddresses(); while (e2.hasMoreElements()) { - InetAddress ip = (InetAddress) e2.nextElement(); + InetAddress ip = e2.nextElement(); ipAddresses.add(ip); } } if (ipAddresses.isEmpty()) { return null; } else { for (InetAddress ip : ipAddresses) { if (ip instanceof Inet4Address) { ipAddress = ip.getHostAddress(); break; } } } if (ipAddress == null) { ipAddress = ipAddresses.get(0).getHostAddress(); } return ipAddress; } public static String getParameter(OMElement root, String name, String def) { OMElement child = root.getFirstChildWithName(new QName(name)); if (child != null && !"".equals(child.getText())) { return child.getText(); } else { return def; } } public static String getRequiredParameter(OMElement root, String name) { OMElement child = root.getFirstChildWithName(new QName(name)); if (child != null && !"".equals(child.getText())) { return child.getText(); } else { throw new SynapseException("Required parameter: " + name + " unspecified"); } } public static String getAttribute(OMElement root, String name, String def) { String value = root.getAttributeValue(new QName(name)); if (value != null && !"".equals(value)) { return value; } else { return def; } } public static ProcessController createController(OMElement root) { if (SampleConfigConstants.TAG_BE_SERVER_CONF_AXIS2_SERVER.equals(root.getLocalName())) { return new Axis2BackEndServerController(root); } else if (SampleConfigConstants.TAG_BE_SERVER_CONF_DERBY_SERVER.equals(root.getLocalName())) { return new DerbyServerController(root); } else if (SampleConfigConstants.TAG_BE_SERVER_CONF_JMS_BROKER.equals(root.getLocalName())) { return new ActiveMQController(root); } else if (SampleConfigConstants.TAG_BE_SERVER_CONF_ECHO_SERVER.equals(root.getLocalName())) { return new EchoHttpServerController(root); } return null; } public static String getCurrentDir() { return System.getProperty("user.dir") + File.separator; } }
false
true
static String getIPAddress() throws Exception { List<InetAddress> ipAddresses = new ArrayList<InetAddress>(); String ipAddress = null; Enumeration e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) e.nextElement(); // Clustering doesn't work for loop-back addresses, so we are not interested // we are not interested in inactive interfaces either // if (ni.isLoopback() || !ni.isUp()) continue; TODO: Find Java 5 alternative Enumeration e2 = ni.getInetAddresses(); while (e2.hasMoreElements()) { InetAddress ip = (InetAddress) e2.nextElement(); ipAddresses.add(ip); } } if (ipAddresses.isEmpty()) { return null; } else { for (InetAddress ip : ipAddresses) { if (ip instanceof Inet4Address) { ipAddress = ip.getHostAddress(); break; } } } if (ipAddress == null) { ipAddress = ipAddresses.get(0).getHostAddress(); } return ipAddress; }
static String getIPAddress() throws Exception { List<InetAddress> ipAddresses = new ArrayList<InetAddress>(); String ipAddress = null; Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); while (e.hasMoreElements()) { NetworkInterface ni = e.nextElement(); // Clustering doesn't work for loop-back addresses, so we are not interested // we are not interested in inactive interfaces either if (ni.isLoopback() || !ni.isUp()) continue; Enumeration<InetAddress> e2 = ni.getInetAddresses(); while (e2.hasMoreElements()) { InetAddress ip = e2.nextElement(); ipAddresses.add(ip); } } if (ipAddresses.isEmpty()) { return null; } else { for (InetAddress ip : ipAddresses) { if (ip instanceof Inet4Address) { ipAddress = ip.getHostAddress(); break; } } } if (ipAddress == null) { ipAddress = ipAddresses.get(0).getHostAddress(); } return ipAddress; }
diff --git a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/config/DeploymentsResolver.java b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/config/DeploymentsResolver.java index 14eaa1fdd..f095b0733 100644 --- a/openejb3/container/openejb-core/src/main/java/org/apache/openejb/config/DeploymentsResolver.java +++ b/openejb3/container/openejb-core/src/main/java/org/apache/openejb/config/DeploymentsResolver.java @@ -1,302 +1,302 @@ /** * 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.config; import org.apache.openejb.config.sys.Deployments; import org.apache.openejb.config.sys.JaxbOpenejb; import org.apache.openejb.loader.FileUtils; import org.apache.openejb.loader.SystemInstance; import org.apache.openejb.util.Logger; import org.apache.xbean.finder.UrlSet; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; /** * @version $Rev$ $Date$ */ public class DeploymentsResolver { private static final String CLASSPATH_INCLUDE = "openejb.deployments.classpath.include"; private static final String CLASSPATH_EXCLUDE = "openejb.deployments.classpath.exclude"; private static final String CLASSPATH_REQUIRE_DESCRIPTOR = "openejb.deployments.classpath.require.descriptor"; private static final String CLASSPATH_FILTER_DESCRIPTORS = "openejb.deployments.classpath.filter.descriptors"; private static final String CLASSPATH_FILTER_SYSTEMAPPS = "openejb.deployments.classpath.filter.systemapps"; private static final Logger logger = DeploymentLoader.logger; private static void loadFrom(Deployments dep, FileUtils path, List<String> jarList) { //////////////////////////////// // // Expand the path of a jar // //////////////////////////////// if (dep.getDir() == null && dep.getJar() != null) { try { File jar = path.getFile(dep.getJar(), false); if (!jarList.contains(jar.getAbsolutePath())) { jarList.add(jar.getAbsolutePath()); } } catch (Exception ignored) { } return; } File dir = null; try { dir = path.getFile(dep.getDir(), false); } catch (Exception ignored) { } if (dir == null || !dir.isDirectory()) return; //////////////////////////////// // // Unpacked "Jar" directory // //////////////////////////////// File ejbJarXml = new File(dir, "META-INF" + File.separator + "ejb-jar.xml"); if (ejbJarXml.exists()) { if (!jarList.contains(dir.getAbsolutePath())) { jarList.add(dir.getAbsolutePath()); } return; } File appXml = new File(dir, "META-INF" + File.separator + "application.xml"); if (appXml.exists()) { if (!jarList.contains(dir.getAbsolutePath())) { jarList.add(dir.getAbsolutePath()); } return; } HashMap<String, URL> files = new HashMap<String, URL>(); DeploymentLoader.scanDir(dir, files, ""); for (String fileName : files.keySet()) { if (fileName.endsWith(".class")) { if (!jarList.contains(dir.getAbsolutePath())) { jarList.add(dir.getAbsolutePath()); } return; } } //////////////////////////////// // // Directory contains Jar files // //////////////////////////////// for (String fileName : files.keySet()) { if (fileName.endsWith(".jar") || fileName.endsWith(".ear")) { File jar = new File(dir, fileName); if (jarList.contains(jar.getAbsolutePath())) continue; jarList.add(jar.getAbsolutePath()); } } } public static List<String> resolveAppLocations(List<Deployments> deployments) { // make a copy of the list because we update it deployments = new ArrayList<Deployments>(deployments); //// getOption ///////////////////////////////// BEGIN //////////////////// String flag = SystemInstance.get().getProperty("openejb.deployments.classpath", "true").toLowerCase(); boolean searchClassPath = flag.equals("true"); //// getOption ///////////////////////////////// END //////////////////// if (searchClassPath) { Deployments deployment = JaxbOpenejb.createDeployments(); deployment.setClasspath(Thread.currentThread().getContextClassLoader()); deployments.add(deployment); } // resolve jar locations ////////////////////////////////////// BEGIN /////// FileUtils base = SystemInstance.get().getBase(); List<String> jarList = new ArrayList<String>(deployments.size()); try { for (Deployments deployment : deployments) { if (deployment.getClasspath() != null) { loadFromClasspath(base, jarList, deployment.getClasspath()); } else { loadFrom(deployment, base, jarList); } } } catch (SecurityException ignored) { } return jarList; } /** * The algorithm of OpenEJB deployments class-path inclusion and exclusion is implemented as follows: * 1- If the string value of the resource URL matches the include class-path pattern * Then load this resource * 2- If the string value of the resource URL matches the exclude class-path pattern * Then ignore this resource * 3- If the include and exclude class-path patterns are not defined * Then load this resource * <p/> * The previous steps are based on the following points: * 1- Include class-path pattern has the highst priority * This helps in case both patterns are defined using the same values. * This appears in step 1 and 2 of the above algorithm. * 2- Loading the resource is the default behaviour in case of not defining a value for any class-path pattern * This appears in step 3 of the above algorithm. */ private static void loadFromClasspath(FileUtils base, List<String> jarList, ClassLoader classLoader) { Deployments deployment = null; String include = null; String exclude = null; String path = null; include = SystemInstance.get().getProperty(CLASSPATH_INCLUDE, ""); exclude = SystemInstance.get().getProperty(CLASSPATH_EXCLUDE, ".*"); boolean requireDescriptors = SystemInstance.get().getProperty(CLASSPATH_REQUIRE_DESCRIPTOR, "false").equalsIgnoreCase("true"); boolean filterDescriptors = SystemInstance.get().getProperty(CLASSPATH_FILTER_DESCRIPTORS, "false").equalsIgnoreCase("true"); boolean filterSystemApps = SystemInstance.get().getProperty(CLASSPATH_FILTER_SYSTEMAPPS, "true").equalsIgnoreCase("true"); logger.debug("Using "+CLASSPATH_INCLUDE+" '"+include+"'"); logger.debug("Using "+CLASSPATH_EXCLUDE+" '"+exclude+"'"); logger.debug("Using "+CLASSPATH_FILTER_SYSTEMAPPS+" '"+filterSystemApps+"'"); logger.debug("Using "+CLASSPATH_FILTER_DESCRIPTORS+" '"+filterDescriptors+"'"); logger.debug("Using "+CLASSPATH_REQUIRE_DESCRIPTOR+" '"+requireDescriptors+"'"); try { UrlSet urlSet = new UrlSet(classLoader); UrlSet includes = urlSet.matching(include); urlSet = urlSet.exclude(ClassLoader.getSystemClassLoader().getParent()); urlSet = urlSet.excludeJavaExtDirs(); urlSet = urlSet.excludeJavaEndorsedDirs(); urlSet = urlSet.excludeJavaHome(); urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", "")); urlSet = urlSet.exclude(".*/JavaVM.framework/.*"); UrlSet prefiltered = urlSet; urlSet = urlSet.exclude(exclude); urlSet = urlSet.include(includes); if (filterSystemApps){ urlSet = urlSet.exclude(".*/openejb-[^/]+(.(jar|ear|war)(!/)?|/target/classes/?)"); } List<URL> urls = urlSet.getUrls(); int size = urls.size(); if (size == 0 && include.length() > 0) { logger.warning("No classpath URLs matched. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); return; } else if (size == 0 && (!filterDescriptors && prefiltered.getUrls().size() == 0)) { return; } else if (size < 10) { logger.debug("Inspecting classpath for applications: " + urls.size() + " urls."); } else if (size < 50 && !requireDescriptors) { logger.info("Inspecting classpath for applications: " + urls.size() + " urls. Consider adjusting your exclude/include. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } else if (!requireDescriptors) { logger.warning("Inspecting classpath for applications: " + urls.size() + " urls."); logger.warning("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } long begin = System.currentTimeMillis(); processUrls(urls, classLoader, !requireDescriptors, base, jarList); long end = System.currentTimeMillis(); long time = end - begin; UrlSet unchecked = new UrlSet(); if (!filterDescriptors){ unchecked = prefiltered.exclude(urlSet); if (filterSystemApps){ - urlSet = urlSet.exclude(".*/openejb-[^/]+(.(jar|ear|war)(!/)?|/target/classes/?)"); + unchecked = unchecked.exclude(".*/openejb-[^/]+(.(jar|ear|war)(./)?|/target/classes/?)"); } processUrls(unchecked.getUrls(), classLoader, false, base, jarList); } if (logger.isDebugEnabled()) { logger.debug("URLs after filtering: "+urlSet.getUrls().size() + unchecked.getUrls().size()); for (URL url : urlSet.getUrls()) { logger.debug("Annotations path: " + url); } for (URL url : unchecked.getUrls()) { logger.debug("Descriptors path: " + url); } } if (urls.size() == 0) return; if (time < 1000) { logger.debug("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 4000 || urls.size() < 3) { logger.info("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 10000) { logger.warning("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); logger.warning("Consider adjusting your " + CLASSPATH_EXCLUDE + " and " + CLASSPATH_INCLUDE + " settings. Current settings: exclude='" + exclude + "', include='" + include + "'"); } else { logger.fatal("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url. TOO LONG!"); logger.fatal("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); List<String> list = new ArrayList<String>(); for (URL url : urls) { list.add(url.toExternalForm()); } Collections.sort(list); for (String url : list) { logger.info("Matched: " + url); } } } catch (IOException e1) { e1.printStackTrace(); logger.warning("Unable to search classpath for modules: Received Exception: " + e1.getClass().getName() + " " + e1.getMessage(), e1); } } private static void processUrls(List<URL> urls, ClassLoader classLoader, boolean desc, FileUtils base, List<String> jarList) { Deployments deployment; String path; for (URL url : urls) { try { Class moduleType = DeploymentLoader.discoverModuleType(url, classLoader, desc); if (AppModule.class.isAssignableFrom(moduleType) || EjbModule.class.isAssignableFrom(moduleType)) { deployment = JaxbOpenejb.createDeployments(); if (url.getProtocol().equals("jar")) { url = new URL(url.getFile().replaceFirst("!.*$", "")); File file = new File(url.getFile()); path = file.getAbsolutePath(); deployment.setJar(path); } else if (url.getProtocol().equals("file")) { File file = new File(url.getFile()); path = file.getAbsolutePath(); deployment.setDir(path); } else { logger.warning("Not loading " + moduleType.getSimpleName() + ". Unknown protocol " + url.getProtocol()); continue; } logger.info("Found " + moduleType.getSimpleName() + " in classpath: " + path); loadFrom(deployment, base, jarList); } } catch (IOException e) { logger.warning("Unable to determine the module type of " + url.toExternalForm() + ": Exception: " + e.getMessage(), e); } catch (UnknownModuleTypeException ignore) { } } } }
true
true
private static void loadFromClasspath(FileUtils base, List<String> jarList, ClassLoader classLoader) { Deployments deployment = null; String include = null; String exclude = null; String path = null; include = SystemInstance.get().getProperty(CLASSPATH_INCLUDE, ""); exclude = SystemInstance.get().getProperty(CLASSPATH_EXCLUDE, ".*"); boolean requireDescriptors = SystemInstance.get().getProperty(CLASSPATH_REQUIRE_DESCRIPTOR, "false").equalsIgnoreCase("true"); boolean filterDescriptors = SystemInstance.get().getProperty(CLASSPATH_FILTER_DESCRIPTORS, "false").equalsIgnoreCase("true"); boolean filterSystemApps = SystemInstance.get().getProperty(CLASSPATH_FILTER_SYSTEMAPPS, "true").equalsIgnoreCase("true"); logger.debug("Using "+CLASSPATH_INCLUDE+" '"+include+"'"); logger.debug("Using "+CLASSPATH_EXCLUDE+" '"+exclude+"'"); logger.debug("Using "+CLASSPATH_FILTER_SYSTEMAPPS+" '"+filterSystemApps+"'"); logger.debug("Using "+CLASSPATH_FILTER_DESCRIPTORS+" '"+filterDescriptors+"'"); logger.debug("Using "+CLASSPATH_REQUIRE_DESCRIPTOR+" '"+requireDescriptors+"'"); try { UrlSet urlSet = new UrlSet(classLoader); UrlSet includes = urlSet.matching(include); urlSet = urlSet.exclude(ClassLoader.getSystemClassLoader().getParent()); urlSet = urlSet.excludeJavaExtDirs(); urlSet = urlSet.excludeJavaEndorsedDirs(); urlSet = urlSet.excludeJavaHome(); urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", "")); urlSet = urlSet.exclude(".*/JavaVM.framework/.*"); UrlSet prefiltered = urlSet; urlSet = urlSet.exclude(exclude); urlSet = urlSet.include(includes); if (filterSystemApps){ urlSet = urlSet.exclude(".*/openejb-[^/]+(.(jar|ear|war)(!/)?|/target/classes/?)"); } List<URL> urls = urlSet.getUrls(); int size = urls.size(); if (size == 0 && include.length() > 0) { logger.warning("No classpath URLs matched. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); return; } else if (size == 0 && (!filterDescriptors && prefiltered.getUrls().size() == 0)) { return; } else if (size < 10) { logger.debug("Inspecting classpath for applications: " + urls.size() + " urls."); } else if (size < 50 && !requireDescriptors) { logger.info("Inspecting classpath for applications: " + urls.size() + " urls. Consider adjusting your exclude/include. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } else if (!requireDescriptors) { logger.warning("Inspecting classpath for applications: " + urls.size() + " urls."); logger.warning("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } long begin = System.currentTimeMillis(); processUrls(urls, classLoader, !requireDescriptors, base, jarList); long end = System.currentTimeMillis(); long time = end - begin; UrlSet unchecked = new UrlSet(); if (!filterDescriptors){ unchecked = prefiltered.exclude(urlSet); if (filterSystemApps){ urlSet = urlSet.exclude(".*/openejb-[^/]+(.(jar|ear|war)(!/)?|/target/classes/?)"); } processUrls(unchecked.getUrls(), classLoader, false, base, jarList); } if (logger.isDebugEnabled()) { logger.debug("URLs after filtering: "+urlSet.getUrls().size() + unchecked.getUrls().size()); for (URL url : urlSet.getUrls()) { logger.debug("Annotations path: " + url); } for (URL url : unchecked.getUrls()) { logger.debug("Descriptors path: " + url); } } if (urls.size() == 0) return; if (time < 1000) { logger.debug("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 4000 || urls.size() < 3) { logger.info("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 10000) { logger.warning("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); logger.warning("Consider adjusting your " + CLASSPATH_EXCLUDE + " and " + CLASSPATH_INCLUDE + " settings. Current settings: exclude='" + exclude + "', include='" + include + "'"); } else { logger.fatal("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url. TOO LONG!"); logger.fatal("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); List<String> list = new ArrayList<String>(); for (URL url : urls) { list.add(url.toExternalForm()); } Collections.sort(list); for (String url : list) { logger.info("Matched: " + url); } } } catch (IOException e1) { e1.printStackTrace(); logger.warning("Unable to search classpath for modules: Received Exception: " + e1.getClass().getName() + " " + e1.getMessage(), e1); } }
private static void loadFromClasspath(FileUtils base, List<String> jarList, ClassLoader classLoader) { Deployments deployment = null; String include = null; String exclude = null; String path = null; include = SystemInstance.get().getProperty(CLASSPATH_INCLUDE, ""); exclude = SystemInstance.get().getProperty(CLASSPATH_EXCLUDE, ".*"); boolean requireDescriptors = SystemInstance.get().getProperty(CLASSPATH_REQUIRE_DESCRIPTOR, "false").equalsIgnoreCase("true"); boolean filterDescriptors = SystemInstance.get().getProperty(CLASSPATH_FILTER_DESCRIPTORS, "false").equalsIgnoreCase("true"); boolean filterSystemApps = SystemInstance.get().getProperty(CLASSPATH_FILTER_SYSTEMAPPS, "true").equalsIgnoreCase("true"); logger.debug("Using "+CLASSPATH_INCLUDE+" '"+include+"'"); logger.debug("Using "+CLASSPATH_EXCLUDE+" '"+exclude+"'"); logger.debug("Using "+CLASSPATH_FILTER_SYSTEMAPPS+" '"+filterSystemApps+"'"); logger.debug("Using "+CLASSPATH_FILTER_DESCRIPTORS+" '"+filterDescriptors+"'"); logger.debug("Using "+CLASSPATH_REQUIRE_DESCRIPTOR+" '"+requireDescriptors+"'"); try { UrlSet urlSet = new UrlSet(classLoader); UrlSet includes = urlSet.matching(include); urlSet = urlSet.exclude(ClassLoader.getSystemClassLoader().getParent()); urlSet = urlSet.excludeJavaExtDirs(); urlSet = urlSet.excludeJavaEndorsedDirs(); urlSet = urlSet.excludeJavaHome(); urlSet = urlSet.excludePaths(System.getProperty("sun.boot.class.path", "")); urlSet = urlSet.exclude(".*/JavaVM.framework/.*"); UrlSet prefiltered = urlSet; urlSet = urlSet.exclude(exclude); urlSet = urlSet.include(includes); if (filterSystemApps){ urlSet = urlSet.exclude(".*/openejb-[^/]+(.(jar|ear|war)(!/)?|/target/classes/?)"); } List<URL> urls = urlSet.getUrls(); int size = urls.size(); if (size == 0 && include.length() > 0) { logger.warning("No classpath URLs matched. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); return; } else if (size == 0 && (!filterDescriptors && prefiltered.getUrls().size() == 0)) { return; } else if (size < 10) { logger.debug("Inspecting classpath for applications: " + urls.size() + " urls."); } else if (size < 50 && !requireDescriptors) { logger.info("Inspecting classpath for applications: " + urls.size() + " urls. Consider adjusting your exclude/include. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } else if (!requireDescriptors) { logger.warning("Inspecting classpath for applications: " + urls.size() + " urls."); logger.warning("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); } long begin = System.currentTimeMillis(); processUrls(urls, classLoader, !requireDescriptors, base, jarList); long end = System.currentTimeMillis(); long time = end - begin; UrlSet unchecked = new UrlSet(); if (!filterDescriptors){ unchecked = prefiltered.exclude(urlSet); if (filterSystemApps){ unchecked = unchecked.exclude(".*/openejb-[^/]+(.(jar|ear|war)(./)?|/target/classes/?)"); } processUrls(unchecked.getUrls(), classLoader, false, base, jarList); } if (logger.isDebugEnabled()) { logger.debug("URLs after filtering: "+urlSet.getUrls().size() + unchecked.getUrls().size()); for (URL url : urlSet.getUrls()) { logger.debug("Annotations path: " + url); } for (URL url : unchecked.getUrls()) { logger.debug("Descriptors path: " + url); } } if (urls.size() == 0) return; if (time < 1000) { logger.debug("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 4000 || urls.size() < 3) { logger.info("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); } else if (time < 10000) { logger.warning("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url."); logger.warning("Consider adjusting your " + CLASSPATH_EXCLUDE + " and " + CLASSPATH_INCLUDE + " settings. Current settings: exclude='" + exclude + "', include='" + include + "'"); } else { logger.fatal("Searched " + urls.size() + " classpath urls in " + time + " milliseconds. Average " + (time / urls.size()) + " milliseconds per url. TOO LONG!"); logger.fatal("ADJUST THE EXCLUDE/INCLUDE!!!. Current settings: " + CLASSPATH_EXCLUDE + "='" + exclude + "', " + CLASSPATH_INCLUDE + "='" + include + "'"); List<String> list = new ArrayList<String>(); for (URL url : urls) { list.add(url.toExternalForm()); } Collections.sort(list); for (String url : list) { logger.info("Matched: " + url); } } } catch (IOException e1) { e1.printStackTrace(); logger.warning("Unable to search classpath for modules: Received Exception: " + e1.getClass().getName() + " " + e1.getMessage(), e1); } }
diff --git a/server/serengeti/src/main/java/com/vmware/bdd/entity/ClusterEntity.java b/server/serengeti/src/main/java/com/vmware/bdd/entity/ClusterEntity.java index 83b907f6..6a84ffb0 100644 --- a/server/serengeti/src/main/java/com/vmware/bdd/entity/ClusterEntity.java +++ b/server/serengeti/src/main/java/com/vmware/bdd/entity/ClusterEntity.java @@ -1,305 +1,308 @@ /*************************************************************************** * Copyright (c) 2012 VMware, Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ***************************************************************************/ package com.vmware.bdd.entity; import java.net.URI; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import com.google.gson.Gson; import com.vmware.bdd.apitypes.ClusterRead; import com.vmware.bdd.apitypes.ClusterRead.ClusterStatus; import com.vmware.bdd.apitypes.NodeGroupRead; import com.vmware.bdd.dal.DAL; import com.vmware.bdd.exception.BddException; /** * Cluster Entity * */ @Entity @SequenceGenerator(name = "IdSequence", sequenceName = "cluster_seq", allocationSize = 1) @Table(name = "cluster") public class ClusterEntity extends EntityBase { @Column(name = "name", unique = true, nullable = false) private String name; @Enumerated(EnumType.STRING) @Column(name = "status", nullable = false) private ClusterStatus status; @Column(name = "distro") private String distro; @Column(name = "start_after_deploy") private boolean startAfterDeploy; @OneToMany(mappedBy = "cluster", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private Set<NodeGroupEntity> nodeGroups; /* * cluster definition field. VCResourcePool inside this array may not be used * by this cluster, so we should avoid setting up the ManyToMany mapping. * JSON encoded VCResourcePoolEntity name array */ @Column(name = "vc_rp_names") private String vcRpNames; /* * cluster definition field. VCDataStores inside this array may not be used * by this cluster, so we should avoid setting up the ManyToMany mapping. * JSON encoded VCDataStoreEntity name array */ @Column(name = "vc_datastore_names") private String vcDatastoreNames; // OneToMany mapping with Network table @ManyToOne @JoinColumn(name = "network_id") private NetworkEntity network; @Column(name = "configuration") private String hadoopConfig; ClusterEntity() { } public ClusterEntity(String name) { super(); this.name = name; this.status = ClusterStatus.NA; } public NetworkEntity getNetwork() { return network; } public void setNetwork(NetworkEntity network) { this.network = network; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ClusterStatus getStatus() { return status; } public void setStatus(ClusterStatus status) { this.status = status; } public String getDistro() { return distro; } public void setDistro(String distro) { this.distro = distro; } public boolean isStartAfterDeploy() { return startAfterDeploy; } public void setStartAfterDeploy(boolean startAfterDeploy) { this.startAfterDeploy = startAfterDeploy; } public Set<NodeGroupEntity> getNodeGroups() { return nodeGroups; } public void setNodeGroups(Set<NodeGroupEntity> nodeGroups) { this.nodeGroups = nodeGroups; } public String getVcRpNames() { return this.vcRpNames; } @SuppressWarnings("unchecked") public List<String> getVcRpNameList() { return (new Gson()).fromJson(vcRpNames, (new ArrayList<String>()).getClass()); } public void setVcRpNameList(List<String> vcRpNameList) { this.vcRpNames = (new Gson()).toJson(vcRpNameList); } public String getVcDatastoreNames() { return this.vcDatastoreNames; } @SuppressWarnings("unchecked") public List<String> getVcDatastoreNameList() { return (new Gson()).fromJson(vcDatastoreNames, (new ArrayList<String>()).getClass()); } public void setVcDatastoreNameList(List<String> vcDatastoreNameList) { this.vcDatastoreNames = (new Gson()).toJson(vcDatastoreNameList); } public int getRealInstanceNum() { int instanceNum = 0; for (NodeGroupEntity group : nodeGroups) { instanceNum += group.getRealInstanceNum(); } return instanceNum; } public int getDefinedInstanceNum() { int instanceNum = 0; for (NodeGroupEntity group : nodeGroups) { instanceNum += group.getDefineInstanceNum(); } return instanceNum; } public Set<VcResourcePoolEntity> getUsedRps() { Set<VcResourcePoolEntity> rps = new HashSet<VcResourcePoolEntity>(); for (NodeGroupEntity group : nodeGroups) { rps.addAll(group.getUsedVcResourcePools()); } return rps; } public Set<String> getUsedVcDatastores() { HashSet<String> datastores = new HashSet<String>(); for (NodeGroupEntity group : nodeGroups) { datastores.addAll(group.getUsedVcDatastores()); } return datastores; } public String getHadoopConfig() { return hadoopConfig; } public void setHadoopConfig(String hadoopConfig) { this.hadoopConfig = hadoopConfig; } public ClusterRead toClusterRead() { ClusterRead clusterRead = new ClusterRead(); clusterRead.setInstanceNum(this.getRealInstanceNum()); clusterRead.setName(this.name); clusterRead.setStatus(this.status); clusterRead.setDistro(this.distro); List<NodeGroupRead> groupList = new ArrayList<NodeGroupRead>(); for(NodeGroupEntity group : this.getNodeGroups()) { groupList.add(group.toNodeGroupRead()); } clusterRead.setNodeGroups(groupList); return clusterRead; } public static ClusterEntity findClusterEntityById(Long clusterId) { return DAL.findById(ClusterEntity.class, clusterId); } public static ClusterEntity findClusterEntityByName(String name) { return DAL.findUniqueByCriteria(ClusterEntity.class, Restrictions.eq("name", name)); } public static List<ClusterEntity> findClusterEntityByDatastore(String dsName) { List<ClusterEntity> clusters = DAL.findByCriteria(ClusterEntity.class, Restrictions.like("vcDatastoreNames", dsName, MatchMode.ANYWHERE)); Iterator<ClusterEntity> i = clusters.iterator(); while (i.hasNext()) { ClusterEntity cluster = i.next(); if (!cluster.getVcDatastoreNameList().contains(dsName)) { i.remove(); } } return clusters; } public static List<ClusterEntity> findClusterEntityByRP(String rpName) { List<ClusterEntity> clusters = DAL.findByCriteria(ClusterEntity.class, Restrictions.like("vcRpNames", rpName, MatchMode.ANYWHERE)); Iterator<ClusterEntity> i = clusters.iterator(); while (i.hasNext()) { ClusterEntity cluster = i.next(); if (!cluster.getVcRpNameList().contains(rpName)) { i.remove(); } } return clusters; } @SuppressWarnings("unchecked") public static boolean hasHDFSUrlConfigured(Map<String, Object> conf) { + if (conf == null) { + return false; + } Map<String, Object> hadoopConf = (Map<String, Object>) conf.get("hadoop"); if (hadoopConf == null) { return false; } Map<String, Object> coreSiteConf = (Map<String, Object>) hadoopConf.get("core-site.xml"); if (coreSiteConf == null) { return false; } String url = (String)coreSiteConf.get("fs.default.name"); if (url != null && !url.isEmpty()) { try { URI uri = new URI(url); if (!"hdfs".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null) { throw BddException.INVALID_PARAMETER("fs.default.name", url); } } catch (Exception ex) { throw BddException.INVALID_PARAMETER(ex, "fs.default.name", url); } return true; } return false; } }
true
true
public static boolean hasHDFSUrlConfigured(Map<String, Object> conf) { Map<String, Object> hadoopConf = (Map<String, Object>) conf.get("hadoop"); if (hadoopConf == null) { return false; } Map<String, Object> coreSiteConf = (Map<String, Object>) hadoopConf.get("core-site.xml"); if (coreSiteConf == null) { return false; } String url = (String)coreSiteConf.get("fs.default.name"); if (url != null && !url.isEmpty()) { try { URI uri = new URI(url); if (!"hdfs".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null) { throw BddException.INVALID_PARAMETER("fs.default.name", url); } } catch (Exception ex) { throw BddException.INVALID_PARAMETER(ex, "fs.default.name", url); } return true; } return false; }
public static boolean hasHDFSUrlConfigured(Map<String, Object> conf) { if (conf == null) { return false; } Map<String, Object> hadoopConf = (Map<String, Object>) conf.get("hadoop"); if (hadoopConf == null) { return false; } Map<String, Object> coreSiteConf = (Map<String, Object>) hadoopConf.get("core-site.xml"); if (coreSiteConf == null) { return false; } String url = (String)coreSiteConf.get("fs.default.name"); if (url != null && !url.isEmpty()) { try { URI uri = new URI(url); if (!"hdfs".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null) { throw BddException.INVALID_PARAMETER("fs.default.name", url); } } catch (Exception ex) { throw BddException.INVALID_PARAMETER(ex, "fs.default.name", url); } return true; } return false; }
diff --git a/iSnorkeling/src/isnork/g3/WaterProofCartogram.java b/iSnorkeling/src/isnork/g3/WaterProofCartogram.java index 078b502..933d7d3 100644 --- a/iSnorkeling/src/isnork/g3/WaterProofCartogram.java +++ b/iSnorkeling/src/isnork/g3/WaterProofCartogram.java @@ -1,665 +1,667 @@ package isnork.g3; import isnork.sim.GameObject.Direction; import isnork.sim.Observation; import isnork.sim.SeaLifePrototype; import isnork.sim.SeaLife; import isnork.sim.iSnorkMessage; import java.awt.geom.Point2D; import java.text.NumberFormat; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.Queue; import java.util.LinkedList; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.collect.Ordering; import com.google.common.primitives.Doubles; public class WaterProofCartogram implements Cartogram { private List<CreatureRecord> movingCreatures; private Messenger messenger; private Point2D currentLocation; private Transcoder xcoder; private final Pokedex dex; private final Random random; private final Square[][] mapStructure; private final int sideLength; private final int viewRadius; private int ticks; private final Set<Integer> creaturesSeen; private final Set<Integer> creaturesOnMap; private final Map<String, Integer> speciesInViewCount; private final static Map<Direction, Coord> DIRECTION_MAP = ImmutableMap .<Direction, Coord> builder().put(Direction.E, new Coord(1, 0)) .put(Direction.W, new Coord(-1, 0)) .put(Direction.S, new Coord(0, 1)) .put(Direction.N, new Coord(0, -1)) .put(Direction.SE, new Coord(1, 1)) .put(Direction.SW, new Coord(-1, 1)) .put(Direction.NE, new Coord(1, -1)) .put(Direction.NW, new Coord(-1, -1)) .put(Direction.STAYPUT, new Coord(0, 0)).build(); private final static Map<Direction, Coord> orthoDirectionMap = ImmutableMap .<Direction, Coord> builder().put(Direction.E, new Coord(1, 0)) .put(Direction.W, new Coord(-1, 0)) .put(Direction.S, new Coord(0, 1)) .put(Direction.N, new Coord(0, -1)).build(); private final static Map<Direction, Coord> diagDirectionMap = ImmutableMap .<Direction, Coord> builder().put(Direction.SE, new Coord(1, 1)) .put(Direction.SW, new Coord(-1, 1)) .put(Direction.NE, new Coord(1, -1)) .put(Direction.NW, new Coord(-1, -1)).build(); private static final int MAX_TICKS_PER_ROUND = 60 * 8; /* * Tunes how quickly to forget we've seen a creature. The higher this * number, the sooner a creature will be removed from the map after viewing. */ private static final double MAX_DECAY = 0.25; public WaterProofCartogram(int mapWidth, int viewRadius, int numDivers, Pokedex dex) { this.sideLength = mapWidth; this.viewRadius = viewRadius; this.mapStructure = new WaterProofSquare[sideLength][sideLength]; for (int i = 0; i < sideLength; i++) { for (int j = 0; j < sideLength; j++) { this.mapStructure[i][j] = new WaterProofSquare(); } } this.random = new Random(); this.movingCreatures = Lists.newArrayList(); this.creaturesSeen = Sets.newHashSet(); this.creaturesOnMap = Sets.newHashSet(); this.speciesInViewCount = Maps.newHashMap(); this.dex = dex; ticks = 0; messenger = new WaterProofMessenger(dex, numDivers, sideLength); } @Override public void update(final Point2D myPosition, Set<Observation> whatYouSee, Set<Observation> playerLocations, Set<iSnorkMessage> incomingMessages) { ticks++; currentLocation = myPosition; for (int i=0; i<mapStructure.length; i++) { for (int j=0; j<mapStructure.length; j++) { mapStructure[i][j].tick(); } } speciesInViewCount.clear(); for (Observation obs : whatYouSee) { int count = speciesInViewCount.containsKey(obs.getName()) ? speciesInViewCount.get(obs.getName()) + 1 : 1; speciesInViewCount.put(obs.getName(), count); } Predicate<iSnorkMessage> isNotFromMyLocation = new Predicate<iSnorkMessage>() { @Override public boolean apply(iSnorkMessage msg) { return !myPosition.equals(msg.getLocation()); } }; messenger.addReceivedMessages(Sets.filter(incomingMessages, isNotFromMyLocation)); for (Observation obs : whatYouSee) { /* This is a diver. */ if (obs.getId() <= 0) continue; if (currentLocation.getX() != 0 || currentLocation.getY() != 0) { dex.personallySawCreature(obs.getName()); } seeCreature(obs.getId(), obs.getName(), dex.get(obs.getName()), obs.getLocation()); } // get discovered creatures based on received messages: for (SeaLife creature : messenger.getDiscovered()) { + if(squareFor(creature.getLocation()) == null) + System.out.println("null: "+creature); seeCreature( creature.getId(), creature.getName(), creature, creature.getLocation()); } if (!whatYouSee.isEmpty()) { communicate(whatYouSee); } updateMovingCreatures(); updateUnseenCreatures(); updateEdgeAtStart(); squareFor(0, 0).setExpectedHappiness(0); //System.out.println(toString()); } public void seeCreature( int id, String name, SeaLifePrototype seaLife, Point2D location) { if (name == null || seaLife == null) { return; } SeaLifePrototype seaLifeProto = new SeaLifePrototypeBuilder().name(name). happiness(dex.getHappiness(name)).dangerous(seaLife.isDangerous()). moving(seaLife.getSpeed() > 0 ? true : false).create(); if (seaLife.getSpeed() > 0) { movingCreatures.add(new CreatureRecord(id, location, seaLifeProto)); } else { squareFor(location).addCreature(seaLifeProto, 1.); } if (currentLocation.getX() != 0 || currentLocation.getY() != 0) { creaturesSeen.add(id); } } private void communicate(Set<Observation> observations) { // pick highest value creature Ordering<Observation> happiness = new Ordering<Observation>() { public int compare(Observation left, Observation right) { return Doubles.compare(left.happinessD(), right.happinessD()); } }; ImmutableSortedSet<Observation> sortedObservations = ImmutableSortedSet .orderedBy(happiness).addAll(observations).build(); Observation bestSeen = sortedObservations.first(); //do not observe other divers if(bestSeen.getId() > 0) { messenger.addOutboundMessage(bestSeen); } } @VisibleForTesting Square squareFor(Point2D location) { return squareFor((int) location.getX(), (int) location.getY()); } @VisibleForTesting Square squareFor(int x, int y) { if (! insideBounds(x, y)) return null; x += (sideLength / 2); y += (sideLength / 2); return mapStructure[x][y]; } private boolean insideBounds(int x, int y) { return Math.abs(x) <= sideLength / 2 && Math.abs(y) <= sideLength / 2; } private void updateEdgeAtStart() { for (int i=0; i<sideLength; i++) { mapStructure[i][0].increaseExpectedHappinessBy(100. * (1. / ticks)); mapStructure[i][sideLength-1] .increaseExpectedHappinessBy(100. * (1. / ticks)); } for (int j=1; j<sideLength-1; j++) { mapStructure[0][j].increaseExpectedHappinessBy(100. * (1. / ticks)); mapStructure[sideLength-1][j] .increaseExpectedHappinessBy(100. * (1. / ticks)); } } private void updateMovingCreatures() { creaturesOnMap.clear(); for (Iterator<CreatureRecord> iter = movingCreatures.iterator(); iter .hasNext();) { CreatureRecord record = iter.next(); if (creaturesOnMap.contains(record.id)) { //System.out.println("Duplicate record"); continue; } creaturesOnMap.add(record.id); int r = (ticks - record.confirmedAt) / 2; double certainty = 1 / (r + 1.); if (certainty <= MAX_DECAY) { iter.remove(); } int x = (int) record.location.getX(); int y = (int) record.location.getY(); /* Loop through squares in viewing radius */ for (int dx = -r; dx <= r; dx++) { for (int dy = -r; dy <= r; dy++) { if (insideBounds(x + dx, y + dy) && Math.sqrt(dx * dx + dy * dy) <= r) { addCreatureToSquare(record.id, x + dx, y + dy, record.seaLife, certainty); } } } } } private void updateUnseenCreatures() { double expectedHappinessInFog = 0.; for (SeaLifePrototype proto : dex.getAllSpecies()) { double expectedCount = (proto.getMaxCount() + proto.getMinCount()) / 2; double difference; if (! speciesInViewCount.containsKey(proto.getName())) { difference = expectedCount; } else { difference = expectedCount - speciesInViewCount.get(proto.getName()); } if (difference > 0) { expectedHappinessInFog += difference * proto.getHappiness(); } } int squaresOutOfView = (int) Math.pow(sideLength, 2) - (int) Math.pow(viewRadius, 2); double expectedFogPerSquare = expectedHappinessInFog / squaresOutOfView; for (int i=0; i<sideLength; i++) { for (int j=0; j<sideLength; j++) { double distanceToDiver = Math.sqrt(Math.pow(i - (currentLocation.getX() + sideLength / 2), 2) + Math.pow(j - (currentLocation.getY() + sideLength / 2), 2)); if (distanceToDiver > viewRadius) { mapStructure[i][j] .increaseExpectedHappinessBy(expectedFogPerSquare); } } } } private int movesToSquare(double r, int x, int y) { double r_delta = (r - viewRadius) / r; if (r_delta < 0) return 0; int small = x < y ? x : y; int large = x < y ? y : x; /* Most efficient way to travel between squares is to take diagonals * until you are on the same row or column, then travel the rest of the * way along a line. */ return (int) (r_delta * (3 * small + 2 * (large - small))); } private double happinessProportionOfCreature(SeaLifePrototype proto) { double viewCount = (double) dex.getPersonalSeenCount(proto.getName()); return viewCount > 3 ? 0. : 1. / (1. + viewCount); } private void addCreatureToSquare( int id, int x, int y, SeaLifePrototype proto, double certainty) { for (int dx = -viewRadius; dx <= viewRadius; dx++) { for (int dy = -viewRadius; dy <= viewRadius; dy++) { double r = Math.sqrt(dx * dx + dy * dy); if (r <= viewRadius) { Square thisSquare = squareFor(x + dx, y + dy); if (thisSquare != null) { double modifier = certainty * (1 / (1. + movesToSquare(r, x, y))); double addHappiness = creaturesSeen.contains(id) ? 0 : modifier * proto.getHappiness() * happinessProportionOfCreature(proto); double addDanger = ! proto.isDangerous() || r > 1.5 ? 0 : modifier * proto.getHappiness() * 2; //System.out.println(x+dx + ", " + (y+dy) + ", " + // proto.getName() + ": mod=" + // modifier + ", hap=" + addHappiness + ", dan=" + // addDanger); thisSquare.increaseExpectedHappinessBy(addHappiness); thisSquare.increaseExpectedDangerBy(addDanger); } } } } } @Override public String getMessage() { return messenger.sendNext(); } @Override public Direction getNextDirection() { Direction nextDir = unOptimizedHeatmapGetNextDirection(); //double danger = getExpectedDangerForCoords(DIRECTION_MAP.get( // nextDir).move((int) currentLocation.getX(), (int) currentLocation.getY())); //if(danger > 0.0) // return Direction.STAYPUT; return nextDir; } private Direction greedyHillClimb(double x, double y) { /* * Iterate over all possible new squares you can hit next. For you to * move in a diagonal direction, you need to be 1.5* as good as ortho To * stay in the same square, you only need to be .5 * as good as ortho */ List<DirectionValue> lst = getExpectations((int) currentLocation.getX(), (int) currentLocation.getY()); Direction dir = selectRandomProportionally(lst, x, y); return dir; } // private Direction getMaxDirection(List<DirectionValue> lst) { // DirectionValue max = lst.get(0); // // for (DirectionValue dv : lst) { // if (dv.getDub() > max.getDub()) { // max = dv; // } // } // // return max.getDir(); // } private List<DirectionValue> getExpectations(int x, int y) { List<DirectionValue> lst = Lists.newArrayListWithCapacity(8); lst.add(new DirectionValue(Direction.STAYPUT, getExpectedHappinessForCoords(x, y) * 6.0)); for (Entry<Direction, Coord> entry : orthoDirectionMap.entrySet()) { lst.add(new DirectionValue(entry.getKey(), getExpectedHappinessForCoords(entry.getValue().move( x, y)) * 3.0)); } for (Entry<Direction, Coord> entry : diagDirectionMap.entrySet()) { lst.add(new DirectionValue(entry.getKey(), getExpectedHappinessForCoords(entry.getValue().move( x, y)) * 2.0)); } return lst; } private Direction selectRandomProportionally(List<DirectionValue> lst, double x, double y){ List<Double> intLst = Lists.newArrayListWithCapacity(8); double runningSum = 0; for (int i = 0; i < 8; i++) { double dub = lst.get(i).getDub(); if (dub > 0){ runningSum += dub; } intLst.add(i, runningSum); } // Object val = random.nextInt(runningSum); double myRand = random.nextDouble() * runningSum; //System.out.println(myRand); Direction dir; if (myRand < intLst.get(0)){ // System.out.println(0); dir = lst.get(0).getDir(); } else if (myRand < intLst.get(1)){ // System.out.println(1); dir = lst.get(1).getDir(); } else if (myRand < intLst.get(2)){ // System.out.println(2); dir = lst.get(2).getDir(); } else if (myRand < intLst.get(3)){ // System.out.println(3); dir = lst.get(3).getDir(); } else if (myRand < intLst.get(4)){ // System.out.println(4); dir = lst.get(4).getDir(); } else if (myRand < intLst.get(5)){ // System.out.println(5); dir = lst.get(5).getDir(); } else if (myRand < intLst.get(6)){ // System.out.println(6); dir = lst.get(6).getDir(); } else if (myRand < intLst.get(7)){ // System.out.println(7); dir = lst.get(7).getDir(); } else{ dir = returnBoat(x, y); } return dir; } private double getExpectedHappinessForCoords(Coord coord) { return getExpectedHappinessForCoords(coord.getX(), coord.getY()); } private double getExpectedHappinessForCoords(int x, int y) { Square square = squareFor(x, y); if (square == null){ return Double.NEGATIVE_INFINITY; } else{ return square.getExpectedHappiness(); } } private final static double square(double x) { return x * x; } private double getExpectedDangerForCoords(double unadjustedX, double unadjustedY) { if (unadjustedX == 0 && unadjustedY == 0) { return 0; } if (isInvalidCoords(unadjustedX, unadjustedY)) { return Double.MIN_VALUE; } double x = unadjustedX + sideLength / 2; double y = unadjustedY + sideLength / 2; int minX = (int) x - viewRadius; minX = ((minX > 0) ? minX : 0); int minY = (int) y - viewRadius; minY = ((minY > 0) ? minY : 0); int maxX = (int) x + viewRadius; maxX = ((maxX < sideLength) ? maxX : sideLength); int maxY = (int) y + viewRadius; maxY = ((maxY < sideLength) ? maxY : sideLength); double expectedDanger = 0.0; for (int xCoord = minX; xCoord < maxX; xCoord++) { for (int yCoord = minY; yCoord < maxY; yCoord++) { double sqrt = Math.sqrt(square((xCoord - x) + square(yCoord - y))); if (sqrt < viewRadius) { expectedDanger += mapStructure[xCoord][yCoord] .getExpectedDanger(); } } } return expectedDanger; } private boolean isInvalidCoords(double x, double y) { if (x < -sideLength / 2) { return true; } else if (x > sideLength / 2) { return true; } else if (y < -sideLength / 2) { return true; } else if (y > sideLength / 2) { return true; } else { return false; } } private Direction unOptimizedHeatmapGetNextDirection() { int tickLeeway = MAX_TICKS_PER_ROUND - 3 * ticks; double y = currentLocation.getY(); double x = currentLocation.getX(); if (Math.abs(x) < tickLeeway && Math.abs(y) < tickLeeway) { return greedyHillClimb(x, y); } else { return returnBoat(x, y); } } private Direction returnBoat(double x, double y) { // Move towards boat String direc = getReturnDirectionString(); return avoidDanger(genList(direc), x, y); } private String getReturnDirectionString() { String direc = ""; if (currentLocation.getY() < 0) direc = direc.concat("S"); else if (currentLocation.getY() > 0) direc = direc.concat("N"); if (currentLocation.getX() < 0) direc = direc.concat("E"); else if (currentLocation.getX() > 0) direc = direc.concat("W"); return direc; } private Direction avoidDanger(List<DirectionValue> genList, double x, double y) { for (DirectionValue dv : genList) { if (getExpectedDangerForCoords(DIRECTION_MAP.get(dv.getDir()).move((int) x, (int) y)) == 0) { return dv.getDir(); } } return Direction.STAYPUT; } private double getExpectedDangerForCoords(Coord coord) { return getExpectedDangerForCoords(coord.getX(), coord.getY()); } private static final List<DirectionValue> genList(String direc) { if (direc.equals("W")) { return ImmutableList.of(new DirectionValue(Direction.W, 2.0), new DirectionValue(Direction.NW, 1.0), new DirectionValue( Direction.SW, 1.0)); } else if (direc.equals("E")) { return ImmutableList.of(new DirectionValue(Direction.E, 2.0), new DirectionValue(Direction.NE, 1.0), new DirectionValue( Direction.SE, 1.0)); } else if (direc.equals("N")) { return ImmutableList.of(new DirectionValue(Direction.N, 2.0), new DirectionValue(Direction.NE, 1.0), new DirectionValue( Direction.NW, 1.0)); } else if (direc.equals("S")) { return ImmutableList.of(new DirectionValue(Direction.S, 2.0), new DirectionValue(Direction.SE, 1.0), new DirectionValue( Direction.SW, 1.0)); } else if (direc.equals("NE")) { return ImmutableList.of(new DirectionValue(Direction.NE, 2.0), new DirectionValue(Direction.N, 1.0), new DirectionValue( Direction.E, 1.0)); } else if (direc.equals("SE")) { return ImmutableList.of(new DirectionValue(Direction.SE, 2.0), new DirectionValue(Direction.S, 1.0), new DirectionValue( Direction.E, 1.0)); } else if (direc.equals("NW")) { return ImmutableList.of(new DirectionValue(Direction.NW, 2.0), new DirectionValue(Direction.W, 1.0), new DirectionValue( Direction.N, 1.0)); } else if (direc.equals("SW")) { return ImmutableList.of(new DirectionValue(Direction.SW, 2.0), new DirectionValue(Direction.S, 1.0), new DirectionValue( Direction.W, 1.0)); } else { return ImmutableList.of(new DirectionValue(Direction.STAYPUT, 1.0)); } } public String toString() { StringBuilder output = new StringBuilder("Board at "); output.append(ticks); output.append("\n"); NumberFormat numberFormat = NumberFormat.getNumberInstance(); numberFormat.setMaximumFractionDigits(2); numberFormat.setMinimumFractionDigits(2); for (int i = 0; i < sideLength; i++) { for (int j = 0; j < sideLength; j++) { output.append(String.format( "%1$#10s", numberFormat.format( mapStructure[j][i].getExpectedHappiness()))); output.append(" "); } output.append("\n"); } /* output.append("\nWe got shit at:\n"); for (int i = 0; i < mapStructure.length; i++) { for (int j = 0; j < mapStructure[i].length; j++) { if (mapStructure[i][j].getCreatures().size() > 0) { output.append(i - (sideLength / 2)); output.append(", "); output.append(j - (sideLength / 2)); output.append("\n"); } } } */ return output.toString(); } private class CreatureRecord { public final int id; public final Point2D location; public final SeaLifePrototype seaLife; public final int confirmedAt; public CreatureRecord( int id, Point2D location, SeaLifePrototype seaLife) { this.id = id; this.location = location; this.seaLife = seaLife; this.confirmedAt = ticks; } } }
true
true
public void update(final Point2D myPosition, Set<Observation> whatYouSee, Set<Observation> playerLocations, Set<iSnorkMessage> incomingMessages) { ticks++; currentLocation = myPosition; for (int i=0; i<mapStructure.length; i++) { for (int j=0; j<mapStructure.length; j++) { mapStructure[i][j].tick(); } } speciesInViewCount.clear(); for (Observation obs : whatYouSee) { int count = speciesInViewCount.containsKey(obs.getName()) ? speciesInViewCount.get(obs.getName()) + 1 : 1; speciesInViewCount.put(obs.getName(), count); } Predicate<iSnorkMessage> isNotFromMyLocation = new Predicate<iSnorkMessage>() { @Override public boolean apply(iSnorkMessage msg) { return !myPosition.equals(msg.getLocation()); } }; messenger.addReceivedMessages(Sets.filter(incomingMessages, isNotFromMyLocation)); for (Observation obs : whatYouSee) { /* This is a diver. */ if (obs.getId() <= 0) continue; if (currentLocation.getX() != 0 || currentLocation.getY() != 0) { dex.personallySawCreature(obs.getName()); } seeCreature(obs.getId(), obs.getName(), dex.get(obs.getName()), obs.getLocation()); } // get discovered creatures based on received messages: for (SeaLife creature : messenger.getDiscovered()) { seeCreature( creature.getId(), creature.getName(), creature, creature.getLocation()); } if (!whatYouSee.isEmpty()) { communicate(whatYouSee); } updateMovingCreatures(); updateUnseenCreatures(); updateEdgeAtStart(); squareFor(0, 0).setExpectedHappiness(0); //System.out.println(toString()); }
public void update(final Point2D myPosition, Set<Observation> whatYouSee, Set<Observation> playerLocations, Set<iSnorkMessage> incomingMessages) { ticks++; currentLocation = myPosition; for (int i=0; i<mapStructure.length; i++) { for (int j=0; j<mapStructure.length; j++) { mapStructure[i][j].tick(); } } speciesInViewCount.clear(); for (Observation obs : whatYouSee) { int count = speciesInViewCount.containsKey(obs.getName()) ? speciesInViewCount.get(obs.getName()) + 1 : 1; speciesInViewCount.put(obs.getName(), count); } Predicate<iSnorkMessage> isNotFromMyLocation = new Predicate<iSnorkMessage>() { @Override public boolean apply(iSnorkMessage msg) { return !myPosition.equals(msg.getLocation()); } }; messenger.addReceivedMessages(Sets.filter(incomingMessages, isNotFromMyLocation)); for (Observation obs : whatYouSee) { /* This is a diver. */ if (obs.getId() <= 0) continue; if (currentLocation.getX() != 0 || currentLocation.getY() != 0) { dex.personallySawCreature(obs.getName()); } seeCreature(obs.getId(), obs.getName(), dex.get(obs.getName()), obs.getLocation()); } // get discovered creatures based on received messages: for (SeaLife creature : messenger.getDiscovered()) { if(squareFor(creature.getLocation()) == null) System.out.println("null: "+creature); seeCreature( creature.getId(), creature.getName(), creature, creature.getLocation()); } if (!whatYouSee.isEmpty()) { communicate(whatYouSee); } updateMovingCreatures(); updateUnseenCreatures(); updateEdgeAtStart(); squareFor(0, 0).setExpectedHappiness(0); //System.out.println(toString()); }
diff --git a/src/org/broad/igv/feature/genome/GenomeImporter.java b/src/org/broad/igv/feature/genome/GenomeImporter.java index 07c38afad..78c56776f 100644 --- a/src/org/broad/igv/feature/genome/GenomeImporter.java +++ b/src/org/broad/igv/feature/genome/GenomeImporter.java @@ -1,312 +1,312 @@ /* * Copyright (c) 2007-2012 The Broad Institute, Inc. * SOFTWARE COPYRIGHT NOTICE * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved. * * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.broad.igv.feature.genome; import org.apache.log4j.Logger; import org.broad.igv.Globals; import org.broad.igv.util.FileUtils; import org.broad.igv.util.HttpUtils; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * /** * * @author jrobinso */ public class GenomeImporter { public static final int MAX_CONTIGS = 1500000; static Logger log = Logger.getLogger(GenomeImporter.class); public static final Pattern SEQUENCE_NAME_SPLITTER = Pattern.compile("\\s+"); /** * Create a zip containing all the information and data required to load a * genome. All file/directory validation is assume to have been done by validation * outside of this method. * * @param genomeFile * @param genomeId Id of the genome. * @param genomeDisplayName The genome name that is user-friendly. * @param fastaFile The location of a fasta file, or directory of fasta files * @param refFlatFile RefFlat file. * @param cytobandFile Cytoband file. * @return The newly created genome archive file. */ public File createGenomeArchive(File genomeFile, String genomeId, String genomeDisplayName, String fastaFile, File refFlatFile, File cytobandFile, File chrAliasFile) throws IOException { if ((genomeFile == null) || (genomeId == null) || (genomeDisplayName == null)) { log.error("Invalid input for genome creation: "); log.error("\tGenome file=" + genomeFile.getAbsolutePath()); log.error("\tGenome Id=" + genomeId); log.error("\tGenome Name" + genomeDisplayName); return null; } File propertyFile = null; File archive = null; FileWriter propertyFileWriter = null; try { boolean fastaDirectory = false; List<String> fastaFileNames = new ArrayList<String>(); if (!FileUtils.resourceExists(fastaFile)) { String msg = "File not found: " + fastaFile; throw new GenomeException(msg); } if (fastaFile.toLowerCase().endsWith(Globals.ZIP_EXTENSION)) { String msg = "Error. Zip archives are not supported. Please select a fasta file."; throw new GenomeException(msg); } if (fastaFile.toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) { String msg = "Error. GZipped files are not supported. Please select a non-gzipped fasta file."; throw new GenomeException(msg); } List<String> fastaIndexPathList = new ArrayList<String>(); String fastaIndexPath = fastaFile + ".fai"; File sequenceInputFile = new File(fastaFile); if (sequenceInputFile.exists()) { // Local file if (sequenceInputFile.isDirectory()) { fastaDirectory = true; List<File> files = getSequenceFiles(sequenceInputFile); for (File file : files) { if (file.getName().toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) { String msg = "<html>Error. One or more fasta files are gzipped: " + file.getName() + "<br>All fasta files must be gunzipped prior to importing."; throw new GenomeException(msg); } - File indexFile = new File(fastaIndexPath); + File indexFile = new File(sequenceInputFile, file.getName() + ".fai"); if (!indexFile.exists()) { - FastaUtils.createIndexFile(fastaFile, fastaIndexPath); + FastaUtils.createIndexFile(file.getAbsolutePath(), indexFile.getAbsolutePath()); } fastaIndexPathList.add(fastaIndexPath); fastaFileNames.add(file.getName()); } } else { // Index if neccessary File indexFile = new File(fastaIndexPath); if (!indexFile.exists()) { FastaUtils.createIndexFile(fastaFile, fastaIndexPath); } fastaIndexPathList.add(fastaIndexPath); } } else { if (!FileUtils.resourceExists(fastaIndexPath)) { String msg = "<html>Index file " + fastaIndexPath + " Not found. " + "<br>Remote fasta files must be indexed prior to importing."; throw new GenomeException(msg); } } fastaFile = FileUtils.getRelativePath(genomeFile.getParent(), fastaFile); // Create "in memory" property file byte[] propertyBytes = createGenomePropertyFile(genomeId, genomeDisplayName, fastaFile, refFlatFile, cytobandFile, chrAliasFile, fastaDirectory, fastaFileNames); File[] inputFiles = {refFlatFile, cytobandFile, chrAliasFile}; // Create archive createGenomeArchive(genomeFile, inputFiles, propertyBytes); } finally { if (propertyFileWriter != null) { try { propertyFileWriter.close(); } catch (IOException ex) { log.error("Failed to close genome archive: +" + archive.getAbsolutePath(), ex); } } if (propertyFile != null) propertyFile.delete(); } return archive; } private List<File> getSequenceFiles(File sequenceDir) { ArrayList<File> files = new ArrayList(); for (File f : sequenceDir.listFiles()) { if (f.getName().startsWith(".") || f.isDirectory() || f.getName().endsWith(".fai")) { continue; } else { files.add(f); } } return files; } /** * This method creates the property.txt file that is stored in each * .genome file. This is not the user-defined genome property file * created by storeUserDefinedGenomeListToFile(...) * * @param genomeId * @param genomeDisplayName * @param relativeSequenceLocation * @param refFlatFile * @param cytobandFile * @param fastaFileNames * @return */ public byte[] createGenomePropertyFile(String genomeId, String genomeDisplayName, String relativeSequenceLocation, File refFlatFile, File cytobandFile, File chrAliasFile, boolean fastaDirectory, List<String> fastaFileNames) throws IOException { PrintWriter propertyFileWriter = null; try { ByteArrayOutputStream propertyBytes = new ByteArrayOutputStream(); // Add the new property file to the archive propertyFileWriter = new PrintWriter(new OutputStreamWriter(propertyBytes)); propertyFileWriter.println("fasta=true"); // Fasta is the only format supported now propertyFileWriter.println("fastaDirectory=" + fastaDirectory); if (fastaDirectory) { propertyFileWriter.print("fastaFiles="); for (String fif : fastaFileNames) { propertyFileWriter.print(fif + ","); } propertyFileWriter.println(); } propertyFileWriter.println("ordered=" + !fastaDirectory); if (genomeId != null) { propertyFileWriter.println(Globals.GENOME_ARCHIVE_ID_KEY + "=" + genomeId); } if (genomeDisplayName != null) { propertyFileWriter.println(Globals.GENOME_ARCHIVE_NAME_KEY + "=" + genomeDisplayName); } if (cytobandFile != null) { propertyFileWriter.println(Globals.GENOME_ARCHIVE_CYTOBAND_FILE_KEY + "=" + cytobandFile.getName()); } if (refFlatFile != null) { propertyFileWriter.println(Globals.GENOME_ARCHIVE_GENE_FILE_KEY + "=" + refFlatFile.getName()); } if (chrAliasFile != null) { propertyFileWriter.println(Globals.GENOME_CHR_ALIAS_FILE_KEY + "=" + chrAliasFile.getName()); } if (relativeSequenceLocation != null) { if (!HttpUtils.isRemoteURL(relativeSequenceLocation)) { relativeSequenceLocation = relativeSequenceLocation.replace('\\', '/'); } propertyFileWriter.println(Globals.GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY + "=" + relativeSequenceLocation); } propertyFileWriter.flush(); return propertyBytes.toByteArray(); } finally { if (propertyFileWriter != null) { propertyFileWriter.close(); } } } final static int ZIP_ENTRY_CHUNK_SIZE = 64000; static public void createGenomeArchive(File zipOutputFile, File[] inputFiles, byte[] propertyBytes) throws FileNotFoundException, IOException { if (zipOutputFile == null) { return; } if ((inputFiles == null) || (inputFiles.length == 0)) { return; } ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(zipOutputFile)); ZipEntry propertiesEntry = new ZipEntry("property.txt"); propertiesEntry.setSize(propertyBytes.length); zipOutputStream.putNextEntry(propertiesEntry); zipOutputStream.write(propertyBytes); for (File file : inputFiles) { if (file == null) { continue; } long fileLength = file.length(); ZipEntry zipEntry = new ZipEntry(file.getName()); zipEntry.setSize(fileLength); zipOutputStream.putNextEntry(zipEntry); BufferedInputStream bufferedInputstream = null; try { InputStream inputStream = new FileInputStream(file); bufferedInputstream = new BufferedInputStream(inputStream); int bytesRead = 0; byte[] data = new byte[ZIP_ENTRY_CHUNK_SIZE]; while ((bytesRead = bufferedInputstream.read(data)) != -1) { zipOutputStream.write(data, 0, bytesRead); } } finally { if (bufferedInputstream != null) { bufferedInputstream.close(); } } } } finally { if (zipOutputStream != null) { zipOutputStream.flush(); zipOutputStream.close(); } } } }
false
true
public File createGenomeArchive(File genomeFile, String genomeId, String genomeDisplayName, String fastaFile, File refFlatFile, File cytobandFile, File chrAliasFile) throws IOException { if ((genomeFile == null) || (genomeId == null) || (genomeDisplayName == null)) { log.error("Invalid input for genome creation: "); log.error("\tGenome file=" + genomeFile.getAbsolutePath()); log.error("\tGenome Id=" + genomeId); log.error("\tGenome Name" + genomeDisplayName); return null; } File propertyFile = null; File archive = null; FileWriter propertyFileWriter = null; try { boolean fastaDirectory = false; List<String> fastaFileNames = new ArrayList<String>(); if (!FileUtils.resourceExists(fastaFile)) { String msg = "File not found: " + fastaFile; throw new GenomeException(msg); } if (fastaFile.toLowerCase().endsWith(Globals.ZIP_EXTENSION)) { String msg = "Error. Zip archives are not supported. Please select a fasta file."; throw new GenomeException(msg); } if (fastaFile.toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) { String msg = "Error. GZipped files are not supported. Please select a non-gzipped fasta file."; throw new GenomeException(msg); } List<String> fastaIndexPathList = new ArrayList<String>(); String fastaIndexPath = fastaFile + ".fai"; File sequenceInputFile = new File(fastaFile); if (sequenceInputFile.exists()) { // Local file if (sequenceInputFile.isDirectory()) { fastaDirectory = true; List<File> files = getSequenceFiles(sequenceInputFile); for (File file : files) { if (file.getName().toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) { String msg = "<html>Error. One or more fasta files are gzipped: " + file.getName() + "<br>All fasta files must be gunzipped prior to importing."; throw new GenomeException(msg); } File indexFile = new File(fastaIndexPath); if (!indexFile.exists()) { FastaUtils.createIndexFile(fastaFile, fastaIndexPath); } fastaIndexPathList.add(fastaIndexPath); fastaFileNames.add(file.getName()); } } else { // Index if neccessary File indexFile = new File(fastaIndexPath); if (!indexFile.exists()) { FastaUtils.createIndexFile(fastaFile, fastaIndexPath); } fastaIndexPathList.add(fastaIndexPath); } } else { if (!FileUtils.resourceExists(fastaIndexPath)) { String msg = "<html>Index file " + fastaIndexPath + " Not found. " + "<br>Remote fasta files must be indexed prior to importing."; throw new GenomeException(msg); } } fastaFile = FileUtils.getRelativePath(genomeFile.getParent(), fastaFile); // Create "in memory" property file byte[] propertyBytes = createGenomePropertyFile(genomeId, genomeDisplayName, fastaFile, refFlatFile, cytobandFile, chrAliasFile, fastaDirectory, fastaFileNames); File[] inputFiles = {refFlatFile, cytobandFile, chrAliasFile}; // Create archive createGenomeArchive(genomeFile, inputFiles, propertyBytes); } finally { if (propertyFileWriter != null) { try { propertyFileWriter.close(); } catch (IOException ex) { log.error("Failed to close genome archive: +" + archive.getAbsolutePath(), ex); } } if (propertyFile != null) propertyFile.delete(); } return archive; }
public File createGenomeArchive(File genomeFile, String genomeId, String genomeDisplayName, String fastaFile, File refFlatFile, File cytobandFile, File chrAliasFile) throws IOException { if ((genomeFile == null) || (genomeId == null) || (genomeDisplayName == null)) { log.error("Invalid input for genome creation: "); log.error("\tGenome file=" + genomeFile.getAbsolutePath()); log.error("\tGenome Id=" + genomeId); log.error("\tGenome Name" + genomeDisplayName); return null; } File propertyFile = null; File archive = null; FileWriter propertyFileWriter = null; try { boolean fastaDirectory = false; List<String> fastaFileNames = new ArrayList<String>(); if (!FileUtils.resourceExists(fastaFile)) { String msg = "File not found: " + fastaFile; throw new GenomeException(msg); } if (fastaFile.toLowerCase().endsWith(Globals.ZIP_EXTENSION)) { String msg = "Error. Zip archives are not supported. Please select a fasta file."; throw new GenomeException(msg); } if (fastaFile.toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) { String msg = "Error. GZipped files are not supported. Please select a non-gzipped fasta file."; throw new GenomeException(msg); } List<String> fastaIndexPathList = new ArrayList<String>(); String fastaIndexPath = fastaFile + ".fai"; File sequenceInputFile = new File(fastaFile); if (sequenceInputFile.exists()) { // Local file if (sequenceInputFile.isDirectory()) { fastaDirectory = true; List<File> files = getSequenceFiles(sequenceInputFile); for (File file : files) { if (file.getName().toLowerCase().endsWith(Globals.GZIP_FILE_EXTENSION)) { String msg = "<html>Error. One or more fasta files are gzipped: " + file.getName() + "<br>All fasta files must be gunzipped prior to importing."; throw new GenomeException(msg); } File indexFile = new File(sequenceInputFile, file.getName() + ".fai"); if (!indexFile.exists()) { FastaUtils.createIndexFile(file.getAbsolutePath(), indexFile.getAbsolutePath()); } fastaIndexPathList.add(fastaIndexPath); fastaFileNames.add(file.getName()); } } else { // Index if neccessary File indexFile = new File(fastaIndexPath); if (!indexFile.exists()) { FastaUtils.createIndexFile(fastaFile, fastaIndexPath); } fastaIndexPathList.add(fastaIndexPath); } } else { if (!FileUtils.resourceExists(fastaIndexPath)) { String msg = "<html>Index file " + fastaIndexPath + " Not found. " + "<br>Remote fasta files must be indexed prior to importing."; throw new GenomeException(msg); } } fastaFile = FileUtils.getRelativePath(genomeFile.getParent(), fastaFile); // Create "in memory" property file byte[] propertyBytes = createGenomePropertyFile(genomeId, genomeDisplayName, fastaFile, refFlatFile, cytobandFile, chrAliasFile, fastaDirectory, fastaFileNames); File[] inputFiles = {refFlatFile, cytobandFile, chrAliasFile}; // Create archive createGenomeArchive(genomeFile, inputFiles, propertyBytes); } finally { if (propertyFileWriter != null) { try { propertyFileWriter.close(); } catch (IOException ex) { log.error("Failed to close genome archive: +" + archive.getAbsolutePath(), ex); } } if (propertyFile != null) propertyFile.delete(); } return archive; }
diff --git a/src/paulscode/android/mupen64plusae/GameSurface.java b/src/paulscode/android/mupen64plusae/GameSurface.java index 1916278e..edda1b8a 100644 --- a/src/paulscode/android/mupen64plusae/GameSurface.java +++ b/src/paulscode/android/mupen64plusae/GameSurface.java @@ -1,361 +1,361 @@ /** * Mupen64PlusAE, an N64 emulator for the Android platform * * Copyright (C) 2012 Paul Lamb * * This file is part of Mupen64PlusAE. * * Mupen64PlusAE 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. * * Mupen64PlusAE 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 Mupen64PlusAE. If not, see <http://www.gnu.org/licenses/>. * * Authors: paulscode, lioncash */ package paulscode.android.mupen64plusae; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import android.content.Context; import android.graphics.Canvas; import android.graphics.PixelFormat; import android.opengl.GLSurfaceView; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; /** * Represents a graphical area of memory that can be drawn to. */ public class GameSurface extends GLSurfaceView implements SurfaceHolder.Callback { public interface CoreLifecycleListener { public void onCoreStartup(); public void onCoreShutdown(); } public interface OnFpsChangedListener { /** * Called when the frame rate value has changed. * * @param fps The new FPS value. */ public void onFpsChanged( int fps ); } // Thread that the emulator core runs on private static Thread mCoreThread; // Core lifecycle listener private CoreLifecycleListener mClListener; // Frame rate listener private OnFpsChangedListener mFpsListener; private int mFpsRecalcPeriod = 0; private boolean mIsFpsEnabled = false; private long mLastFpsTime = 0; private int mFrameCount = -1; // Internal flags private boolean mIsRgba8888 = false; // EGL private objects private EGLSurface mEGLSurface; private EGLDisplay mEGLDisplay; // Startup public GameSurface( Context context, AttributeSet attribs ) { super( context, attribs ); getHolder().addCallback( this ); setFocusable( true ); setFocusableInTouchMode( true ); requestFocus(); } public void init( CoreLifecycleListener clListener, OnFpsChangedListener fpsListener, int fpsRecalcPeriod, boolean isRgba8888 ) { mClListener = clListener; mFpsListener = fpsListener; mFpsRecalcPeriod = fpsRecalcPeriod; mIsFpsEnabled = mFpsRecalcPeriod > 0; mIsRgba8888 = isRgba8888; } @Override public void surfaceCreated( SurfaceHolder holder ) { // Called when we have a valid drawing surface Log.i( "GameSurface", "surfaceCreated: " ); } @SuppressWarnings( "deprecation" ) @Override public void surfaceChanged( SurfaceHolder holder, int format, int width, int height ) { // Called when the surface is resized Log.i( "GameSurface", "surfaceChanged: " ); int sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 by default switch( format ) { case PixelFormat.A_8: break; case PixelFormat.LA_88: break; case PixelFormat.L_8: break; case PixelFormat.RGBA_4444: sdlFormat = 0x85421002; // SDL_PIXELFORMAT_RGBA4444 break; case PixelFormat.RGBA_5551: sdlFormat = 0x85441002; // SDL_PIXELFORMAT_RGBA5551 break; case PixelFormat.RGBA_8888: sdlFormat = 0x86462004; // SDL_PIXELFORMAT_RGBA8888 break; case PixelFormat.RGBX_8888: sdlFormat = 0x86262004; // SDL_PIXELFORMAT_RGBX8888 break; case PixelFormat.RGB_332: sdlFormat = 0x84110801; // SDL_PIXELFORMAT_RGB332 break; case PixelFormat.RGB_565: sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 break; case PixelFormat.RGB_888: // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead? sdlFormat = 0x86161804; // SDL_PIXELFORMAT_RGB888 break; case PixelFormat.OPAQUE: /* * TODO: Not sure this is right, Android API says, * "System chooses an opaque format", but how do we know which one?? */ break; default: Log.w( "GameLifecycleHandler", "Pixel format unknown: " + format ); break; } NativeMethods.onResize( width, height, sdlFormat ); mCoreThread = new Thread( new Runnable() { @Override public void run() { NativeMethods.init(); } }, "CoreThread" ); mCoreThread.start(); // Wait for the emu state callback indicating emulation has started CoreInterface.waitForEmuState( CoreInterface.EMULATOR_STATE_RUNNING ); // The core has started up, notify the listener if( mClListener != null ) mClListener.onCoreStartup(); } @Override public void surfaceDestroyed( SurfaceHolder holder ) { // Called when we lose the surface Log.i( "GameSurface", "surfaceDestroyed: " ); // The core is about to shut down, notify the listener if( mClListener != null ) mClListener.onCoreShutdown(); // Tell the core to quit NativeMethods.quit(); // Now wait for the core thread to quit if( mCoreThread != null ) { try { mCoreThread.join(); } catch( Exception e ) { Log.i( "GameSurface", "Problem stopping core thread: " + e ); } mCoreThread = null; } } @Override public void onDraw( Canvas canvas ) { // Unused, suppress the super method } // EGL functions public boolean initEGL( int majorVersion, int minorVersion ) { Log.v( "GameSurface", "Starting up OpenGL ES " + majorVersion + "." + minorVersion ); try { final int EGL_OPENGL_ES_BIT = 1; final int EGL_OPENGL_ES2_BIT = 4; final int[] version = new int[2]; final int[] configSpec; // Get EGL instance. EGL10 egl = (EGL10) EGLContext.getEGL(); // Now get an EGL display connection for the native display EGLDisplay dpy = egl.eglGetDisplay( EGL10.EGL_DEFAULT_DISPLAY ); // Now initialize the EGL display. egl.eglInitialize( dpy, version ); int renderableType = 0; if( majorVersion == 2 ) { renderableType = EGL_OPENGL_ES2_BIT; } else if( majorVersion == 1 ) { renderableType = EGL_OPENGL_ES_BIT; } // @formatter:off if( mIsRgba8888 ) { configSpec = new int[] { EGL10.EGL_RED_SIZE, 8, // get a config with 8 bits of red EGL10.EGL_GREEN_SIZE, 8, // get a config with 8 bits of green EGL10.EGL_BLUE_SIZE, 8, // get a config with 8 bits of blue EGL10.EGL_ALPHA_SIZE, 8, // get a config with 8 bits of alpha - EGL10.EGL_DEPTH_SIZE, 16, // get a config with a 16-bit depth color buffer + EGL10.EGL_DEPTH_SIZE, 16, // get a config with 16 bits of Z in the depth buffer EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE }; } else { configSpec = new int[] { - EGL10.EGL_DEPTH_SIZE, 16, // get a config with a 16-bit depth color buffer. + EGL10.EGL_DEPTH_SIZE, 16, // get a config with 16-bits of Z in the depth buffer. EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE }; } final EGLConfig[] configs = new EGLConfig[1]; final int[] num_config = new int[1]; // If none of the EGL framebuffer configs correspond to our attributes, then we stop initializing. if( !egl.eglChooseConfig( dpy, configSpec, configs, 1, num_config ) || num_config[0] == 0 ) { Log.e( "GameSurface", "No EGL config available" ); return false; } // @formatter:on EGLConfig config = configs[0]; // paulscode, GLES2 fix: int EGL_CONTEXT_CLIENT_VERSION = 0x3098; int[] contextAttrs = new int[] { EGL_CONTEXT_CLIENT_VERSION, majorVersion, EGL10.EGL_NONE }; EGLContext ctx = egl.eglCreateContext( dpy, config, EGL10.EGL_NO_CONTEXT, contextAttrs ); // end GLES2 fix // EGLContext ctx = egl.eglCreateContext( dpy, config, EGL10.EGL_NO_CONTEXT, null ); if( ctx.equals( EGL10.EGL_NO_CONTEXT ) ) { Log.e( "GameSurface", "Couldn't create context" ); return false; } EGLSurface surface = egl.eglCreateWindowSurface( dpy, config, this, null ); if( surface.equals( EGL10.EGL_NO_SURFACE ) ) { Log.e( "GameSurface", "Couldn't create surface" ); return false; } if( !egl.eglMakeCurrent( dpy, surface, surface, ctx ) ) { Log.e( "GameSurface", "Couldn't make context current" ); return false; } mEGLDisplay = dpy; mEGLSurface = surface; } catch( Exception e ) { Log.v( "GameSurface", e.toString() ); for( StackTraceElement s : e.getStackTrace() ) { Log.v( "GameSurface", s.toString() ); } } return true; } // EGL buffer flip public void flipEGL() { try { // Get an EGL instance. EGL10 egl = (EGL10) EGLContext.getEGL(); // Make sure native-side executions complete before // doing any further GL rendering calls. egl.eglWaitNative( EGL10.EGL_CORE_NATIVE_ENGINE, null ); //-- Drawing here --// // Make sure all GL executions are complete before // doing any further native-side rendering calls. egl.eglWaitGL(); // Now finally 'flip' the buffer. egl.eglSwapBuffers( mEGLDisplay, mEGLSurface ); } catch( Exception e ) { Log.v( "GameSurface", "flipEGL(): " + e ); for( StackTraceElement s : e.getStackTrace() ) { Log.v( "GameSurface", s.toString() ); } } // Update frame rate info if( mIsFpsEnabled ) { mFrameCount++; if( mFrameCount >= mFpsRecalcPeriod && mFpsListener != null ) { long currentTime = System.currentTimeMillis(); float fFPS = ( (float) mFrameCount / (float) ( currentTime - mLastFpsTime ) ) * 1000.0f; mFpsListener.onFpsChanged( Math.round( fFPS ) ); mFrameCount = 0; mLastFpsTime = currentTime; } } } }
false
true
public boolean initEGL( int majorVersion, int minorVersion ) { Log.v( "GameSurface", "Starting up OpenGL ES " + majorVersion + "." + minorVersion ); try { final int EGL_OPENGL_ES_BIT = 1; final int EGL_OPENGL_ES2_BIT = 4; final int[] version = new int[2]; final int[] configSpec; // Get EGL instance. EGL10 egl = (EGL10) EGLContext.getEGL(); // Now get an EGL display connection for the native display EGLDisplay dpy = egl.eglGetDisplay( EGL10.EGL_DEFAULT_DISPLAY ); // Now initialize the EGL display. egl.eglInitialize( dpy, version ); int renderableType = 0; if( majorVersion == 2 ) { renderableType = EGL_OPENGL_ES2_BIT; } else if( majorVersion == 1 ) { renderableType = EGL_OPENGL_ES_BIT; } // @formatter:off if( mIsRgba8888 ) { configSpec = new int[] { EGL10.EGL_RED_SIZE, 8, // get a config with 8 bits of red EGL10.EGL_GREEN_SIZE, 8, // get a config with 8 bits of green EGL10.EGL_BLUE_SIZE, 8, // get a config with 8 bits of blue EGL10.EGL_ALPHA_SIZE, 8, // get a config with 8 bits of alpha EGL10.EGL_DEPTH_SIZE, 16, // get a config with a 16-bit depth color buffer EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE }; } else { configSpec = new int[] { EGL10.EGL_DEPTH_SIZE, 16, // get a config with a 16-bit depth color buffer. EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE }; } final EGLConfig[] configs = new EGLConfig[1]; final int[] num_config = new int[1]; // If none of the EGL framebuffer configs correspond to our attributes, then we stop initializing. if( !egl.eglChooseConfig( dpy, configSpec, configs, 1, num_config ) || num_config[0] == 0 ) { Log.e( "GameSurface", "No EGL config available" ); return false; } // @formatter:on EGLConfig config = configs[0]; // paulscode, GLES2 fix: int EGL_CONTEXT_CLIENT_VERSION = 0x3098; int[] contextAttrs = new int[] { EGL_CONTEXT_CLIENT_VERSION, majorVersion, EGL10.EGL_NONE }; EGLContext ctx = egl.eglCreateContext( dpy, config, EGL10.EGL_NO_CONTEXT, contextAttrs ); // end GLES2 fix // EGLContext ctx = egl.eglCreateContext( dpy, config, EGL10.EGL_NO_CONTEXT, null ); if( ctx.equals( EGL10.EGL_NO_CONTEXT ) ) { Log.e( "GameSurface", "Couldn't create context" ); return false; } EGLSurface surface = egl.eglCreateWindowSurface( dpy, config, this, null ); if( surface.equals( EGL10.EGL_NO_SURFACE ) ) { Log.e( "GameSurface", "Couldn't create surface" ); return false; } if( !egl.eglMakeCurrent( dpy, surface, surface, ctx ) ) { Log.e( "GameSurface", "Couldn't make context current" ); return false; } mEGLDisplay = dpy; mEGLSurface = surface; } catch( Exception e ) { Log.v( "GameSurface", e.toString() ); for( StackTraceElement s : e.getStackTrace() ) { Log.v( "GameSurface", s.toString() ); } } return true; }
public boolean initEGL( int majorVersion, int minorVersion ) { Log.v( "GameSurface", "Starting up OpenGL ES " + majorVersion + "." + minorVersion ); try { final int EGL_OPENGL_ES_BIT = 1; final int EGL_OPENGL_ES2_BIT = 4; final int[] version = new int[2]; final int[] configSpec; // Get EGL instance. EGL10 egl = (EGL10) EGLContext.getEGL(); // Now get an EGL display connection for the native display EGLDisplay dpy = egl.eglGetDisplay( EGL10.EGL_DEFAULT_DISPLAY ); // Now initialize the EGL display. egl.eglInitialize( dpy, version ); int renderableType = 0; if( majorVersion == 2 ) { renderableType = EGL_OPENGL_ES2_BIT; } else if( majorVersion == 1 ) { renderableType = EGL_OPENGL_ES_BIT; } // @formatter:off if( mIsRgba8888 ) { configSpec = new int[] { EGL10.EGL_RED_SIZE, 8, // get a config with 8 bits of red EGL10.EGL_GREEN_SIZE, 8, // get a config with 8 bits of green EGL10.EGL_BLUE_SIZE, 8, // get a config with 8 bits of blue EGL10.EGL_ALPHA_SIZE, 8, // get a config with 8 bits of alpha EGL10.EGL_DEPTH_SIZE, 16, // get a config with 16 bits of Z in the depth buffer EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE }; } else { configSpec = new int[] { EGL10.EGL_DEPTH_SIZE, 16, // get a config with 16-bits of Z in the depth buffer. EGL10.EGL_RENDERABLE_TYPE, renderableType, EGL10.EGL_NONE }; } final EGLConfig[] configs = new EGLConfig[1]; final int[] num_config = new int[1]; // If none of the EGL framebuffer configs correspond to our attributes, then we stop initializing. if( !egl.eglChooseConfig( dpy, configSpec, configs, 1, num_config ) || num_config[0] == 0 ) { Log.e( "GameSurface", "No EGL config available" ); return false; } // @formatter:on EGLConfig config = configs[0]; // paulscode, GLES2 fix: int EGL_CONTEXT_CLIENT_VERSION = 0x3098; int[] contextAttrs = new int[] { EGL_CONTEXT_CLIENT_VERSION, majorVersion, EGL10.EGL_NONE }; EGLContext ctx = egl.eglCreateContext( dpy, config, EGL10.EGL_NO_CONTEXT, contextAttrs ); // end GLES2 fix // EGLContext ctx = egl.eglCreateContext( dpy, config, EGL10.EGL_NO_CONTEXT, null ); if( ctx.equals( EGL10.EGL_NO_CONTEXT ) ) { Log.e( "GameSurface", "Couldn't create context" ); return false; } EGLSurface surface = egl.eglCreateWindowSurface( dpy, config, this, null ); if( surface.equals( EGL10.EGL_NO_SURFACE ) ) { Log.e( "GameSurface", "Couldn't create surface" ); return false; } if( !egl.eglMakeCurrent( dpy, surface, surface, ctx ) ) { Log.e( "GameSurface", "Couldn't make context current" ); return false; } mEGLDisplay = dpy; mEGLSurface = surface; } catch( Exception e ) { Log.v( "GameSurface", e.toString() ); for( StackTraceElement s : e.getStackTrace() ) { Log.v( "GameSurface", s.toString() ); } } return true; }
diff --git a/phone/com/android/internal/policy/impl/LockScreen.java b/phone/com/android/internal/policy/impl/LockScreen.java index 311f201..618771f 100644 --- a/phone/com/android/internal/policy/impl/LockScreen.java +++ b/phone/com/android/internal/policy/impl/LockScreen.java @@ -1,973 +1,975 @@ /* * 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 com.android.internal.policy.impl; import com.android.internal.R; import com.android.internal.telephony.IccCard; import com.android.internal.widget.LockPatternUtils; import com.android.internal.widget.SlidingTab; import com.android.internal.widget.SlidingTab.OnTriggerListener; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.ColorStateList; import android.media.AudioManager; import android.text.format.DateFormat; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import android.graphics.drawable.Drawable; import android.util.Log; import android.os.Environment; import android.os.SystemClock; import android.os.SystemProperties; import android.provider.Settings; import android.gesture.Gesture; import android.gesture.GestureLibraries; import android.gesture.GestureLibrary; import android.gesture.GestureOverlayView; import android.gesture.Prediction; import android.gesture.GestureOverlayView.OnGesturePerformedListener; import java.util.ArrayList; import java.util.Date; import java.io.File; import java.net.URISyntaxException; /** * The screen within {@link LockPatternKeyguardView} that shows general * information about the device depending on its state, and how to get * past it, as applicable. */ class LockScreen extends LinearLayout implements KeyguardScreen, KeyguardUpdateMonitor.InfoCallback, KeyguardUpdateMonitor.SimStateCallback, SlidingTab.OnTriggerListener, OnGesturePerformedListener { private static final boolean DBG = false; private static final String TAG = "LockScreen"; private static final String ENABLE_MENU_KEY_FILE = "/data/local/enable_menu_key"; private Status mStatus = Status.Normal; private final LockPatternUtils mLockPatternUtils; private final KeyguardUpdateMonitor mUpdateMonitor; private final KeyguardScreenCallback mCallback; private TextView mCarrier; private SlidingTab mSelector; private SlidingTab mSelector2; private TextView mTime; private TextView mDate; private TextView mStatus1; private TextView mStatus2; private TextView mScreenLocked; private TextView mEmergencyCallText; private Button mEmergencyCallButton; private ImageButton mPlayIcon; private ImageButton mPauseIcon; private ImageButton mRewindIcon; private ImageButton mForwardIcon; private AudioManager am = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE); private boolean mWasMusicActive = am.isMusicActive(); private boolean mIsMusicActive = false; private GestureLibrary mLibrary; private TextView mCustomMsg; // current configuration state of keyboard and display private int mKeyboardHidden; private int mCreationOrientation; // are we showing battery information? private boolean mShowingBatteryInfo = false; // last known plugged in state private boolean mPluggedIn = false; // last known battery level private int mBatteryLevel = 100; private String mNextAlarm = null; private Drawable mAlarmIcon = null; private String mCharging = null; private Drawable mChargingIcon = null; private boolean mSilentMode; private AudioManager mAudioManager; private String mDateFormatString; private java.text.DateFormat mTimeFormat; private boolean mEnableMenuKeyInLockScreen; private static boolean mShowSpnPref; private static boolean mShowPlmnPref; private boolean mTrackballUnlockScreen = (Settings.System.getInt(mContext.getContentResolver(), Settings.System.TRACKBALL_UNLOCK_SCREEN, 0) == 1); private boolean mMenuUnlockScreen = (Settings.System.getInt(mContext.getContentResolver(), Settings.System.MENU_UNLOCK_SCREEN, 0) == 1); private boolean mLockMusicControls = (Settings.System.getInt(mContext.getContentResolver(), Settings.System.LOCKSCREEN_MUSIC_CONTROLS, 1) == 1); private boolean mLockAlwaysMusic = (Settings.System.getInt(mContext.getContentResolver(), Settings.System.LOCKSCREEN_ALWAYS_MUSIC_CONTROLS, 0) == 1); private boolean mLockPhoneMessagingTab = (Settings.System.getInt(mContext.getContentResolver(), Settings.System.LOCKSCREEN_PHONE_MESSAGING_TAB, 0) == 1); private String mMessagingTabApp = (Settings.System.getString(mContext.getContentResolver(), Settings.System.LOCKSCREEN_MESSAGING_TAB_APP)); private double mGestureSensitivity; private boolean mGestureTrail; private boolean mGestureActive; private boolean mHideUnlockTab; private int mGestureColor; /** * The status of this lock screen. */ enum Status { /** * Normal case (sim card present, it's not locked) */ Normal(true), /** * The sim card is 'network locked'. */ NetworkLocked(true), /** * The sim card is missing. */ SimMissing(false), /** * The sim card is missing, and this is the device isn't provisioned, so we don't let * them get past the screen. */ SimMissingLocked(false), /** * The sim card is PUK locked, meaning they've entered the wrong sim unlock code too many * times. */ SimPukLocked(false), /** * The sim card is locked. */ SimLocked(true); private final boolean mShowStatusLines; Status(boolean mShowStatusLines) { this.mShowStatusLines = mShowStatusLines; } /** * @return Whether the status lines (battery level and / or next alarm) are shown while * in this state. Mostly dictated by whether this is room for them. */ public boolean showStatusLines() { return mShowStatusLines; } } /** * In general, we enable unlocking the insecure key guard with the menu key. However, there are * some cases where we wish to disable it, notably when the menu button placement or technology * is prone to false positives. * * @return true if the menu key should be enabled */ private boolean shouldEnableMenuKey() { final Resources res = getResources(); final boolean configDisabled = res.getBoolean(R.bool.config_disableMenuKeyInLockScreen); final boolean isMonkey = SystemProperties.getBoolean("ro.monkey", false); final boolean fileOverride = (new File(ENABLE_MENU_KEY_FILE)).exists(); return !configDisabled || isMonkey || fileOverride; } /** * @param context Used to setup the view. * @param configuration The current configuration. Used to use when selecting layout, etc. * @param lockPatternUtils Used to know the state of the lock pattern settings. * @param updateMonitor Used to register for updates on various keyguard related * state, and query the initial state at setup. * @param callback Used to communicate back to the host keyguard view. */ LockScreen(Context context, Configuration configuration, LockPatternUtils lockPatternUtils, KeyguardUpdateMonitor updateMonitor, KeyguardScreenCallback callback) { super(context); mLockPatternUtils = lockPatternUtils; mUpdateMonitor = updateMonitor; mCallback = callback; mShowSpnPref = (Settings.System.getInt(context.getContentResolver(), Settings.System.SHOW_SPN_LS, 1) == 1); mShowPlmnPref = (Settings.System.getInt(context.getContentResolver(), Settings.System.SHOW_PLMN_LS, 1) == 1); mEnableMenuKeyInLockScreen = shouldEnableMenuKey(); mCreationOrientation = configuration.orientation; mKeyboardHidden = configuration.hardKeyboardHidden; if (LockPatternKeyguardView.DEBUG_CONFIGURATION) { Log.v(TAG, "***** CREATING LOCK SCREEN", new RuntimeException()); Log.v(TAG, "Cur orient=" + mCreationOrientation + " res orient=" + context.getResources().getConfiguration().orientation); } final LayoutInflater inflater = LayoutInflater.from(context); if (DBG) Log.v(TAG, "Creation orientation = " + mCreationOrientation); if (mCreationOrientation != Configuration.ORIENTATION_LANDSCAPE) { inflater.inflate(R.layout.keyguard_screen_tab_unlock, this, true); } else { inflater.inflate(R.layout.keyguard_screen_tab_unlock_land, this, true); } mCarrier = (TextView) findViewById(R.id.carrier); // Required for Marquee to work mCarrier.setSelected(true); mCarrier.setTextColor(0xffffffff); mDate = (TextView) findViewById(R.id.date); mStatus1 = (TextView) findViewById(R.id.status1); mStatus2 = (TextView) findViewById(R.id.status2); mCustomMsg = (TextView) findViewById(R.id.customMsg); if (mCustomMsg != null) { if (mLockPatternUtils.isShowCustomMsg()) { mCustomMsg.setVisibility(View.VISIBLE); mCustomMsg.setText(mLockPatternUtils.getCustomMsg()); mCustomMsg.setTextColor(mLockPatternUtils.getCustomMsgColor()); } else { mCustomMsg.setVisibility(View.GONE); } } mPlayIcon = (ImageButton) findViewById(R.id.musicControlPlay); mPauseIcon = (ImageButton) findViewById(R.id.musicControlPause); mRewindIcon = (ImageButton) findViewById(R.id.musicControlPrevious); mForwardIcon = (ImageButton) findViewById(R.id.musicControlNext); mScreenLocked = (TextView) findViewById(R.id.screenLocked); mSelector = (SlidingTab) findViewById(R.id.tab_selector); mSelector.setHoldAfterTrigger(true, false); mSelector.setLeftHintText(R.string.lockscreen_unlock_label); mSelector2 = (SlidingTab) findViewById(R.id.tab_selector2); if (mSelector2 != null) { mSelector2.setHoldAfterTrigger(true, false); mSelector2.setLeftHintText(R.string.lockscreen_phone_label); mSelector2.setRightHintText(R.string.lockscreen_messaging_label); } mEmergencyCallText = (TextView) findViewById(R.id.emergencyCallText); mEmergencyCallButton = (Button) findViewById(R.id.emergencyCallButton); mEmergencyCallButton.setText(R.string.lockscreen_emergency_call); mLockPatternUtils.updateEmergencyCallButtonState(mEmergencyCallButton); mEmergencyCallButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.takeEmergencyCallAction(); } }); mPlayIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); refreshMusicStatus(); if(!am.isMusicActive()) { mPauseIcon.setVisibility(View.VISIBLE); mPlayIcon.setVisibility(View.GONE); mRewindIcon.setVisibility(View.VISIBLE); mForwardIcon.setVisibility(View.VISIBLE); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE); } } }); mPauseIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); refreshMusicStatus(); if(am.isMusicActive()) { mPlayIcon.setVisibility(View.VISIBLE); mPauseIcon.setVisibility(View.GONE); mRewindIcon.setVisibility(View.GONE); mForwardIcon.setVisibility(View.GONE); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE); } } }); mRewindIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PREVIOUS); } }); mForwardIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_NEXT); } }); setFocusable(true); setFocusableInTouchMode(true); setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); updateMonitor.registerInfoCallback(this); updateMonitor.registerSimStateCallback(this); mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE); mSilentMode = isSilentMode(); mSelector.setLeftTabResources( R.drawable.ic_jog_dial_unlock, R.drawable.jog_tab_target_green, R.drawable.jog_tab_bar_left_unlock, R.drawable.jog_tab_left_unlock); updateRightTabResources(); mSelector.setOnTriggerListener(this); if (mSelector2 != null) { mSelector2.setLeftTabResources( R.drawable.ic_jog_dial_answer, R.drawable.jog_tab_target_green, R.drawable.jog_tab_bar_left_generic, R.drawable.jog_tab_left_generic); mSelector2.setRightTabResources( R.drawable.ic_jog_dial_messaging, R.drawable.jog_tab_target_green, R.drawable.jog_tab_bar_right_generic, R.drawable.jog_tab_right_generic); mSelector2.setOnTriggerListener(new OnTriggerListener() { public void onTrigger(View v, int whichHandle) { if (whichHandle == SlidingTab.OnTriggerListener.LEFT_HANDLE) { Intent callIntent = new Intent(Intent.ACTION_DIAL); callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getContext().startActivity(callIntent); mCallback.goToUnlockScreen(); } else if (whichHandle == SlidingTab.OnTriggerListener.RIGHT_HANDLE){ if (mMessagingTabApp != null) { try { Intent i = Intent.parseUri(mMessagingTabApp, 0); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mContext.startActivity(i); mCallback.goToUnlockScreen(); } catch (URISyntaxException e) { } catch (ActivityNotFoundException e) { } } } } @Override public void onGrabbedStateChange(View v, int grabbedState) { mCallback.pokeWakelock(); } }); }; mGestureActive = (Settings.System.getInt(context.getContentResolver(), Settings.System.LOCKSCREEN_GESTURES_ENABLED, 0) == 1); mGestureTrail = (Settings.System.getInt(context.getContentResolver(), Settings.System.LOCKSCREEN_GESTURES_TRAIL, 0) == 1); mGestureColor = Settings.System.getInt(context.getContentResolver(), Settings.System.LOCKSCREEN_GESTURES_COLOR, 0xFFFFFF00); boolean prefHideUnlockTab = (Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCKSCREEN_GESTURES_DISABLE_UNLOCK, 0) == 1); if (!mGestureActive) { mGestureTrail = false; } GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures); gestures.setGestureVisible(mGestureTrail); gestures.setGestureColor(mGestureColor); boolean GestureCanUnlock = false; - if (mGestureActive) { - File mStoreFile = new File(Environment.getDataDirectory(), "/misc/lockscreen_gestures"); - mGestureSensitivity = Settings.System.getInt(context.getContentResolver(), - Settings.System.LOCKSCREEN_GESTURES_SENSITIVITY, 3); - mLibrary = GestureLibraries.fromFile(mStoreFile); - if (mLibrary.load()) { - gestures.addOnGesturePerformedListener(this); - for (String name : mLibrary.getGestureEntries()) { - if ("UNLOCK___UNLOCK".equals(name)) { - GestureCanUnlock = true; - break; + if (gestures != null) { + if (mGestureActive) { + File mStoreFile = new File(Environment.getDataDirectory(), "/misc/lockscreen_gestures"); + mGestureSensitivity = Settings.System.getInt(context.getContentResolver(), + Settings.System.LOCKSCREEN_GESTURES_SENSITIVITY, 3); + mLibrary = GestureLibraries.fromFile(mStoreFile); + if (mLibrary.load()) { + gestures.addOnGesturePerformedListener(this); + for (String name : mLibrary.getGestureEntries()) { + if ("UNLOCK___UNLOCK".equals(name)) { + GestureCanUnlock = true; + break; + } } } } } // Safety check in case our preferences in CMParts for hiding the unlock tab don't properly update // system settings... ALWAYS provide a way to unlock the phone if (prefHideUnlockTab && (GestureCanUnlock || mTrackballUnlockScreen || mMenuUnlockScreen)) { mHideUnlockTab = true; } else { mHideUnlockTab = false; } resetStatusInfo(updateMonitor); } private boolean isSilentMode() { return mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL; } private void updateRightTabResources() { boolean vibe = mSilentMode && (mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE); mSelector.setRightTabResources( mSilentMode ? ( vibe ? R.drawable.ic_jog_dial_vibrate_on : R.drawable.ic_jog_dial_sound_off ) : R.drawable.ic_jog_dial_sound_on, mSilentMode ? R.drawable.jog_tab_target_yellow : R.drawable.jog_tab_target_gray, mSilentMode ? R.drawable.jog_tab_bar_right_sound_on : R.drawable.jog_tab_bar_right_sound_off, mSilentMode ? R.drawable.jog_tab_right_sound_on : R.drawable.jog_tab_right_sound_off); } private void resetStatusInfo(KeyguardUpdateMonitor updateMonitor) { mShowingBatteryInfo = updateMonitor.shouldShowBatteryInfo(); mPluggedIn = updateMonitor.isDevicePluggedIn(); mBatteryLevel = updateMonitor.getBatteryLevel(); mIsMusicActive = am.isMusicActive(); mStatus = getCurrentStatus(updateMonitor.getSimState()); updateLayout(mStatus); refreshBatteryStringAndIcon(); refreshAlarmDisplay(); refreshMusicStatus(); mTimeFormat = DateFormat.getTimeFormat(getContext()); mDateFormatString = getContext().getString(R.string.full_wday_month_day_no_year); refreshTimeAndDateDisplay(); updateStatusLines(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER && mTrackballUnlockScreen) || (keyCode == KeyEvent.KEYCODE_MENU && mMenuUnlockScreen) || (keyCode == KeyEvent.KEYCODE_MENU && mEnableMenuKeyInLockScreen)) { mCallback.goToUnlockScreen(); } return false; } /** {@inheritDoc} */ public void onTrigger(View v, int whichHandle) { if (whichHandle == SlidingTab.OnTriggerListener.LEFT_HANDLE) { mCallback.goToUnlockScreen(); } else if (whichHandle == SlidingTab.OnTriggerListener.RIGHT_HANDLE) { // toggle silent mode toggleSilentMode(); updateRightTabResources(); String message = mSilentMode ? getContext().getString(R.string.global_action_silent_mode_on_status) : getContext().getString(R.string.global_action_silent_mode_off_status); final int toastIcon = mSilentMode ? R.drawable.ic_lock_ringer_off : R.drawable.ic_lock_ringer_on; final int toastColor = mSilentMode ? getContext().getResources().getColor(R.color.keyguard_text_color_soundoff) : getContext().getResources().getColor(R.color.keyguard_text_color_soundon); toastMessage(mScreenLocked, message, toastColor, toastIcon); mCallback.pokeWakelock(); } } /** {@inheritDoc} */ public void onGrabbedStateChange(View v, int grabbedState) { if (grabbedState == SlidingTab.OnTriggerListener.RIGHT_HANDLE) { mSilentMode = isSilentMode(); mSelector.setRightHintText(mSilentMode ? R.string.lockscreen_sound_on_label : R.string.lockscreen_sound_off_label); } mCallback.pokeWakelock(); } /** * Displays a message in a text view and then restores the previous text. * @param textView The text view. * @param text The text. * @param color The color to apply to the text, or 0 if the existing color should be used. * @param iconResourceId The left hand icon. */ private void toastMessage(final TextView textView, final String text, final int color, final int iconResourceId) { if (mPendingR1 != null) { textView.removeCallbacks(mPendingR1); mPendingR1 = null; } if (mPendingR2 != null) { mPendingR2.run(); // fire immediately, restoring non-toasted appearance textView.removeCallbacks(mPendingR2); mPendingR2 = null; } final String oldText = textView.getText().toString(); final ColorStateList oldColors = textView.getTextColors(); mPendingR1 = new Runnable() { public void run() { textView.setText(text); if (color != 0) { textView.setTextColor(color); } textView.setCompoundDrawablesWithIntrinsicBounds(iconResourceId, 0, 0, 0); } }; textView.postDelayed(mPendingR1, 0); mPendingR2 = new Runnable() { public void run() { textView.setText(oldText); textView.setTextColor(oldColors); textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); } }; textView.postDelayed(mPendingR2, 3500); } private Runnable mPendingR1; private Runnable mPendingR2; private void refreshAlarmDisplay() { mNextAlarm = mLockPatternUtils.getNextAlarm(); if (mNextAlarm != null) { mAlarmIcon = getContext().getResources().getDrawable(R.drawable.ic_lock_idle_alarm); } updateStatusLines(); } /** {@inheritDoc} */ public void onRefreshBatteryInfo(boolean showBatteryInfo, boolean pluggedIn, int batteryLevel) { if (DBG) Log.d(TAG, "onRefreshBatteryInfo(" + showBatteryInfo + ", " + pluggedIn + ")"); mShowingBatteryInfo = showBatteryInfo; mPluggedIn = pluggedIn; mBatteryLevel = batteryLevel; refreshBatteryStringAndIcon(); updateStatusLines(); } private void refreshBatteryStringAndIcon() { if (!mShowingBatteryInfo) { mCharging = null; return; } if (mChargingIcon == null) { mChargingIcon = getContext().getResources().getDrawable(R.drawable.ic_lock_idle_charging); } if (mPluggedIn) { if (mBatteryLevel >= 100) { mCharging = getContext().getString(R.string.lockscreen_charged); } else { mCharging = getContext().getString(R.string.lockscreen_plugged_in, mBatteryLevel); } } else { mCharging = getContext().getString(R.string.lockscreen_low_battery); } } private void refreshMusicStatus() { if ((mWasMusicActive || mIsMusicActive || mLockAlwaysMusic) && (mLockMusicControls)) { if(am.isMusicActive()) { mPauseIcon.setVisibility(View.VISIBLE); mPlayIcon.setVisibility(View.GONE); mRewindIcon.setVisibility(View.VISIBLE); mForwardIcon.setVisibility(View.VISIBLE); } else { mPlayIcon.setVisibility(View.VISIBLE); mPauseIcon.setVisibility(View.GONE); mRewindIcon.setVisibility(View.GONE); mForwardIcon.setVisibility(View.GONE); } } else { mPlayIcon.setVisibility(View.GONE); mPauseIcon.setVisibility(View.GONE); mRewindIcon.setVisibility(View.GONE); mForwardIcon.setVisibility(View.GONE); } } private void sendMediaButtonEvent(int code) { long eventtime = SystemClock.uptimeMillis(); Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, code, 0); downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent); getContext().sendOrderedBroadcast(downIntent, null); Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, code, 0); upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent); getContext().sendOrderedBroadcast(upIntent, null); } /** {@inheritDoc} */ public void onTimeChanged() { refreshTimeAndDateDisplay(); } private void refreshTimeAndDateDisplay() { mDate.setText(DateFormat.format(mDateFormatString, new Date())); } private void updateStatusLines() { if (!mStatus.showStatusLines() || (mCharging == null && mNextAlarm == null)) { mStatus1.setVisibility(View.INVISIBLE); mStatus2.setVisibility(View.INVISIBLE); } else if (mCharging != null && mNextAlarm == null) { // charging only mStatus1.setVisibility(View.VISIBLE); mStatus2.setVisibility(View.INVISIBLE); mStatus1.setText(mCharging); mStatus1.setCompoundDrawablesWithIntrinsicBounds(mChargingIcon, null, null, null); } else if (mNextAlarm != null && mCharging == null) { // next alarm only mStatus1.setVisibility(View.VISIBLE); mStatus2.setVisibility(View.INVISIBLE); mStatus1.setText(mNextAlarm); mStatus1.setCompoundDrawablesWithIntrinsicBounds(mAlarmIcon, null, null, null); } else if (mCharging != null && mNextAlarm != null) { // both charging and next alarm mStatus1.setVisibility(View.VISIBLE); mStatus2.setVisibility(View.VISIBLE); mStatus1.setText(mCharging); mStatus1.setCompoundDrawablesWithIntrinsicBounds(mChargingIcon, null, null, null); mStatus2.setText(mNextAlarm); mStatus2.setCompoundDrawablesWithIntrinsicBounds(mAlarmIcon, null, null, null); } } /** {@inheritDoc} */ public void onRefreshCarrierInfo(CharSequence plmn, CharSequence spn) { if (DBG) Log.d(TAG, "onRefreshCarrierInfo(" + plmn + ", " + spn + ")"); updateLayout(mStatus); } /** * Determine the current status of the lock screen given the sim state and other stuff. */ private Status getCurrentStatus(IccCard.State simState) { boolean missingAndNotProvisioned = (!mUpdateMonitor.isDeviceProvisioned() && simState == IccCard.State.ABSENT); if (missingAndNotProvisioned) { return Status.SimMissingLocked; } switch (simState) { case ABSENT: return Status.SimMissing; case NETWORK_LOCKED: return Status.SimMissingLocked; case NOT_READY: return Status.SimMissing; case PIN_REQUIRED: return Status.SimLocked; case PUK_REQUIRED: return Status.SimPukLocked; case READY: return Status.Normal; case UNKNOWN: return Status.SimMissing; } return Status.SimMissing; } /** * Update the layout to match the current status. */ private void updateLayout(Status status) { // The emergency call button no longer appears on this screen. if (DBG) Log.d(TAG, "updateLayout: status=" + status); mEmergencyCallButton.setVisibility(View.GONE); // in almost all cases switch (status) { case Normal: // text mCarrier.setText( getCarrierString( mUpdateMonitor.getTelephonyPlmn(), mUpdateMonitor.getTelephonySpn())); // Empty now, but used for sliding tab feedback mScreenLocked.setText(""); // layout mScreenLocked.setVisibility(View.VISIBLE); mSelector.setVisibility(View.VISIBLE); if (mSelector2 != null) { if (mLockPhoneMessagingTab) { mSelector2.setVisibility(View.VISIBLE); } else { mSelector2.setVisibility(View.GONE); } } mEmergencyCallText.setVisibility(View.GONE); break; case NetworkLocked: // The carrier string shows both sim card status (i.e. No Sim Card) and // carrier's name and/or "Emergency Calls Only" status mCarrier.setText( getCarrierString( mUpdateMonitor.getTelephonyPlmn(), getContext().getText(R.string.lockscreen_network_locked_message))); mScreenLocked.setText(R.string.lockscreen_instructions_when_pattern_disabled); // layout mScreenLocked.setVisibility(View.VISIBLE); mSelector.setVisibility(View.VISIBLE); if (mSelector2 != null) { if (mLockPhoneMessagingTab) { mSelector2.setVisibility(View.VISIBLE); } else { mSelector2.setVisibility(View.GONE); } } mEmergencyCallText.setVisibility(View.GONE); break; case SimMissing: // text mCarrier.setText(R.string.lockscreen_missing_sim_message_short); mScreenLocked.setText(R.string.lockscreen_missing_sim_instructions); // layout mScreenLocked.setVisibility(View.VISIBLE); mSelector.setVisibility(View.VISIBLE); if (mSelector2 != null) { mSelector2.setVisibility(View.GONE); } mEmergencyCallText.setVisibility(View.VISIBLE); // do not need to show the e-call button; user may unlock break; case SimMissingLocked: // text mCarrier.setText( getCarrierString( mUpdateMonitor.getTelephonyPlmn(), getContext().getText(R.string.lockscreen_missing_sim_message_short))); mScreenLocked.setText(R.string.lockscreen_missing_sim_instructions); // layout mScreenLocked.setVisibility(View.VISIBLE); mSelector.setVisibility(View.GONE); // cannot unlock if (mSelector2 != null) { mSelector2.setVisibility(View.GONE); } mEmergencyCallText.setVisibility(View.VISIBLE); mEmergencyCallButton.setVisibility(View.VISIBLE); break; case SimLocked: // text mCarrier.setText( getCarrierString( mUpdateMonitor.getTelephonyPlmn(), getContext().getText(R.string.lockscreen_sim_locked_message))); // layout mScreenLocked.setVisibility(View.INVISIBLE); mSelector.setVisibility(View.VISIBLE); if (mSelector2 != null) { mSelector2.setVisibility(View.GONE); } mEmergencyCallText.setVisibility(View.GONE); break; case SimPukLocked: // text mCarrier.setText( getCarrierString( mUpdateMonitor.getTelephonyPlmn(), getContext().getText(R.string.lockscreen_sim_puk_locked_message))); mScreenLocked.setText(R.string.lockscreen_sim_puk_locked_instructions); // layout mScreenLocked.setVisibility(View.VISIBLE); mSelector.setVisibility(View.GONE); // cannot unlock if (mSelector2 != null) { mSelector2.setVisibility(View.GONE); } mEmergencyCallText.setVisibility(View.VISIBLE); mEmergencyCallButton.setVisibility(View.VISIBLE); break; } if (mHideUnlockTab) { mSelector.setVisibility(View.GONE); } } static CharSequence getCarrierString(CharSequence telephonyPlmn, CharSequence telephonySpn) { if (telephonyPlmn != null && (telephonySpn == null || !mShowSpnPref) && mShowPlmnPref) { return telephonyPlmn; } else if (telephonyPlmn != null && telephonySpn != null && mShowPlmnPref && mShowSpnPref) { return telephonyPlmn + "|" + telephonySpn; } else if ((telephonyPlmn == null || !mShowPlmnPref) && telephonySpn != null && mShowSpnPref) { return telephonySpn; } else { return ""; } } public void onSimStateChanged(IccCard.State simState) { if (DBG) Log.d(TAG, "onSimStateChanged(" + simState + ")"); mStatus = getCurrentStatus(simState); updateLayout(mStatus); updateStatusLines(); } void updateConfiguration() { Configuration newConfig = getResources().getConfiguration(); if (newConfig.orientation != mCreationOrientation) { mCallback.recreateMe(newConfig); } else if (newConfig.hardKeyboardHidden != mKeyboardHidden) { mKeyboardHidden = newConfig.hardKeyboardHidden; final boolean isKeyboardOpen = mKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO; if (mUpdateMonitor.isKeyguardBypassEnabled() && isKeyboardOpen) { mCallback.goToUnlockScreen(); } } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (LockPatternKeyguardView.DEBUG_CONFIGURATION) { Log.v(TAG, "***** LOCK ATTACHED TO WINDOW"); Log.v(TAG, "Cur orient=" + mCreationOrientation + ", new config=" + getResources().getConfiguration()); } updateConfiguration(); } /** {@inheritDoc} */ @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (LockPatternKeyguardView.DEBUG_CONFIGURATION) { Log.w(TAG, "***** LOCK CONFIG CHANGING", new RuntimeException()); Log.v(TAG, "Cur orient=" + mCreationOrientation + ", new config=" + newConfig); } updateConfiguration(); } /** {@inheritDoc} */ public boolean needsInput() { return false; } /** {@inheritDoc} */ public void onPause() { } /** {@inheritDoc} */ public void onResume() { resetStatusInfo(mUpdateMonitor); mLockPatternUtils.updateEmergencyCallButtonState(mEmergencyCallButton); } /** {@inheritDoc} */ public void cleanUp() { mUpdateMonitor.removeCallback(this); } /** {@inheritDoc} */ public void onRingerModeChanged(int state) { boolean silent = AudioManager.RINGER_MODE_NORMAL != state; if (silent != mSilentMode) { mSilentMode = silent; updateRightTabResources(); } } public void onPhoneStateChanged(String newState) { mLockPatternUtils.updateEmergencyCallButtonState(mEmergencyCallButton); } public void toggleSilentMode() { mSilentMode = !mSilentMode; if (mSilentMode) { final boolean vibe = (Settings.System.getInt( getContext().getContentResolver(), Settings.System.VIBRATE_IN_SILENT, 1) == 1); mAudioManager.setRingerMode(vibe ? AudioManager.RINGER_MODE_VIBRATE : AudioManager.RINGER_MODE_SILENT); } else { mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL); } } @Override public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) { ArrayList<Prediction> predictions = mLibrary.recognize(gesture); if (predictions.size() > 0 && predictions.get(0).score > mGestureSensitivity) { String[] payload = predictions.get(0).name.split("___", 2); String uri = payload[1]; if (uri != null) { if ("UNLOCK".equals(uri)) { mCallback.goToUnlockScreen(); } else if ("SOUND".equals(uri)) { toggleSilentMode(); mCallback.pokeWakelock(); } else try { Intent i = Intent.parseUri(uri, 0); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mContext.startActivity(i); mCallback.goToUnlockScreen(); } catch (URISyntaxException e) { } catch (ActivityNotFoundException e) { } } } else { mCallback.pokeWakelock(); // reset timeout - give them another chance to gesture } } }
true
true
LockScreen(Context context, Configuration configuration, LockPatternUtils lockPatternUtils, KeyguardUpdateMonitor updateMonitor, KeyguardScreenCallback callback) { super(context); mLockPatternUtils = lockPatternUtils; mUpdateMonitor = updateMonitor; mCallback = callback; mShowSpnPref = (Settings.System.getInt(context.getContentResolver(), Settings.System.SHOW_SPN_LS, 1) == 1); mShowPlmnPref = (Settings.System.getInt(context.getContentResolver(), Settings.System.SHOW_PLMN_LS, 1) == 1); mEnableMenuKeyInLockScreen = shouldEnableMenuKey(); mCreationOrientation = configuration.orientation; mKeyboardHidden = configuration.hardKeyboardHidden; if (LockPatternKeyguardView.DEBUG_CONFIGURATION) { Log.v(TAG, "***** CREATING LOCK SCREEN", new RuntimeException()); Log.v(TAG, "Cur orient=" + mCreationOrientation + " res orient=" + context.getResources().getConfiguration().orientation); } final LayoutInflater inflater = LayoutInflater.from(context); if (DBG) Log.v(TAG, "Creation orientation = " + mCreationOrientation); if (mCreationOrientation != Configuration.ORIENTATION_LANDSCAPE) { inflater.inflate(R.layout.keyguard_screen_tab_unlock, this, true); } else { inflater.inflate(R.layout.keyguard_screen_tab_unlock_land, this, true); } mCarrier = (TextView) findViewById(R.id.carrier); // Required for Marquee to work mCarrier.setSelected(true); mCarrier.setTextColor(0xffffffff); mDate = (TextView) findViewById(R.id.date); mStatus1 = (TextView) findViewById(R.id.status1); mStatus2 = (TextView) findViewById(R.id.status2); mCustomMsg = (TextView) findViewById(R.id.customMsg); if (mCustomMsg != null) { if (mLockPatternUtils.isShowCustomMsg()) { mCustomMsg.setVisibility(View.VISIBLE); mCustomMsg.setText(mLockPatternUtils.getCustomMsg()); mCustomMsg.setTextColor(mLockPatternUtils.getCustomMsgColor()); } else { mCustomMsg.setVisibility(View.GONE); } } mPlayIcon = (ImageButton) findViewById(R.id.musicControlPlay); mPauseIcon = (ImageButton) findViewById(R.id.musicControlPause); mRewindIcon = (ImageButton) findViewById(R.id.musicControlPrevious); mForwardIcon = (ImageButton) findViewById(R.id.musicControlNext); mScreenLocked = (TextView) findViewById(R.id.screenLocked); mSelector = (SlidingTab) findViewById(R.id.tab_selector); mSelector.setHoldAfterTrigger(true, false); mSelector.setLeftHintText(R.string.lockscreen_unlock_label); mSelector2 = (SlidingTab) findViewById(R.id.tab_selector2); if (mSelector2 != null) { mSelector2.setHoldAfterTrigger(true, false); mSelector2.setLeftHintText(R.string.lockscreen_phone_label); mSelector2.setRightHintText(R.string.lockscreen_messaging_label); } mEmergencyCallText = (TextView) findViewById(R.id.emergencyCallText); mEmergencyCallButton = (Button) findViewById(R.id.emergencyCallButton); mEmergencyCallButton.setText(R.string.lockscreen_emergency_call); mLockPatternUtils.updateEmergencyCallButtonState(mEmergencyCallButton); mEmergencyCallButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.takeEmergencyCallAction(); } }); mPlayIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); refreshMusicStatus(); if(!am.isMusicActive()) { mPauseIcon.setVisibility(View.VISIBLE); mPlayIcon.setVisibility(View.GONE); mRewindIcon.setVisibility(View.VISIBLE); mForwardIcon.setVisibility(View.VISIBLE); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE); } } }); mPauseIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); refreshMusicStatus(); if(am.isMusicActive()) { mPlayIcon.setVisibility(View.VISIBLE); mPauseIcon.setVisibility(View.GONE); mRewindIcon.setVisibility(View.GONE); mForwardIcon.setVisibility(View.GONE); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE); } } }); mRewindIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PREVIOUS); } }); mForwardIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_NEXT); } }); setFocusable(true); setFocusableInTouchMode(true); setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); updateMonitor.registerInfoCallback(this); updateMonitor.registerSimStateCallback(this); mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE); mSilentMode = isSilentMode(); mSelector.setLeftTabResources( R.drawable.ic_jog_dial_unlock, R.drawable.jog_tab_target_green, R.drawable.jog_tab_bar_left_unlock, R.drawable.jog_tab_left_unlock); updateRightTabResources(); mSelector.setOnTriggerListener(this); if (mSelector2 != null) { mSelector2.setLeftTabResources( R.drawable.ic_jog_dial_answer, R.drawable.jog_tab_target_green, R.drawable.jog_tab_bar_left_generic, R.drawable.jog_tab_left_generic); mSelector2.setRightTabResources( R.drawable.ic_jog_dial_messaging, R.drawable.jog_tab_target_green, R.drawable.jog_tab_bar_right_generic, R.drawable.jog_tab_right_generic); mSelector2.setOnTriggerListener(new OnTriggerListener() { public void onTrigger(View v, int whichHandle) { if (whichHandle == SlidingTab.OnTriggerListener.LEFT_HANDLE) { Intent callIntent = new Intent(Intent.ACTION_DIAL); callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getContext().startActivity(callIntent); mCallback.goToUnlockScreen(); } else if (whichHandle == SlidingTab.OnTriggerListener.RIGHT_HANDLE){ if (mMessagingTabApp != null) { try { Intent i = Intent.parseUri(mMessagingTabApp, 0); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mContext.startActivity(i); mCallback.goToUnlockScreen(); } catch (URISyntaxException e) { } catch (ActivityNotFoundException e) { } } } } @Override public void onGrabbedStateChange(View v, int grabbedState) { mCallback.pokeWakelock(); } }); }; mGestureActive = (Settings.System.getInt(context.getContentResolver(), Settings.System.LOCKSCREEN_GESTURES_ENABLED, 0) == 1); mGestureTrail = (Settings.System.getInt(context.getContentResolver(), Settings.System.LOCKSCREEN_GESTURES_TRAIL, 0) == 1); mGestureColor = Settings.System.getInt(context.getContentResolver(), Settings.System.LOCKSCREEN_GESTURES_COLOR, 0xFFFFFF00); boolean prefHideUnlockTab = (Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCKSCREEN_GESTURES_DISABLE_UNLOCK, 0) == 1); if (!mGestureActive) { mGestureTrail = false; } GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures); gestures.setGestureVisible(mGestureTrail); gestures.setGestureColor(mGestureColor); boolean GestureCanUnlock = false; if (mGestureActive) { File mStoreFile = new File(Environment.getDataDirectory(), "/misc/lockscreen_gestures"); mGestureSensitivity = Settings.System.getInt(context.getContentResolver(), Settings.System.LOCKSCREEN_GESTURES_SENSITIVITY, 3); mLibrary = GestureLibraries.fromFile(mStoreFile); if (mLibrary.load()) { gestures.addOnGesturePerformedListener(this); for (String name : mLibrary.getGestureEntries()) { if ("UNLOCK___UNLOCK".equals(name)) { GestureCanUnlock = true; break; } } } } // Safety check in case our preferences in CMParts for hiding the unlock tab don't properly update // system settings... ALWAYS provide a way to unlock the phone if (prefHideUnlockTab && (GestureCanUnlock || mTrackballUnlockScreen || mMenuUnlockScreen)) { mHideUnlockTab = true; } else { mHideUnlockTab = false; } resetStatusInfo(updateMonitor); }
LockScreen(Context context, Configuration configuration, LockPatternUtils lockPatternUtils, KeyguardUpdateMonitor updateMonitor, KeyguardScreenCallback callback) { super(context); mLockPatternUtils = lockPatternUtils; mUpdateMonitor = updateMonitor; mCallback = callback; mShowSpnPref = (Settings.System.getInt(context.getContentResolver(), Settings.System.SHOW_SPN_LS, 1) == 1); mShowPlmnPref = (Settings.System.getInt(context.getContentResolver(), Settings.System.SHOW_PLMN_LS, 1) == 1); mEnableMenuKeyInLockScreen = shouldEnableMenuKey(); mCreationOrientation = configuration.orientation; mKeyboardHidden = configuration.hardKeyboardHidden; if (LockPatternKeyguardView.DEBUG_CONFIGURATION) { Log.v(TAG, "***** CREATING LOCK SCREEN", new RuntimeException()); Log.v(TAG, "Cur orient=" + mCreationOrientation + " res orient=" + context.getResources().getConfiguration().orientation); } final LayoutInflater inflater = LayoutInflater.from(context); if (DBG) Log.v(TAG, "Creation orientation = " + mCreationOrientation); if (mCreationOrientation != Configuration.ORIENTATION_LANDSCAPE) { inflater.inflate(R.layout.keyguard_screen_tab_unlock, this, true); } else { inflater.inflate(R.layout.keyguard_screen_tab_unlock_land, this, true); } mCarrier = (TextView) findViewById(R.id.carrier); // Required for Marquee to work mCarrier.setSelected(true); mCarrier.setTextColor(0xffffffff); mDate = (TextView) findViewById(R.id.date); mStatus1 = (TextView) findViewById(R.id.status1); mStatus2 = (TextView) findViewById(R.id.status2); mCustomMsg = (TextView) findViewById(R.id.customMsg); if (mCustomMsg != null) { if (mLockPatternUtils.isShowCustomMsg()) { mCustomMsg.setVisibility(View.VISIBLE); mCustomMsg.setText(mLockPatternUtils.getCustomMsg()); mCustomMsg.setTextColor(mLockPatternUtils.getCustomMsgColor()); } else { mCustomMsg.setVisibility(View.GONE); } } mPlayIcon = (ImageButton) findViewById(R.id.musicControlPlay); mPauseIcon = (ImageButton) findViewById(R.id.musicControlPause); mRewindIcon = (ImageButton) findViewById(R.id.musicControlPrevious); mForwardIcon = (ImageButton) findViewById(R.id.musicControlNext); mScreenLocked = (TextView) findViewById(R.id.screenLocked); mSelector = (SlidingTab) findViewById(R.id.tab_selector); mSelector.setHoldAfterTrigger(true, false); mSelector.setLeftHintText(R.string.lockscreen_unlock_label); mSelector2 = (SlidingTab) findViewById(R.id.tab_selector2); if (mSelector2 != null) { mSelector2.setHoldAfterTrigger(true, false); mSelector2.setLeftHintText(R.string.lockscreen_phone_label); mSelector2.setRightHintText(R.string.lockscreen_messaging_label); } mEmergencyCallText = (TextView) findViewById(R.id.emergencyCallText); mEmergencyCallButton = (Button) findViewById(R.id.emergencyCallButton); mEmergencyCallButton.setText(R.string.lockscreen_emergency_call); mLockPatternUtils.updateEmergencyCallButtonState(mEmergencyCallButton); mEmergencyCallButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.takeEmergencyCallAction(); } }); mPlayIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); refreshMusicStatus(); if(!am.isMusicActive()) { mPauseIcon.setVisibility(View.VISIBLE); mPlayIcon.setVisibility(View.GONE); mRewindIcon.setVisibility(View.VISIBLE); mForwardIcon.setVisibility(View.VISIBLE); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE); } } }); mPauseIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); refreshMusicStatus(); if(am.isMusicActive()) { mPlayIcon.setVisibility(View.VISIBLE); mPauseIcon.setVisibility(View.GONE); mRewindIcon.setVisibility(View.GONE); mForwardIcon.setVisibility(View.GONE); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE); } } }); mRewindIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_PREVIOUS); } }); mForwardIcon.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mCallback.pokeWakelock(); sendMediaButtonEvent(KeyEvent.KEYCODE_MEDIA_NEXT); } }); setFocusable(true); setFocusableInTouchMode(true); setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); updateMonitor.registerInfoCallback(this); updateMonitor.registerSimStateCallback(this); mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE); mSilentMode = isSilentMode(); mSelector.setLeftTabResources( R.drawable.ic_jog_dial_unlock, R.drawable.jog_tab_target_green, R.drawable.jog_tab_bar_left_unlock, R.drawable.jog_tab_left_unlock); updateRightTabResources(); mSelector.setOnTriggerListener(this); if (mSelector2 != null) { mSelector2.setLeftTabResources( R.drawable.ic_jog_dial_answer, R.drawable.jog_tab_target_green, R.drawable.jog_tab_bar_left_generic, R.drawable.jog_tab_left_generic); mSelector2.setRightTabResources( R.drawable.ic_jog_dial_messaging, R.drawable.jog_tab_target_green, R.drawable.jog_tab_bar_right_generic, R.drawable.jog_tab_right_generic); mSelector2.setOnTriggerListener(new OnTriggerListener() { public void onTrigger(View v, int whichHandle) { if (whichHandle == SlidingTab.OnTriggerListener.LEFT_HANDLE) { Intent callIntent = new Intent(Intent.ACTION_DIAL); callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getContext().startActivity(callIntent); mCallback.goToUnlockScreen(); } else if (whichHandle == SlidingTab.OnTriggerListener.RIGHT_HANDLE){ if (mMessagingTabApp != null) { try { Intent i = Intent.parseUri(mMessagingTabApp, 0); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); mContext.startActivity(i); mCallback.goToUnlockScreen(); } catch (URISyntaxException e) { } catch (ActivityNotFoundException e) { } } } } @Override public void onGrabbedStateChange(View v, int grabbedState) { mCallback.pokeWakelock(); } }); }; mGestureActive = (Settings.System.getInt(context.getContentResolver(), Settings.System.LOCKSCREEN_GESTURES_ENABLED, 0) == 1); mGestureTrail = (Settings.System.getInt(context.getContentResolver(), Settings.System.LOCKSCREEN_GESTURES_TRAIL, 0) == 1); mGestureColor = Settings.System.getInt(context.getContentResolver(), Settings.System.LOCKSCREEN_GESTURES_COLOR, 0xFFFFFF00); boolean prefHideUnlockTab = (Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCKSCREEN_GESTURES_DISABLE_UNLOCK, 0) == 1); if (!mGestureActive) { mGestureTrail = false; } GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures); gestures.setGestureVisible(mGestureTrail); gestures.setGestureColor(mGestureColor); boolean GestureCanUnlock = false; if (gestures != null) { if (mGestureActive) { File mStoreFile = new File(Environment.getDataDirectory(), "/misc/lockscreen_gestures"); mGestureSensitivity = Settings.System.getInt(context.getContentResolver(), Settings.System.LOCKSCREEN_GESTURES_SENSITIVITY, 3); mLibrary = GestureLibraries.fromFile(mStoreFile); if (mLibrary.load()) { gestures.addOnGesturePerformedListener(this); for (String name : mLibrary.getGestureEntries()) { if ("UNLOCK___UNLOCK".equals(name)) { GestureCanUnlock = true; break; } } } } } // Safety check in case our preferences in CMParts for hiding the unlock tab don't properly update // system settings... ALWAYS provide a way to unlock the phone if (prefHideUnlockTab && (GestureCanUnlock || mTrackballUnlockScreen || mMenuUnlockScreen)) { mHideUnlockTab = true; } else { mHideUnlockTab = false; } resetStatusInfo(updateMonitor); }
diff --git a/examples/TestMonitor/ExplicitTestMonitor.java b/examples/TestMonitor/ExplicitTestMonitor.java index ab7258a..1ca4bca 100644 --- a/examples/TestMonitor/ExplicitTestMonitor.java +++ b/examples/TestMonitor/ExplicitTestMonitor.java @@ -1,41 +1,40 @@ package examples.TestMonitor; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ExplicitTestMonitor extends TestMonitor { final Lock mutex = new ReentrantLock(); Condition[] conds; private int numProc; private int numAccess; public ExplicitTestMonitor(int numProc_) { numProc = numProc_; numAccess = 0; conds = new Condition[numProc]; for(int i = 0; i < numProc; ++i) { conds[i] = mutex.newCondition(); } } public void access(int myId) { setCurrentCpuTime(); mutex.lock(); - addSyncTime(); setCurrentCpuTime(); while((numAccess % numProc) != myId) { try { conds[numAccess % numProc].signal(); conds[myId].await(); } catch(InterruptedException e) { } } addSyncTime(); //System.out.println("myId: " + myId_dummy + " numAccess: " + numAccess); ++numAccess; conds[numAccess % numProc].signal(); mutex.unlock(); } }
true
true
public void access(int myId) { setCurrentCpuTime(); mutex.lock(); addSyncTime(); setCurrentCpuTime(); while((numAccess % numProc) != myId) { try { conds[numAccess % numProc].signal(); conds[myId].await(); } catch(InterruptedException e) { } } addSyncTime(); //System.out.println("myId: " + myId_dummy + " numAccess: " + numAccess); ++numAccess; conds[numAccess % numProc].signal(); mutex.unlock(); }
public void access(int myId) { setCurrentCpuTime(); mutex.lock(); setCurrentCpuTime(); while((numAccess % numProc) != myId) { try { conds[numAccess % numProc].signal(); conds[myId].await(); } catch(InterruptedException e) { } } addSyncTime(); //System.out.println("myId: " + myId_dummy + " numAccess: " + numAccess); ++numAccess; conds[numAccess % numProc].signal(); mutex.unlock(); }
diff --git a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java index ef94acf28..762528be5 100644 --- a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java +++ b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/ProxyService.java @@ -1,607 +1,612 @@ /* * 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.synapse.core.axis2; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.apache.axis2.AxisFault; import org.apache.axis2.description.*; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.wsdl.WSDLConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.neethi.Policy; import org.apache.neethi.PolicyEngine; import org.apache.synapse.Constants; import org.apache.synapse.SynapseException; import org.apache.synapse.mediators.base.SequenceMediator; import org.apache.synapse.endpoints.Endpoint; import org.apache.synapse.config.SynapseConfiguration; import org.apache.synapse.config.Util; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLInputFactory; import java.io.IOException; import java.io.InputStream; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.util.*; import java.net.URI; import java.net.URLConnection; import java.net.MalformedURLException; import java.net.URL; /** * <proxy-service name="string" [transports="(http |https |jms )+|all"]> * <description>..</description>? * <target [inSequence="name"] [outSequence="name"] [faultSequence="name"] [endpoint="name"]> * <endpoint>...</endpoint> * <inSequence>...</inSequence> * <outSequence>...</outSequence> * <faultSequence>...</faultSequence> * </target>? * <publishWSDL uri=".." key="string"> * <wsdl:definition>...</wsdl:definition>? * <wsdl20:description>...</wsdl20:description>? * </publishWSDL>? * <enableSec/>? * <enableRM/>? * <policy key="string">? * // optional service parameters * <parameter name="string"> * text | xml * </parameter>? * </proxy-service> */ public class ProxyService { private static final Log log = LogFactory.getLog(ProxyService.class); private static final Log trace = LogFactory.getLog(Constants.TRACE_LOGGER); /** * The proxy service name */ private String name; /** * The proxy service description */ private String description; /** * The transport/s over which this service should be exposed */ //private String transports; private ArrayList transports; /** * The target endpoint, if assigned */ private String targetEndpoint = null; /** * The target inSequence, if assigned */ private String targetInSequence = null; /** * The target outSequence, if assigned */ private String targetOutSequence = null; /** * The target faultSequence, if assigned */ private String targetFaultSequence = null; /** * The target endpoint, if assigned */ private Endpoint targetInLineEndpoint = null; /** * The target inSequence, if assigned */ private SequenceMediator targetInLineInSequence = null; /** * The target outSequence, if assigned */ private SequenceMediator targetInLineOutSequence = null; /** * The target faultSequence, if assigned */ private SequenceMediator targetInLineFaultSequence = null; // if a target endpoint or sequence is not specified, // the default Synapse main mediator will be used /** * A list parameters */ private Map parameters = new HashMap(); /** * The key for the base WSDL, if specified */ private String wsdlKey; /** * The URI for the base WSDL, if specified */ private URI wsdlURI; /** * Inline XML representation of wsdl */ private Object inLineWSDL; /** * The keys for any supplied schemas */ // todo: do we need this private List schemaKeys = new ArrayList(); /** * The keys for any supplied policies that would apply at the service level */ private List serviceLevelPolicies = new ArrayList(); /** * Should WS RM (default configuration) be engaged on this service */ private boolean wsRMEnabled = false; /** * Should WS Sec (default configuration) be engaged on this service */ private boolean wsSecEnabled = false; /** * This will say weather need to start the service at the load or not */ private boolean startOnLoad = true; /** * This will hold the status of the proxy weather it is running or not */ private boolean running = false; public static final String ALL_TRANSPORTS = "all"; /** * To decide to whether statistics should have collected or not */ private int statisticsEnable = Constants.STATISTICS_UNSET; /** * The variable that indicate tracing on or off for the current mediator */ protected int traceState = Constants.TRACING_UNSET; public ProxyService() { } public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) { AxisService proxyService = null; InputStream wsdlInputStream = null; OMElement wsdlElement = null; if (wsdlKey != null) { Object keyObject = synCfg.getEntry(wsdlKey); if (keyObject instanceof OMElement) { wsdlElement = (OMElement) keyObject; } } else if (inLineWSDL != null) { wsdlElement = (OMElement) inLineWSDL; } else if (wsdlURI != null) { try { URL url = wsdlURI.toURL(); if (url != null) { URLConnection urlc = url.openConnection(); try { if (urlc != null) { XMLStreamReader parser = XMLInputFactory.newInstance(). createXMLStreamReader(urlc.getInputStream()); StAXOMBuilder builder = new StAXOMBuilder(parser); wsdlElement = builder.getDocumentElement(); // detach from URL connection and keep in memory // TODO remove this wsdlElement.build(); } } catch (XMLStreamException e) { log.warn("Content at URL : " + url + " is non XML.."); } } } catch (MalformedURLException e) { handleException("Malformed URI for wsdl", e); } catch (IOException e) { handleException("Error reading from wsdl URI", e); } } if (wsdlElement != null) { OMNamespace wsdlNamespace = wsdlElement.getNamespace(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { wsdlElement.serialize(baos); wsdlInputStream = new ByteArrayInputStream(baos.toByteArray()); } catch (XMLStreamException e) { handleException("Error converting to a StreamSource", e); } if (wsdlInputStream != null) { try { // detect version of the WSDL 1.1 or 2.0 if (wsdlNamespace != null) { WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null; if (WSDL2Constants.WSDL_NAMESPACE. equals(wsdlNamespace.getNamespaceURI())) { wsdlToAxisServiceBuilder = new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null); } else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11. equals(wsdlNamespace.getNamespaceURI())) { wsdlToAxisServiceBuilder = new WSDL11ToAxisServiceBuilder(wsdlInputStream, null, null); } else { handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0"); } if (wsdlToAxisServiceBuilder == null) { throw new SynapseException( "Could not get the WSDL to Axis Service Builder"); } proxyService = wsdlToAxisServiceBuilder.populateService(); proxyService.setWsdlFound(true); } else { handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0"); } } catch (AxisFault af) { handleException("Error building service from WSDL", af); } catch (IOException ioe) { handleException("Error reading WSDL", ioe); } } } else { // this is for POX... create a dummy service and an operation for which // our SynapseDispatcher will properly dispatch to proxyService = new AxisService(); AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate")); proxyService.addOperation(mediateOperation); } // Set the name and description. Currently Axis2 uses the name as the // default Service destination if (proxyService == null) { throw new SynapseException("Could not create a proxy service"); } proxyService.setName(name); if (description != null) { proxyService.setServiceDescription(description); } // process transports and expose over requested transports. If none // is specified, default to all transports using service name as // destination if (transports == null || transports.size() == 0) { // default to all transports using service name as destination } else { proxyService.setExposedTransports(transports); } // process parameters Iterator iter = parameters.keySet().iterator(); while (iter.hasNext()) { String name = (String) iter.next(); Object value = parameters.get(name); Parameter p = new Parameter(); p.setName(name); p.setValue(value); try { proxyService.addParameter(p); } catch (AxisFault af) { handleException("Error setting parameter : " + name + "" + "to proxy service as a Parameter", af); } } // if service level policies are specified, apply them if (!serviceLevelPolicies.isEmpty()) { Policy svcEffectivePolicy = null; iter = serviceLevelPolicies.iterator(); while (iter.hasNext()) { String policyKey = (String) iter.next(); Object policyProp = synCfg.getEntry(policyKey); if (policyProp != null) { if (svcEffectivePolicy == null) { svcEffectivePolicy = PolicyEngine.getPolicy( Util.getStreamSource(policyProp).getInputStream()); } else { svcEffectivePolicy = (Policy) svcEffectivePolicy.merge( PolicyEngine.getPolicy( Util.getStreamSource(policyProp).getInputStream())); } } } PolicyInclude pi = proxyService.getPolicyInclude(); if (pi != null && svcEffectivePolicy != null) { pi.addPolicyElement(PolicyInclude.AXIS_SERVICE_POLICY, svcEffectivePolicy); // todo: check whether the rm or sec is enabled } } // create a custom message receiver for this proxy service ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver(); msgRcvr.setName(name); iter = proxyService.getOperations(); while (iter.hasNext()) { AxisOperation op = (AxisOperation) iter.next(); op.setMessageReceiver(msgRcvr); } try { axisCfg.addService(proxyService); this.setRunning(true); } catch (AxisFault axisFault) { - handleException("Unable to start the Proxy Service"); + try { + if (axisCfg.getService(proxyService.getName()) != null) { + axisCfg.removeService(proxyService.getName()); + } + } catch (AxisFault ignore) {} + handleException("Error adding Proxy service to the Axis2 engine"); } // todo: need to remove this and engage modules by looking at policies // should RM be engaged on this service? if (wsRMEnabled) { try { proxyService.engageModule(axisCfg.getModule( Constants.SANDESHA2_MODULE_NAME), axisCfg); } catch (AxisFault axisFault) { handleException("Error loading WS RM module on proxy service : " + name, axisFault); } } // should Security be engaged on this service? if (wsSecEnabled) { try { proxyService.engageModule(axisCfg.getModule( Constants.RAMPART_MODULE_NAME), axisCfg); } catch (AxisFault axisFault) { handleException("Error loading WS Sec module on proxy service : " + name, axisFault); } } return proxyService; } public void start(SynapseConfiguration synCfg) { AxisConfiguration axisConfig = synCfg.getAxisConfiguration(); axisConfig.getServiceForActivation(this.getName()).setActive(true); this.setRunning(true); } public void stop(SynapseConfiguration synCfg) { AxisConfiguration axisConfig = synCfg.getAxisConfiguration().getAxisConfiguration(); try { axisConfig.getService(this.getName()).setActive(false); this.setRunning(false); } catch (AxisFault axisFault) { handleException(axisFault.getMessage()); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ArrayList getTransports() { return transports; } public void addParameter(String name, Object value) { parameters.put(name, value); } public Map getParameterMap() { return this.parameters; } public void setTransports(ArrayList transports) { this.transports = transports; } public String getTargetEndpoint() { return targetEndpoint; } public void setTargetEndpoint(String targetEndpoint) { this.targetEndpoint = targetEndpoint; } public String getTargetInSequence() { return targetInSequence; } public void setTargetInSequence(String targetInSequence) { this.targetInSequence = targetInSequence; } public String getTargetOutSequence() { return targetOutSequence; } public void setTargetOutSequence(String targetOutSequence) { this.targetOutSequence = targetOutSequence; } public String getWSDLKey() { return wsdlKey; } public void setWSDLKey(String wsdlKey) { this.wsdlKey = wsdlKey; } public List getSchemas() { return schemaKeys; } public void setSchemas(List schemas) { this.schemaKeys = schemas; } public List getServiceLevelPolicies() { return serviceLevelPolicies; } public void addServiceLevelPolicy(String serviceLevelPolicy) { this.serviceLevelPolicies.add(serviceLevelPolicy); } public boolean isWsRMEnabled() { return wsRMEnabled; } public void setWsRMEnabled(boolean wsRMEnabled) { this.wsRMEnabled = wsRMEnabled; } public boolean isWsSecEnabled() { return wsSecEnabled; } public void setWsSecEnabled(boolean wsSecEnabled) { this.wsSecEnabled = wsSecEnabled; } public boolean isStartOnLoad() { return startOnLoad; } public void setStartOnLoad(boolean startOnLoad) { this.startOnLoad = startOnLoad; } public boolean isRunning() { return running; } public void setRunning(boolean running) { this.running = running; } private static void handleException(String msg) { log.error(msg); throw new SynapseException(msg); } private static void handleException(String msg, Exception e) { log.error(msg, e); throw new SynapseException(msg, e); } /** * To check whether statistics should have collected or not * * @return Returns the int value that indicate statistics is enabled or not. */ public int getStatisticsEnable() { return statisticsEnable; } /** * To set the statistics enable variable value * * @param statisticsEnable */ public void setStatisticsEnable(int statisticsEnable) { this.statisticsEnable = statisticsEnable; } /** * Returns the int value that indicate the tracing state * * @return Returns the int value that indicate the tracing state */ public int getTraceState() { return traceState; } /** * Set the tracing State variable * * @param traceState */ public void setTraceState(int traceState) { this.traceState = traceState; } public String getTargetFaultSequence() { return targetFaultSequence; } public void setTargetFaultSequence(String targetFaultSequence) { this.targetFaultSequence = targetFaultSequence; } public Object getInLineWSDL() { return inLineWSDL; } public void setInLineWSDL(Object inLineWSDL) { this.inLineWSDL = inLineWSDL; } public URI getWsdlURI() { return wsdlURI; } public void setWsdlURI(URI wsdlURI) { this.wsdlURI = wsdlURI; } public Endpoint getTargetInLineEndpoint() { return targetInLineEndpoint; } public void setTargetInLineEndpoint(Endpoint targetInLineEndpoint) { this.targetInLineEndpoint = targetInLineEndpoint; } public SequenceMediator getTargetInLineInSequence() { return targetInLineInSequence; } public void setTargetInLineInSequence(SequenceMediator targetInLineInSequence) { this.targetInLineInSequence = targetInLineInSequence; } public SequenceMediator getTargetInLineOutSequence() { return targetInLineOutSequence; } public void setTargetInLineOutSequence(SequenceMediator targetInLineOutSequence) { this.targetInLineOutSequence = targetInLineOutSequence; } public SequenceMediator getTargetInLineFaultSequence() { return targetInLineFaultSequence; } public void setTargetInLineFaultSequence(SequenceMediator targetInLineFaultSequence) { this.targetInLineFaultSequence = targetInLineFaultSequence; } }
true
true
public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) { AxisService proxyService = null; InputStream wsdlInputStream = null; OMElement wsdlElement = null; if (wsdlKey != null) { Object keyObject = synCfg.getEntry(wsdlKey); if (keyObject instanceof OMElement) { wsdlElement = (OMElement) keyObject; } } else if (inLineWSDL != null) { wsdlElement = (OMElement) inLineWSDL; } else if (wsdlURI != null) { try { URL url = wsdlURI.toURL(); if (url != null) { URLConnection urlc = url.openConnection(); try { if (urlc != null) { XMLStreamReader parser = XMLInputFactory.newInstance(). createXMLStreamReader(urlc.getInputStream()); StAXOMBuilder builder = new StAXOMBuilder(parser); wsdlElement = builder.getDocumentElement(); // detach from URL connection and keep in memory // TODO remove this wsdlElement.build(); } } catch (XMLStreamException e) { log.warn("Content at URL : " + url + " is non XML.."); } } } catch (MalformedURLException e) { handleException("Malformed URI for wsdl", e); } catch (IOException e) { handleException("Error reading from wsdl URI", e); } } if (wsdlElement != null) { OMNamespace wsdlNamespace = wsdlElement.getNamespace(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { wsdlElement.serialize(baos); wsdlInputStream = new ByteArrayInputStream(baos.toByteArray()); } catch (XMLStreamException e) { handleException("Error converting to a StreamSource", e); } if (wsdlInputStream != null) { try { // detect version of the WSDL 1.1 or 2.0 if (wsdlNamespace != null) { WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null; if (WSDL2Constants.WSDL_NAMESPACE. equals(wsdlNamespace.getNamespaceURI())) { wsdlToAxisServiceBuilder = new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null); } else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11. equals(wsdlNamespace.getNamespaceURI())) { wsdlToAxisServiceBuilder = new WSDL11ToAxisServiceBuilder(wsdlInputStream, null, null); } else { handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0"); } if (wsdlToAxisServiceBuilder == null) { throw new SynapseException( "Could not get the WSDL to Axis Service Builder"); } proxyService = wsdlToAxisServiceBuilder.populateService(); proxyService.setWsdlFound(true); } else { handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0"); } } catch (AxisFault af) { handleException("Error building service from WSDL", af); } catch (IOException ioe) { handleException("Error reading WSDL", ioe); } } } else { // this is for POX... create a dummy service and an operation for which // our SynapseDispatcher will properly dispatch to proxyService = new AxisService(); AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate")); proxyService.addOperation(mediateOperation); } // Set the name and description. Currently Axis2 uses the name as the // default Service destination if (proxyService == null) { throw new SynapseException("Could not create a proxy service"); } proxyService.setName(name); if (description != null) { proxyService.setServiceDescription(description); } // process transports and expose over requested transports. If none // is specified, default to all transports using service name as // destination if (transports == null || transports.size() == 0) { // default to all transports using service name as destination } else { proxyService.setExposedTransports(transports); } // process parameters Iterator iter = parameters.keySet().iterator(); while (iter.hasNext()) { String name = (String) iter.next(); Object value = parameters.get(name); Parameter p = new Parameter(); p.setName(name); p.setValue(value); try { proxyService.addParameter(p); } catch (AxisFault af) { handleException("Error setting parameter : " + name + "" + "to proxy service as a Parameter", af); } } // if service level policies are specified, apply them if (!serviceLevelPolicies.isEmpty()) { Policy svcEffectivePolicy = null; iter = serviceLevelPolicies.iterator(); while (iter.hasNext()) { String policyKey = (String) iter.next(); Object policyProp = synCfg.getEntry(policyKey); if (policyProp != null) { if (svcEffectivePolicy == null) { svcEffectivePolicy = PolicyEngine.getPolicy( Util.getStreamSource(policyProp).getInputStream()); } else { svcEffectivePolicy = (Policy) svcEffectivePolicy.merge( PolicyEngine.getPolicy( Util.getStreamSource(policyProp).getInputStream())); } } } PolicyInclude pi = proxyService.getPolicyInclude(); if (pi != null && svcEffectivePolicy != null) { pi.addPolicyElement(PolicyInclude.AXIS_SERVICE_POLICY, svcEffectivePolicy); // todo: check whether the rm or sec is enabled } } // create a custom message receiver for this proxy service ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver(); msgRcvr.setName(name); iter = proxyService.getOperations(); while (iter.hasNext()) { AxisOperation op = (AxisOperation) iter.next(); op.setMessageReceiver(msgRcvr); } try { axisCfg.addService(proxyService); this.setRunning(true); } catch (AxisFault axisFault) { handleException("Unable to start the Proxy Service"); } // todo: need to remove this and engage modules by looking at policies // should RM be engaged on this service? if (wsRMEnabled) { try { proxyService.engageModule(axisCfg.getModule( Constants.SANDESHA2_MODULE_NAME), axisCfg); } catch (AxisFault axisFault) { handleException("Error loading WS RM module on proxy service : " + name, axisFault); } } // should Security be engaged on this service? if (wsSecEnabled) { try { proxyService.engageModule(axisCfg.getModule( Constants.RAMPART_MODULE_NAME), axisCfg); } catch (AxisFault axisFault) { handleException("Error loading WS Sec module on proxy service : " + name, axisFault); } } return proxyService; }
public AxisService buildAxisService(SynapseConfiguration synCfg, AxisConfiguration axisCfg) { AxisService proxyService = null; InputStream wsdlInputStream = null; OMElement wsdlElement = null; if (wsdlKey != null) { Object keyObject = synCfg.getEntry(wsdlKey); if (keyObject instanceof OMElement) { wsdlElement = (OMElement) keyObject; } } else if (inLineWSDL != null) { wsdlElement = (OMElement) inLineWSDL; } else if (wsdlURI != null) { try { URL url = wsdlURI.toURL(); if (url != null) { URLConnection urlc = url.openConnection(); try { if (urlc != null) { XMLStreamReader parser = XMLInputFactory.newInstance(). createXMLStreamReader(urlc.getInputStream()); StAXOMBuilder builder = new StAXOMBuilder(parser); wsdlElement = builder.getDocumentElement(); // detach from URL connection and keep in memory // TODO remove this wsdlElement.build(); } } catch (XMLStreamException e) { log.warn("Content at URL : " + url + " is non XML.."); } } } catch (MalformedURLException e) { handleException("Malformed URI for wsdl", e); } catch (IOException e) { handleException("Error reading from wsdl URI", e); } } if (wsdlElement != null) { OMNamespace wsdlNamespace = wsdlElement.getNamespace(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { wsdlElement.serialize(baos); wsdlInputStream = new ByteArrayInputStream(baos.toByteArray()); } catch (XMLStreamException e) { handleException("Error converting to a StreamSource", e); } if (wsdlInputStream != null) { try { // detect version of the WSDL 1.1 or 2.0 if (wsdlNamespace != null) { WSDLToAxisServiceBuilder wsdlToAxisServiceBuilder = null; if (WSDL2Constants.WSDL_NAMESPACE. equals(wsdlNamespace.getNamespaceURI())) { wsdlToAxisServiceBuilder = new WSDL20ToAxisServiceBuilder(wsdlInputStream, null, null); } else if (org.apache.axis2.namespace.Constants.NS_URI_WSDL11. equals(wsdlNamespace.getNamespaceURI())) { wsdlToAxisServiceBuilder = new WSDL11ToAxisServiceBuilder(wsdlInputStream, null, null); } else { handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0"); } if (wsdlToAxisServiceBuilder == null) { throw new SynapseException( "Could not get the WSDL to Axis Service Builder"); } proxyService = wsdlToAxisServiceBuilder.populateService(); proxyService.setWsdlFound(true); } else { handleException("Unknown WSDL format.. not WSDL 1.1 or WSDL 2.0"); } } catch (AxisFault af) { handleException("Error building service from WSDL", af); } catch (IOException ioe) { handleException("Error reading WSDL", ioe); } } } else { // this is for POX... create a dummy service and an operation for which // our SynapseDispatcher will properly dispatch to proxyService = new AxisService(); AxisOperation mediateOperation = new InOutAxisOperation(new QName("mediate")); proxyService.addOperation(mediateOperation); } // Set the name and description. Currently Axis2 uses the name as the // default Service destination if (proxyService == null) { throw new SynapseException("Could not create a proxy service"); } proxyService.setName(name); if (description != null) { proxyService.setServiceDescription(description); } // process transports and expose over requested transports. If none // is specified, default to all transports using service name as // destination if (transports == null || transports.size() == 0) { // default to all transports using service name as destination } else { proxyService.setExposedTransports(transports); } // process parameters Iterator iter = parameters.keySet().iterator(); while (iter.hasNext()) { String name = (String) iter.next(); Object value = parameters.get(name); Parameter p = new Parameter(); p.setName(name); p.setValue(value); try { proxyService.addParameter(p); } catch (AxisFault af) { handleException("Error setting parameter : " + name + "" + "to proxy service as a Parameter", af); } } // if service level policies are specified, apply them if (!serviceLevelPolicies.isEmpty()) { Policy svcEffectivePolicy = null; iter = serviceLevelPolicies.iterator(); while (iter.hasNext()) { String policyKey = (String) iter.next(); Object policyProp = synCfg.getEntry(policyKey); if (policyProp != null) { if (svcEffectivePolicy == null) { svcEffectivePolicy = PolicyEngine.getPolicy( Util.getStreamSource(policyProp).getInputStream()); } else { svcEffectivePolicy = (Policy) svcEffectivePolicy.merge( PolicyEngine.getPolicy( Util.getStreamSource(policyProp).getInputStream())); } } } PolicyInclude pi = proxyService.getPolicyInclude(); if (pi != null && svcEffectivePolicy != null) { pi.addPolicyElement(PolicyInclude.AXIS_SERVICE_POLICY, svcEffectivePolicy); // todo: check whether the rm or sec is enabled } } // create a custom message receiver for this proxy service ProxyServiceMessageReceiver msgRcvr = new ProxyServiceMessageReceiver(); msgRcvr.setName(name); iter = proxyService.getOperations(); while (iter.hasNext()) { AxisOperation op = (AxisOperation) iter.next(); op.setMessageReceiver(msgRcvr); } try { axisCfg.addService(proxyService); this.setRunning(true); } catch (AxisFault axisFault) { try { if (axisCfg.getService(proxyService.getName()) != null) { axisCfg.removeService(proxyService.getName()); } } catch (AxisFault ignore) {} handleException("Error adding Proxy service to the Axis2 engine"); } // todo: need to remove this and engage modules by looking at policies // should RM be engaged on this service? if (wsRMEnabled) { try { proxyService.engageModule(axisCfg.getModule( Constants.SANDESHA2_MODULE_NAME), axisCfg); } catch (AxisFault axisFault) { handleException("Error loading WS RM module on proxy service : " + name, axisFault); } } // should Security be engaged on this service? if (wsSecEnabled) { try { proxyService.engageModule(axisCfg.getModule( Constants.RAMPART_MODULE_NAME), axisCfg); } catch (AxisFault axisFault) { handleException("Error loading WS Sec module on proxy service : " + name, axisFault); } } return proxyService; }
diff --git a/src/Level2.java b/src/Level2.java index a35f72b..bc585c5 100644 --- a/src/Level2.java +++ b/src/Level2.java @@ -1,341 +1,342 @@ import java.awt.Font; import java.util.ArrayList; import org.newdawn.slick.GameContainer; import org.newdawn.slick.TrueTypeFont; import org.newdawn.slick.gui.TextField; public class Level2 extends Level { CommandBox commandbox_1; CommandBox commandbox_2; CommandBox commandbox_3; CommandBox commandbox_4; CommandBox commandbox_5; CommandBox commandbox_6; CommandBox commandbox_7; CommandBox commandbox_8; CommandBox commandbox_9; CommandBox commandbox_10; CommandBox commandbox_11; CommandBox commandbox_12; CommandBox commandbox_13; CommandBox commandbox_14; CommandBox commandbox_15; CommandBox commandbox_16; CommandBox commandbox_17; Model model; TextField tf1; TextField tf2; TextField tf3; TextField tf4; TextField tf5; ArrayList<TextField> tf_list; Font font1; TrueTypeFont font2; ArrayList<CommandBox> boxes; Level prev_level; Level next_level; Stack stack = new Stack(600, 40, 24); public Level2(Model m, GameContainer gc) { this.model = m; commandbox_1 = new CommandBox(40, 180, "If in front of fridge"); commandbox_2 = new CommandBox(40, 240, "If in front of drawer"); commandbox_3 = new CommandBox(210, 180, "If in front of cabinet"); commandbox_4 = new CommandBox(210, 240, "open fridge"); commandbox_5 = new CommandBox(40, 300, "open cabinet"); commandbox_6 = new CommandBox(40, 360, "open drawer"); commandbox_7 = new CommandBox(40, 420, "close fridge"); commandbox_8 = new CommandBox(210, 300, "close drawer"); commandbox_9 = new CommandBox(210, 360, "close cabinet"); commandbox_10 = new CommandBox(210, 420, "get bread"); commandbox_11 = new CommandBox(40, 480, "get knife"); commandbox_12 = new CommandBox(210, 480, "get spoon"); commandbox_13 = new CommandBox(40, 540, "get fork"); commandbox_14 = new CommandBox(210, 540, "get bowl"); commandbox_15 = new CommandBox(40, 600, "get peanut butter"); commandbox_16 = new CommandBox(210, 600, "get jelly"); commandbox_17 = new CommandBox(40, 660, "get plate"); boxes = new ArrayList<CommandBox>(); boxes.add( commandbox_1); boxes.add( commandbox_2); boxes.add( commandbox_3); boxes.add(commandbox_4); boxes.add( commandbox_5); boxes.add(commandbox_6); boxes.add( commandbox_7); boxes.add( commandbox_8); boxes.add(commandbox_9); boxes.add(commandbox_10); boxes.add( commandbox_11); boxes.add(commandbox_12); boxes.add(commandbox_13); boxes.add(commandbox_14); boxes.add(commandbox_15); boxes.add(commandbox_16); boxes.add(commandbox_17); tf_list = new ArrayList<TextField>(); font1 = new Font("Times New Roman", Font.PLAIN, 15); font2 = new TrueTypeFont(font1, false); tf1 = new TextField(gc,font2, 100, 40, 400, 20); tf2 = new TextField(gc,font2, 100, 60, 400, 20); tf3 = new TextField(gc,font2, 100, 80, 400, 20); tf4 = new TextField(gc,font2, 100, 100, 400, 20); tf5 = new TextField(gc, font2, 100, 120, 400, 20); tf1.setText("Now that the kitchen is cleaned, it's time for the "); tf2.setText("robot to gather all of the materials it needs. The"); tf3.setText("robot is moving around the kitchen and will stop at "); tf4.setText("different locations in the kitchen. Make sure he gathers" ); tf5.setText("everything it needs to make sandwiches!"); tf_list = new ArrayList<TextField>(); tf_list.add(tf1); tf_list.add(tf2); tf_list.add(tf3); tf_list.add(tf4); tf_list.add(tf5); } public void run() { boolean at_fridge = false; boolean at_drawer = false; boolean at_cabinet = false; boolean open_fridge = false; boolean open_drawer = false; boolean open_cabinet = false; boolean close_fridge = false; boolean close_drawer = false; boolean close_cabinet = false; boolean bread = false; boolean knife = false; boolean pb = false; boolean j = false; boolean plate = false; boolean fBlock = false; boolean dBlock = false; boolean cBlock = false; String message = ""; for(int i = 0; i<stack.num_boxes; i++) { CommandBox temp = stack.box_stack[i]; if (temp == null) { continue; } if (temp.str.equals(commandbox_1.str)) { if (dBlock || cBlock){ message = "Complete the actions at a location!"; break; } at_fridge = true; fBlock = true; } else if (temp.str.equals(commandbox_2.str)) { if (fBlock || cBlock){ message = "Complete the actions at a location!"; break; } at_drawer = true; dBlock = true; } else if (temp.str.equals(commandbox_3.str)) { if (fBlock || dBlock){ message = "Complete the actions at a location!"; break; } at_cabinet = true; cBlock = true; } else if (temp.str.equals(commandbox_4.str)) { if (!at_fridge){ message = "You are not at the fridge!"; break; } open_fridge = true; } else if (temp.str.equals(commandbox_5.str)) { if (!at_cabinet){ message = "You are not at the cabinet!"; break; } open_cabinet = true; } else if (temp.str.equals(commandbox_6.str)) { if (!at_drawer){ message = "You are not at the drawer!"; break; } open_drawer = true; } else if (temp.str.equals(commandbox_7.str)) { if (!open_fridge){ message = "The fridge is not open!"; break; } close_fridge = true; fBlock = false; } else if (temp.str.equals(commandbox_8.str)) { if (!open_drawer){ message = "The drawer is not open!"; break; } close_drawer = true; dBlock = false; } else if (temp.str.equals(commandbox_9.str)) { if (!open_cabinet){ message = "The cabinet is not open!"; break; } close_cabinet = true; cBlock = false; } else if (temp.str.equals(commandbox_10.str)) { if (!fBlock){ message = "There is no food in the cabinet or drawer!"; break; }else if(!open_fridge){ message = "The fridge is not open!"; break; } bread = true; } else if (temp.str.equals(commandbox_11.str)) { if (!open_drawer){ message = "The drawer is not open!"; break; } knife = true; } else if (temp.str.equals(commandbox_12.str) || temp.str.equals(commandbox_13.str) || temp.str.equals(commandbox_14.str)) { message = "You're carrying too many things!"; + break; } else if (temp.str.equals(commandbox_15.str)){ if (!fBlock){ message = "There is no food in the cabinet or drawer!"; break; }else if(!open_fridge){ message = "The fridge is not open!"; break; } pb = true; } else if (temp.str.equals(commandbox_16.str)){ if (!fBlock){ message = "There is no food in the cabinet or drawer!"; break; }else if(!open_fridge){ message = "The fridge is not open!"; break; } j = true; } else if (temp.str.equals(commandbox_17.str)){ if (!open_cabinet){ message = "The cabinet is not open!"; break; } plate = true; } } if (!message.equals("")){ model.cur_error = message; model.cur_prog = Model.Progress.ERROR; } else if (!(at_fridge && at_drawer && at_cabinet)){ model.cur_error = "You're not going to a crucial location!"; model.cur_prog = Model.Progress.ERROR; } else if (!(close_fridge && close_cabinet && close_drawer)){ model.cur_error = "You left something open!"; model.cur_prog = Model.Progress.ERROR; } else if (!(bread && knife && pb && j && plate)){ model.cur_error = "You forgot to get something!"; model.cur_prog = Model.Progress.ERROR; } else { model.cur_error = "Done!"; model.cur_prog = Model.Progress.SUCCESS; } } @Override void render() { // TODO Auto-generated method stub } @Override ArrayList<CommandBox> getBoxes() { // TODO Auto-generated method stub return boxes; } @Override Stack getStack() { // TODO Auto-generated method stub return stack; } @Override ArrayList<TextField> getTF() { // TODO Auto-generated method stub return tf_list; } @Override void setPrevLevel(Level level) { // TODO Auto-generated method stub prev_level = level; } @Override Level getPrevLevel() { // TODO Auto-generated method stub return prev_level; } @Override void setNextLevel(Level level) { // TODO Auto-generated method stub next_level = level; } @Override Level getNextLevel() { // TODO Auto-generated method stub return next_level; } }
true
true
public void run() { boolean at_fridge = false; boolean at_drawer = false; boolean at_cabinet = false; boolean open_fridge = false; boolean open_drawer = false; boolean open_cabinet = false; boolean close_fridge = false; boolean close_drawer = false; boolean close_cabinet = false; boolean bread = false; boolean knife = false; boolean pb = false; boolean j = false; boolean plate = false; boolean fBlock = false; boolean dBlock = false; boolean cBlock = false; String message = ""; for(int i = 0; i<stack.num_boxes; i++) { CommandBox temp = stack.box_stack[i]; if (temp == null) { continue; } if (temp.str.equals(commandbox_1.str)) { if (dBlock || cBlock){ message = "Complete the actions at a location!"; break; } at_fridge = true; fBlock = true; } else if (temp.str.equals(commandbox_2.str)) { if (fBlock || cBlock){ message = "Complete the actions at a location!"; break; } at_drawer = true; dBlock = true; } else if (temp.str.equals(commandbox_3.str)) { if (fBlock || dBlock){ message = "Complete the actions at a location!"; break; } at_cabinet = true; cBlock = true; } else if (temp.str.equals(commandbox_4.str)) { if (!at_fridge){ message = "You are not at the fridge!"; break; } open_fridge = true; } else if (temp.str.equals(commandbox_5.str)) { if (!at_cabinet){ message = "You are not at the cabinet!"; break; } open_cabinet = true; } else if (temp.str.equals(commandbox_6.str)) { if (!at_drawer){ message = "You are not at the drawer!"; break; } open_drawer = true; } else if (temp.str.equals(commandbox_7.str)) { if (!open_fridge){ message = "The fridge is not open!"; break; } close_fridge = true; fBlock = false; } else if (temp.str.equals(commandbox_8.str)) { if (!open_drawer){ message = "The drawer is not open!"; break; } close_drawer = true; dBlock = false; } else if (temp.str.equals(commandbox_9.str)) { if (!open_cabinet){ message = "The cabinet is not open!"; break; } close_cabinet = true; cBlock = false; } else if (temp.str.equals(commandbox_10.str)) { if (!fBlock){ message = "There is no food in the cabinet or drawer!"; break; }else if(!open_fridge){ message = "The fridge is not open!"; break; } bread = true; } else if (temp.str.equals(commandbox_11.str)) { if (!open_drawer){ message = "The drawer is not open!"; break; } knife = true; } else if (temp.str.equals(commandbox_12.str) || temp.str.equals(commandbox_13.str) || temp.str.equals(commandbox_14.str)) { message = "You're carrying too many things!"; } else if (temp.str.equals(commandbox_15.str)){ if (!fBlock){ message = "There is no food in the cabinet or drawer!"; break; }else if(!open_fridge){ message = "The fridge is not open!"; break; } pb = true; } else if (temp.str.equals(commandbox_16.str)){ if (!fBlock){ message = "There is no food in the cabinet or drawer!"; break; }else if(!open_fridge){ message = "The fridge is not open!"; break; } j = true; } else if (temp.str.equals(commandbox_17.str)){ if (!open_cabinet){ message = "The cabinet is not open!"; break; } plate = true; } } if (!message.equals("")){ model.cur_error = message; model.cur_prog = Model.Progress.ERROR; } else if (!(at_fridge && at_drawer && at_cabinet)){ model.cur_error = "You're not going to a crucial location!"; model.cur_prog = Model.Progress.ERROR; } else if (!(close_fridge && close_cabinet && close_drawer)){ model.cur_error = "You left something open!"; model.cur_prog = Model.Progress.ERROR; } else if (!(bread && knife && pb && j && plate)){ model.cur_error = "You forgot to get something!"; model.cur_prog = Model.Progress.ERROR; } else { model.cur_error = "Done!"; model.cur_prog = Model.Progress.SUCCESS; } }
public void run() { boolean at_fridge = false; boolean at_drawer = false; boolean at_cabinet = false; boolean open_fridge = false; boolean open_drawer = false; boolean open_cabinet = false; boolean close_fridge = false; boolean close_drawer = false; boolean close_cabinet = false; boolean bread = false; boolean knife = false; boolean pb = false; boolean j = false; boolean plate = false; boolean fBlock = false; boolean dBlock = false; boolean cBlock = false; String message = ""; for(int i = 0; i<stack.num_boxes; i++) { CommandBox temp = stack.box_stack[i]; if (temp == null) { continue; } if (temp.str.equals(commandbox_1.str)) { if (dBlock || cBlock){ message = "Complete the actions at a location!"; break; } at_fridge = true; fBlock = true; } else if (temp.str.equals(commandbox_2.str)) { if (fBlock || cBlock){ message = "Complete the actions at a location!"; break; } at_drawer = true; dBlock = true; } else if (temp.str.equals(commandbox_3.str)) { if (fBlock || dBlock){ message = "Complete the actions at a location!"; break; } at_cabinet = true; cBlock = true; } else if (temp.str.equals(commandbox_4.str)) { if (!at_fridge){ message = "You are not at the fridge!"; break; } open_fridge = true; } else if (temp.str.equals(commandbox_5.str)) { if (!at_cabinet){ message = "You are not at the cabinet!"; break; } open_cabinet = true; } else if (temp.str.equals(commandbox_6.str)) { if (!at_drawer){ message = "You are not at the drawer!"; break; } open_drawer = true; } else if (temp.str.equals(commandbox_7.str)) { if (!open_fridge){ message = "The fridge is not open!"; break; } close_fridge = true; fBlock = false; } else if (temp.str.equals(commandbox_8.str)) { if (!open_drawer){ message = "The drawer is not open!"; break; } close_drawer = true; dBlock = false; } else if (temp.str.equals(commandbox_9.str)) { if (!open_cabinet){ message = "The cabinet is not open!"; break; } close_cabinet = true; cBlock = false; } else if (temp.str.equals(commandbox_10.str)) { if (!fBlock){ message = "There is no food in the cabinet or drawer!"; break; }else if(!open_fridge){ message = "The fridge is not open!"; break; } bread = true; } else if (temp.str.equals(commandbox_11.str)) { if (!open_drawer){ message = "The drawer is not open!"; break; } knife = true; } else if (temp.str.equals(commandbox_12.str) || temp.str.equals(commandbox_13.str) || temp.str.equals(commandbox_14.str)) { message = "You're carrying too many things!"; break; } else if (temp.str.equals(commandbox_15.str)){ if (!fBlock){ message = "There is no food in the cabinet or drawer!"; break; }else if(!open_fridge){ message = "The fridge is not open!"; break; } pb = true; } else if (temp.str.equals(commandbox_16.str)){ if (!fBlock){ message = "There is no food in the cabinet or drawer!"; break; }else if(!open_fridge){ message = "The fridge is not open!"; break; } j = true; } else if (temp.str.equals(commandbox_17.str)){ if (!open_cabinet){ message = "The cabinet is not open!"; break; } plate = true; } } if (!message.equals("")){ model.cur_error = message; model.cur_prog = Model.Progress.ERROR; } else if (!(at_fridge && at_drawer && at_cabinet)){ model.cur_error = "You're not going to a crucial location!"; model.cur_prog = Model.Progress.ERROR; } else if (!(close_fridge && close_cabinet && close_drawer)){ model.cur_error = "You left something open!"; model.cur_prog = Model.Progress.ERROR; } else if (!(bread && knife && pb && j && plate)){ model.cur_error = "You forgot to get something!"; model.cur_prog = Model.Progress.ERROR; } else { model.cur_error = "Done!"; model.cur_prog = Model.Progress.SUCCESS; } }
diff --git a/rim/src/com/google/zxing/client/rim/ZXingLMMainScreen.java b/rim/src/com/google/zxing/client/rim/ZXingLMMainScreen.java index 1e8a2f57..7c59ac2d 100644 --- a/rim/src/com/google/zxing/client/rim/ZXingLMMainScreen.java +++ b/rim/src/com/google/zxing/client/rim/ZXingLMMainScreen.java @@ -1,331 +1,332 @@ /* * Copyright 2008 ZXing 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 com.google.zxing.client.rim; import com.google.zxing.DecodeHintType; import com.google.zxing.MonochromeBitmapSource; import com.google.zxing.MultiFormatReader; import com.google.zxing.Reader; import com.google.zxing.ReaderException; import com.google.zxing.Result; import com.google.zxing.client.j2me.LCDUIImageMonochromeBitmapSource; import com.google.zxing.client.rim.persistence.AppSettings; import com.google.zxing.client.rim.persistence.history.DecodeHistory; import com.google.zxing.client.rim.persistence.history.DecodeHistoryItem; import com.google.zxing.client.rim.util.Log; import com.google.zxing.client.rim.util.ReasonableTimer; import com.google.zxing.client.rim.util.URLDecoder; import net.rim.blackberry.api.browser.Browser; import net.rim.blackberry.api.browser.BrowserSession; import net.rim.device.api.ui.DrawStyle; import net.rim.device.api.ui.Field; import net.rim.device.api.ui.FieldChangeListener; import net.rim.device.api.ui.Manager; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.ui.component.ButtonField; import net.rim.device.api.ui.component.Dialog; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.container.DialogFieldManager; import net.rim.device.api.ui.container.MainScreen; import net.rim.device.api.ui.container.PopupScreen; import net.rim.device.api.ui.container.VerticalFieldManager; import javax.microedition.io.Connector; import javax.microedition.io.file.FileConnection; import javax.microedition.lcdui.Image; import java.io.IOException; import java.io.InputStream; import java.util.Hashtable; /** * The main appication menu screen. * * This code was contributed by LifeMarks. * * @author Matt York ([email protected]) */ final class ZXingLMMainScreen extends MainScreen { private final ZXingUiApplication app; private final QRCapturedJournalListener imageListener; private PopupScreen popup; private final Reader reader; private final Hashtable readerHints; ZXingLMMainScreen() { super(DEFAULT_MENU | DEFAULT_CLOSE); setTitle(new LabelField("ZXing", DrawStyle.ELLIPSIS | USE_ALL_WIDTH)); setChangeListener(null); Manager vfm = new VerticalFieldManager(USE_ALL_WIDTH); FieldChangeListener buttonListener = new ButtonListener(); //0 Field snapButton = new ButtonField("Snap", FIELD_HCENTER | ButtonField.CONSUME_CLICK | USE_ALL_WIDTH); snapButton.setChangeListener(buttonListener); vfm.add(snapButton); //1 Field historyButton = new ButtonField("History", FIELD_HCENTER | ButtonField.CONSUME_CLICK); historyButton.setChangeListener(buttonListener); vfm.add(historyButton); //2 Field settingsButton = new ButtonField("Settings", FIELD_HCENTER | ButtonField.CONSUME_CLICK); settingsButton.setChangeListener(buttonListener); vfm.add(settingsButton); //3 Field aboutButton = new ButtonField("About", FIELD_HCENTER | ButtonField.CONSUME_CLICK); aboutButton.setChangeListener(buttonListener); vfm.add(aboutButton); //4 Field helpButton = new ButtonField("Help", FIELD_HCENTER | ButtonField.CONSUME_CLICK); helpButton.setChangeListener(buttonListener); vfm.add(helpButton); vfm.setChangeListener(null); add(vfm); app = (ZXingUiApplication) UiApplication.getUiApplication(); imageListener = new QRCapturedJournalListener(this); reader = new MultiFormatReader(); readerHints = new Hashtable(1); readerHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); } /** * Handles the newly created file. If the file is a jpg image, from the camera, the images is assumed to be * a qrcode and decoding is attempted. */ void imageSaved(String imagePath) { Log.info("Image saved: " + imagePath); app.removeFileSystemJournalListener(imageListener); if (imagePath.endsWith(".jpg") && imagePath.indexOf("IMG") >= 0) // a blackberry camera image file { Log.info("imageSaved - Got file: " + imagePath); Camera.getInstance().exit(); Log.info("camera exit finished"); app.requestForeground(); DialogFieldManager manager = new DialogFieldManager(); popup = new PopupScreen(manager); manager.addCustomField(new LabelField("Decoding image...")); app.pushScreen(popup); // original Log.info("started progress screen."); Runnable fct = new FileConnectionThread(imagePath); Log.info("Starting file connection thread."); app.invokeLater(fct); Log.info("Finished file connection thread."); } else { Log.error("Failed to locate camera image."); } } /** * Closes the application and persists all required data. */ public void close() { app.removeFileSystemJournalListener(imageListener); DecodeHistory.getInstance().persist(); super.close(); } /** * This method is overriden to remove the 'save changes' dialog when exiting. */ public boolean onSavePrompt() { setDirty(false); return true; } /** * Listens for selected buttons and starts the required screen. */ private final class ButtonListener implements FieldChangeListener { public void fieldChanged(Field field, int context) { Log.debug("*** fieldChanged: " + field.getIndex()); switch (field.getIndex()) { case 0: // snap try { app.addFileSystemJournalListener(imageListener); Camera.getInstance().invoke(); // start camera return; } catch (Exception e) { Log.error("!!! Problem invoking camera.!!!: " + e); } break; case 1: // history app.pushScreen(new HistoryScreen()); break; case 2: // settings app.pushScreen(new SettingsScreen()); break; case 3: //about app.pushScreen(new AboutScreen()); break; case 4: //help app.pushScreen(new HelpScreen()); break; } } } /** * Thread that decodes the newly created image. If the image is successfully decoded and the data is a URL, * the browser is invoked and pointed to the given URL. */ private final class FileConnectionThread implements Runnable { private final String imagePath; private FileConnectionThread(String imagePath) { this.imagePath = imagePath; } public void run() { FileConnection file = null; InputStream is = null; Image capturedImage = null; try { file = (FileConnection) Connector.open("file://" + imagePath, Connector.READ_WRITE); is = file.openInputStream(); capturedImage = Image.createImage(is); } catch (IOException e) { Log.error("Problem creating image: " + e); removeProgressBar(); invalidate(); showMessage("An error occured processing the image."); return; } finally { - if (is != null) { - try { + try { + if (is != null) { is.close(); - } catch (IOException ioe) { } - } - if (file != null && file.exists()) { - if (file.isOpen()) { - //file.close(); + if (file != null && file.exists()) { + if (file.isOpen()) { + file.close(); + } + file.delete(); + Log.info("Deleted image file."); } - //file.delete(); - Log.info("Deleted image file."); + } catch (IOException ioe) { + Log.error("Error while closing file: " + ioe); } } if (capturedImage != null) { Log.info("Got image..."); MonochromeBitmapSource source = new LCDUIImageMonochromeBitmapSource(capturedImage); Result result; ReasonableTimer decodingTimer = null; try { decodingTimer = new ReasonableTimer(); Log.info("Attempting to decode image..."); result = reader.decode(source, readerHints); decodingTimer.finished(); } catch (ReaderException e) { Log.error("Could not decode image: " + e); decodingTimer.finished(); removeProgressBar(); invalidate(); boolean showResolutionMsg = !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue(); if (showResolutionMsg) { showMessage("A QR Code was not found in the image. " + "We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } else { showMessage("A QR Code was not found in the image."); } return; } if (result != null) { String resultText = result.getText(); Log.info("result: " + resultText); if (isURI(resultText)) { resultText = URLDecoder.decode(resultText); removeProgressBar(); invalidate(); if (!decodingTimer.wasResonableTime() && !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue()) { showMessage("We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } DecodeHistory.getInstance().addHistoryItem(new DecodeHistoryItem(resultText)); invokeBrowser(resultText); return; } } else { removeProgressBar(); invalidate(); showMessage("A QR Code was not found in the image."); return; } } removeProgressBar(); invalidate(); } /** * Quick check to see if the result of decoding the qr code was a valid uri. */ private boolean isURI(String uri) { return uri.startsWith("http://"); } /** * Invokes the web browser and browses to the given uri. */ private void invokeBrowser(String uri) { BrowserSession browserSession = Browser.getDefaultSession(); browserSession.displayPage(uri); } /** * Syncronized version of removing progress dialog. * NOTE: All methods accessing the gui that are in seperate threads should syncronize on app.getEventLock() */ private void removeProgressBar() { synchronized (app.getAppEventLock()) { if (popup != null) { app.popScreen(popup); } } } /** * Syncronized version of showing a message dialog. * NOTE: All methods accessing the gui that are in seperate threads should syncronize on app.getEventLock() */ private void showMessage(String message) { synchronized (app.getAppEventLock()) { Dialog.alert(message); } } } }
false
true
public void run() { FileConnection file = null; InputStream is = null; Image capturedImage = null; try { file = (FileConnection) Connector.open("file://" + imagePath, Connector.READ_WRITE); is = file.openInputStream(); capturedImage = Image.createImage(is); } catch (IOException e) { Log.error("Problem creating image: " + e); removeProgressBar(); invalidate(); showMessage("An error occured processing the image."); return; } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { } } if (file != null && file.exists()) { if (file.isOpen()) { //file.close(); } //file.delete(); Log.info("Deleted image file."); } } if (capturedImage != null) { Log.info("Got image..."); MonochromeBitmapSource source = new LCDUIImageMonochromeBitmapSource(capturedImage); Result result; ReasonableTimer decodingTimer = null; try { decodingTimer = new ReasonableTimer(); Log.info("Attempting to decode image..."); result = reader.decode(source, readerHints); decodingTimer.finished(); } catch (ReaderException e) { Log.error("Could not decode image: " + e); decodingTimer.finished(); removeProgressBar(); invalidate(); boolean showResolutionMsg = !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue(); if (showResolutionMsg) { showMessage("A QR Code was not found in the image. " + "We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } else { showMessage("A QR Code was not found in the image."); } return; } if (result != null) { String resultText = result.getText(); Log.info("result: " + resultText); if (isURI(resultText)) { resultText = URLDecoder.decode(resultText); removeProgressBar(); invalidate(); if (!decodingTimer.wasResonableTime() && !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue()) { showMessage("We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } DecodeHistory.getInstance().addHistoryItem(new DecodeHistoryItem(resultText)); invokeBrowser(resultText); return; } } else { removeProgressBar(); invalidate(); showMessage("A QR Code was not found in the image."); return; } } removeProgressBar(); invalidate(); }
public void run() { FileConnection file = null; InputStream is = null; Image capturedImage = null; try { file = (FileConnection) Connector.open("file://" + imagePath, Connector.READ_WRITE); is = file.openInputStream(); capturedImage = Image.createImage(is); } catch (IOException e) { Log.error("Problem creating image: " + e); removeProgressBar(); invalidate(); showMessage("An error occured processing the image."); return; } finally { try { if (is != null) { is.close(); } if (file != null && file.exists()) { if (file.isOpen()) { file.close(); } file.delete(); Log.info("Deleted image file."); } } catch (IOException ioe) { Log.error("Error while closing file: " + ioe); } } if (capturedImage != null) { Log.info("Got image..."); MonochromeBitmapSource source = new LCDUIImageMonochromeBitmapSource(capturedImage); Result result; ReasonableTimer decodingTimer = null; try { decodingTimer = new ReasonableTimer(); Log.info("Attempting to decode image..."); result = reader.decode(source, readerHints); decodingTimer.finished(); } catch (ReaderException e) { Log.error("Could not decode image: " + e); decodingTimer.finished(); removeProgressBar(); invalidate(); boolean showResolutionMsg = !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue(); if (showResolutionMsg) { showMessage("A QR Code was not found in the image. " + "We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } else { showMessage("A QR Code was not found in the image."); } return; } if (result != null) { String resultText = result.getText(); Log.info("result: " + resultText); if (isURI(resultText)) { resultText = URLDecoder.decode(resultText); removeProgressBar(); invalidate(); if (!decodingTimer.wasResonableTime() && !AppSettings.getInstance().getBooleanItem(AppSettings.SETTING_CAM_RES_MSG).booleanValue()) { showMessage("We detected that the decoding process took quite a while. " + "It will be much faster if you decrease your camera's resolution (640x480)."); } DecodeHistory.getInstance().addHistoryItem(new DecodeHistoryItem(resultText)); invokeBrowser(resultText); return; } } else { removeProgressBar(); invalidate(); showMessage("A QR Code was not found in the image."); return; } } removeProgressBar(); invalidate(); }
diff --git a/gnu/testlet/java/io/FilePermission/simple.java b/gnu/testlet/java/io/FilePermission/simple.java index ff12c7e3..1a0791f6 100644 --- a/gnu/testlet/java/io/FilePermission/simple.java +++ b/gnu/testlet/java/io/FilePermission/simple.java @@ -1,182 +1,175 @@ // Copyright (C) 2003, Red Hat, Inc. // Copyright (C) 2004, Mark Wielaard <[email protected]> // // This file is part of Mauve. // // Mauve 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, or (at your option) // any later version. // // Mauve 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 Mauve; see the file COPYING. If not, write to // the Free Software Foundation, 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // // Tags: JDK1.2 package gnu.testlet.java.io.FilePermission; import gnu.testlet.*; import java.io.FilePermission; import java.security.Permissions; public class simple implements Testlet { public void test(TestHarness harness) { // Test for a classpath regression. Permissions p = new Permissions(); // (The following used to use the bogus action "nothing" ... but // the JDK 1.4.2 javadoc makes it clear that only actions "read", // "write", "execute" and "delete" are recognized. And the JDK // 1.4.2 implementation throws IllegalArgumentException for an // unrecognized action.) p.add(new FilePermission("/tmp/p", "read")); p.add(new FilePermission("/tmp/p", "read")); // Classpath didn't handle dirs without a file separator correctly FilePermission fp1 = new FilePermission("/tmp", "read"); harness.check(fp1.implies(fp1)); // Test the constructor's checking of its arguments. harness.checkPoint("constructor file arg checking"); try { harness.check(new FilePermission(null, "read") == null); } catch (java.lang.NullPointerException ex) { harness.check(true); } harness.checkPoint("constructor action checking (simple)"); harness.check(new FilePermission("/tmp/p", "read") != null); harness.check(new FilePermission("/tmp/p", "write") != null); harness.check(new FilePermission("/tmp/p", "execute") != null); harness.check(new FilePermission("/tmp/p", "delete") != null); harness.checkPoint("constructor action checking (lists)"); harness.check(new FilePermission("/tmp/p", "read,delete") != null); harness.check(new FilePermission("/tmp/p", "read,read") != null); harness.check(new FilePermission("/tmp/p", "read,read,read") != null); harness.checkPoint("constructor action checking (case)"); harness.check(new FilePermission("/tmp/p", "Read,DELETE") != null); harness.check(new FilePermission("/tmp/p", "rEAD") != null); harness.checkPoint("constructor action checking(underspecified)"); harness.check(new FilePermission("/tmp/p", " read ") != null); harness.check(new FilePermission("/tmp/p", "read, read") != null); harness.check(new FilePermission("/tmp/p", "read ,read") != null); harness.checkPoint("constructor action checking(bad actions)"); try { harness.check(new FilePermission("/tmp/p", null) == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", " ") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "foo") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "nothing") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } harness.checkPoint("constructor action checking(bad action lists)"); try { harness.check(new FilePermission("/tmp/p", ",") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } - // The following case fails under JDK 1.4.2. IMO, its a bug. - try { - harness.check(new FilePermission("/tmp/p", ",read") == null); - } - catch (java.lang.IllegalArgumentException ex) { - harness.check(true); - } try { harness.check(new FilePermission("/tmp/p", "read,") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "read,,read") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } harness.checkPoint("constructor action checking(wierd stuff)"); try { harness.check(new FilePermission("/tmp/p", "read read") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "read\nread") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "read;read") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } harness.checkPoint("implies() action checking"); for (int i = 1; i < 1 << actions.length; i++) { for (int j = 1; j < 1 << actions.length; j++) { FilePermission pi = new FilePermission("/tmp/p", makeActions(i)); FilePermission pj = new FilePermission("/tmp/p", makeActions(j)); harness.check(pi.implies(pj) == ((i & j) == j)); } } } // stuff for implies action checking private static String[] actions = {"read", "write", "execute", "delete"}; private static String makeActions(int mask) { String result = ""; for (int i = 0; i < actions.length; i++) { if ((mask & (1 << i)) != 0) { if (result.length() > 0) result += ","; result += actions[i]; } } return result; } }
true
true
public void test(TestHarness harness) { // Test for a classpath regression. Permissions p = new Permissions(); // (The following used to use the bogus action "nothing" ... but // the JDK 1.4.2 javadoc makes it clear that only actions "read", // "write", "execute" and "delete" are recognized. And the JDK // 1.4.2 implementation throws IllegalArgumentException for an // unrecognized action.) p.add(new FilePermission("/tmp/p", "read")); p.add(new FilePermission("/tmp/p", "read")); // Classpath didn't handle dirs without a file separator correctly FilePermission fp1 = new FilePermission("/tmp", "read"); harness.check(fp1.implies(fp1)); // Test the constructor's checking of its arguments. harness.checkPoint("constructor file arg checking"); try { harness.check(new FilePermission(null, "read") == null); } catch (java.lang.NullPointerException ex) { harness.check(true); } harness.checkPoint("constructor action checking (simple)"); harness.check(new FilePermission("/tmp/p", "read") != null); harness.check(new FilePermission("/tmp/p", "write") != null); harness.check(new FilePermission("/tmp/p", "execute") != null); harness.check(new FilePermission("/tmp/p", "delete") != null); harness.checkPoint("constructor action checking (lists)"); harness.check(new FilePermission("/tmp/p", "read,delete") != null); harness.check(new FilePermission("/tmp/p", "read,read") != null); harness.check(new FilePermission("/tmp/p", "read,read,read") != null); harness.checkPoint("constructor action checking (case)"); harness.check(new FilePermission("/tmp/p", "Read,DELETE") != null); harness.check(new FilePermission("/tmp/p", "rEAD") != null); harness.checkPoint("constructor action checking(underspecified)"); harness.check(new FilePermission("/tmp/p", " read ") != null); harness.check(new FilePermission("/tmp/p", "read, read") != null); harness.check(new FilePermission("/tmp/p", "read ,read") != null); harness.checkPoint("constructor action checking(bad actions)"); try { harness.check(new FilePermission("/tmp/p", null) == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", " ") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "foo") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "nothing") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } harness.checkPoint("constructor action checking(bad action lists)"); try { harness.check(new FilePermission("/tmp/p", ",") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } // The following case fails under JDK 1.4.2. IMO, its a bug. try { harness.check(new FilePermission("/tmp/p", ",read") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "read,") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "read,,read") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } harness.checkPoint("constructor action checking(wierd stuff)"); try { harness.check(new FilePermission("/tmp/p", "read read") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "read\nread") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "read;read") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } harness.checkPoint("implies() action checking"); for (int i = 1; i < 1 << actions.length; i++) { for (int j = 1; j < 1 << actions.length; j++) { FilePermission pi = new FilePermission("/tmp/p", makeActions(i)); FilePermission pj = new FilePermission("/tmp/p", makeActions(j)); harness.check(pi.implies(pj) == ((i & j) == j)); } } }
public void test(TestHarness harness) { // Test for a classpath regression. Permissions p = new Permissions(); // (The following used to use the bogus action "nothing" ... but // the JDK 1.4.2 javadoc makes it clear that only actions "read", // "write", "execute" and "delete" are recognized. And the JDK // 1.4.2 implementation throws IllegalArgumentException for an // unrecognized action.) p.add(new FilePermission("/tmp/p", "read")); p.add(new FilePermission("/tmp/p", "read")); // Classpath didn't handle dirs without a file separator correctly FilePermission fp1 = new FilePermission("/tmp", "read"); harness.check(fp1.implies(fp1)); // Test the constructor's checking of its arguments. harness.checkPoint("constructor file arg checking"); try { harness.check(new FilePermission(null, "read") == null); } catch (java.lang.NullPointerException ex) { harness.check(true); } harness.checkPoint("constructor action checking (simple)"); harness.check(new FilePermission("/tmp/p", "read") != null); harness.check(new FilePermission("/tmp/p", "write") != null); harness.check(new FilePermission("/tmp/p", "execute") != null); harness.check(new FilePermission("/tmp/p", "delete") != null); harness.checkPoint("constructor action checking (lists)"); harness.check(new FilePermission("/tmp/p", "read,delete") != null); harness.check(new FilePermission("/tmp/p", "read,read") != null); harness.check(new FilePermission("/tmp/p", "read,read,read") != null); harness.checkPoint("constructor action checking (case)"); harness.check(new FilePermission("/tmp/p", "Read,DELETE") != null); harness.check(new FilePermission("/tmp/p", "rEAD") != null); harness.checkPoint("constructor action checking(underspecified)"); harness.check(new FilePermission("/tmp/p", " read ") != null); harness.check(new FilePermission("/tmp/p", "read, read") != null); harness.check(new FilePermission("/tmp/p", "read ,read") != null); harness.checkPoint("constructor action checking(bad actions)"); try { harness.check(new FilePermission("/tmp/p", null) == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", " ") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "foo") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "nothing") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } harness.checkPoint("constructor action checking(bad action lists)"); try { harness.check(new FilePermission("/tmp/p", ",") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "read,") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "read,,read") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } harness.checkPoint("constructor action checking(wierd stuff)"); try { harness.check(new FilePermission("/tmp/p", "read read") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "read\nread") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } try { harness.check(new FilePermission("/tmp/p", "read;read") == null); } catch (java.lang.IllegalArgumentException ex) { harness.check(true); } harness.checkPoint("implies() action checking"); for (int i = 1; i < 1 << actions.length; i++) { for (int j = 1; j < 1 << actions.length; j++) { FilePermission pi = new FilePermission("/tmp/p", makeActions(i)); FilePermission pj = new FilePermission("/tmp/p", makeActions(j)); harness.check(pi.implies(pj) == ((i & j) == j)); } } }
diff --git a/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/IMSRTabToSampleTabLSFProcess.java b/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/IMSRTabToSampleTabLSFProcess.java index 5b1db11..ec8acec 100644 --- a/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/IMSRTabToSampleTabLSFProcess.java +++ b/conan-biosd-processes/src/main/java/uk/ac/ebi/fgpt/conan/process/biosd/IMSRTabToSampleTabLSFProcess.java @@ -1,78 +1,77 @@ package uk.ac.ebi.fgpt.conan.process.biosd; import net.sourceforge.fluxion.spi.ServiceProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.fgpt.conan.lsf.AbstractLSFProcess; import uk.ac.ebi.fgpt.conan.lsf.LSFProcess; import uk.ac.ebi.fgpt.conan.model.ConanParameter; import uk.ac.ebi.fgpt.conan.properties.ConanProperties; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Map; @ServiceProvider public class IMSRTabToSampleTabLSFProcess extends AbstractBioSDLSFProcess { private Logger log = LoggerFactory.getLogger(getClass()); public String getName() { return "topresampletabimsr"; } protected Logger getLog() { return log; } public Collection<ConanParameter> getParameters() { return parameters; } protected String getComponentName() { return LSFProcess.UNSPECIFIED_COMPONENT_NAME; } protected String getCommand(Map<ConanParameter, String> parameters) throws IllegalArgumentException { getLog().debug( "Executing " + getName() + " with the following parameters: " + parameters.toString()); // deal with parameters SampleTabAccessionParameter accession = new SampleTabAccessionParameter(); accession.setAccession(parameters.get(accessionParameter)); if (accession.getAccession() == null) { throw new IllegalArgumentException("Accession cannot be null"); } String scriptpath = ConanProperties .getProperty("biosamples.script.path"); File script = new File(scriptpath, "IMSRTabToSampleTab.sh"); File outdir; try { outdir = getOutputDirectory(accession); } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException("Unable to create directories for "+accession); } - String imsrTabFilename = "raw.tab.txt"; - File imsrTabFile = new File(outdir, imsrTabFilename); + File imsrTabFile = new File(outdir, "raw.tab.txt"); if (!imsrTabFile.exists()){ throw new IllegalArgumentException("IMSR Tab file does not exist for "+accession); } File sampletabFile = new File(outdir, "sampletab.pre.txt"); // main command to execute script String mainCommand = script.getAbsolutePath() + " " + imsrTabFile.getAbsolutePath() + " " + sampletabFile.getAbsolutePath(); getLog().debug("Command is: <" + mainCommand + ">"); return mainCommand; } }
true
true
protected String getCommand(Map<ConanParameter, String> parameters) throws IllegalArgumentException { getLog().debug( "Executing " + getName() + " with the following parameters: " + parameters.toString()); // deal with parameters SampleTabAccessionParameter accession = new SampleTabAccessionParameter(); accession.setAccession(parameters.get(accessionParameter)); if (accession.getAccession() == null) { throw new IllegalArgumentException("Accession cannot be null"); } String scriptpath = ConanProperties .getProperty("biosamples.script.path"); File script = new File(scriptpath, "IMSRTabToSampleTab.sh"); File outdir; try { outdir = getOutputDirectory(accession); } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException("Unable to create directories for "+accession); } String imsrTabFilename = "raw.tab.txt"; File imsrTabFile = new File(outdir, imsrTabFilename); if (!imsrTabFile.exists()){ throw new IllegalArgumentException("IMSR Tab file does not exist for "+accession); } File sampletabFile = new File(outdir, "sampletab.pre.txt"); // main command to execute script String mainCommand = script.getAbsolutePath() + " " + imsrTabFile.getAbsolutePath() + " " + sampletabFile.getAbsolutePath(); getLog().debug("Command is: <" + mainCommand + ">"); return mainCommand; }
protected String getCommand(Map<ConanParameter, String> parameters) throws IllegalArgumentException { getLog().debug( "Executing " + getName() + " with the following parameters: " + parameters.toString()); // deal with parameters SampleTabAccessionParameter accession = new SampleTabAccessionParameter(); accession.setAccession(parameters.get(accessionParameter)); if (accession.getAccession() == null) { throw new IllegalArgumentException("Accession cannot be null"); } String scriptpath = ConanProperties .getProperty("biosamples.script.path"); File script = new File(scriptpath, "IMSRTabToSampleTab.sh"); File outdir; try { outdir = getOutputDirectory(accession); } catch (IOException e) { e.printStackTrace(); throw new IllegalArgumentException("Unable to create directories for "+accession); } File imsrTabFile = new File(outdir, "raw.tab.txt"); if (!imsrTabFile.exists()){ throw new IllegalArgumentException("IMSR Tab file does not exist for "+accession); } File sampletabFile = new File(outdir, "sampletab.pre.txt"); // main command to execute script String mainCommand = script.getAbsolutePath() + " " + imsrTabFile.getAbsolutePath() + " " + sampletabFile.getAbsolutePath(); getLog().debug("Command is: <" + mainCommand + ">"); return mainCommand; }
diff --git a/src/main/java/com/smarchive/dropwizard/gelf/filters/GelfLoggingFilter.java b/src/main/java/com/smarchive/dropwizard/gelf/filters/GelfLoggingFilter.java index 5a82f43..4e174dd 100644 --- a/src/main/java/com/smarchive/dropwizard/gelf/filters/GelfLoggingFilter.java +++ b/src/main/java/com/smarchive/dropwizard/gelf/filters/GelfLoggingFilter.java @@ -1,243 +1,243 @@ package com.smarchive.dropwizard.gelf.filters; import com.google.common.base.Stopwatch; import com.google.common.io.CountingOutputStream; import com.google.common.net.HttpHeaders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponseWrapper; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * A {@link Filter} which logs requests and adds some data about it to the logger's {@link MDC}. */ public class GelfLoggingFilter implements Filter { private static final Logger LOG = LoggerFactory.getLogger(GelfLoggingFilter.class); /** * Called by the web container to indicate to a filter that it is * being placed into service. * <p/> * <p>The servlet container calls the init * method exactly once after instantiating the filter. The init * method must complete successfully before the filter is asked to do any * filtering work. * <p/> * <p>The web container cannot place the filter into service if the init * method either * <ol> * <li>Throws a ServletException * <li>Does not return within a time period defined by the web container * </ol> * * @param filterConfig the {@link FilterChain} for this {@link Filter} * @throws ServletException if something goes wrong */ @Override public void init(FilterConfig filterConfig) throws ServletException { // Do nothing } /** * The <code>doFilter</code> method of the Filter is called by the * container each time a request/response pair is passed through the * chain due to a client request for a resource at the end of the chain. * The FilterChain passed in to this method allows the Filter to pass * on the request and response to the next entity in the chain. * <p/> * <p>A typical implementation of this method would follow the following * pattern: * <ol> * <li>Examine the request * <li>Optionally wrap the request object with a custom implementation to * filter content or headers for input filtering * <li>Optionally wrap the response object with a custom implementation to * filter content or headers for output filtering * <li> * <ul> * <li><strong>Either</strong> invoke the next entity in the chain * using the FilterChain object * (<code>chain.doFilter()</code>), * <li><strong>or</strong> not pass on the request/response pair to * the next entity in the filter chain to * block the request processing * </ul> * <li>Directly set headers on the response after invocation of the * next entity in the filter chain. * </ol> */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final Stopwatch stopwatch = new Stopwatch(); // It's quite safe to assume that we only receive HTTP requests final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; String address = httpRequest.getHeader(HttpHeaders.X_FORWARDED_FOR); if (address == null) { address = request.getRemoteAddr(); } MDC.put("remoteAddress", address); MDC.put("httpMethod", httpRequest.getMethod()); MDC.put("protocol", httpRequest.getProtocol()); MDC.put("requestUri", httpRequest.getRequestURI()); MDC.put("requestLength", String.valueOf(httpRequest.getContentLength())); MDC.put("requestContentType", httpRequest.getContentType()); MDC.put("requestEncoding", httpRequest.getCharacterEncoding()); final String userAgent = httpRequest.getHeader(HttpHeaders.USER_AGENT); if (userAgent != null) { MDC.put("userAgent", userAgent); } final String authType = httpRequest.getAuthType(); if (authType != null) { MDC.put("requestAuth", authType); MDC.put("userPrincipal", httpRequest.getUserPrincipal().getName()); } final CountingHttpServletResponseWrapper responseWrapper = new CountingHttpServletResponseWrapper(httpResponse); stopwatch.start(); chain.doFilter(request, responseWrapper); stopwatch.stop(); MDC.put("responseStatus", String.valueOf(httpResponse.getStatus())); MDC.put("responseContentType", httpResponse.getContentType()); MDC.put("responseEncoding", httpResponse.getCharacterEncoding()); - MDC.put("responseTimeNanos", String.valueOf(stopwatch.elapsedTime(TimeUnit.NANOSECONDS))); + MDC.put("responseTimeNanos", String.valueOf(stopwatch.elapsed(TimeUnit.NANOSECONDS))); MDC.put("responseLength", String.valueOf(responseWrapper.getCount())); LOG.info("{} {} {}", httpRequest.getMethod(), httpRequest.getRequestURI(), httpRequest.getProtocol()); // This should be safe since the request has been processed completely MDC.clear(); } /** * Called by the web container to indicate to a filter that it is being * taken out of service. * <p/> * <p>This method is only called once all threads within the filter's * doFilter method have exited or after a timeout period has passed. * After the web container calls this method, it will not call the * doFilter method again on this instance of the filter. * <p/> * <p>This method gives the filter an opportunity to clean up any * resources that are being held (for example, memory, file handles, * threads) and make sure that any persistent state is synchronized * with the filter's current state in memory. */ @Override public void destroy() { // Do nothing } /** * An implementation of {@link ServletOutputStream} which counts the bytes being * written using a {@link CountingOutputStream}. */ private static final class CountingServletOutputStream extends ServletOutputStream { private final CountingOutputStream outputStream; private CountingServletOutputStream(ServletOutputStream servletOutputStream) { this.outputStream = new CountingOutputStream(servletOutputStream); } /** * Writes the specified byte to this output stream. The general * contract for <code>write</code> is that one byte is written * to the output stream. The byte to be written is the eight * low-order bits of the argument <code>b</code>. The 24 * high-order bits of <code>b</code> are ignored. * <p/> * Subclasses of <code>OutputStream</code> must provide an * implementation for this method. * * @param b the <code>byte</code>. * @throws java.io.IOException if an I/O error occurs. In particular, * an <code>IOException</code> may be thrown if the * output stream has been closed. */ @Override public void write(int b) throws IOException { outputStream.write(b); } public long getCount() { return outputStream.getCount(); } } /** * An implementation of {@link HttpServletResponseWrapper} which counts the bytes being written as the response * body using a {@link CountingServletOutputStream}. */ private static final class CountingHttpServletResponseWrapper extends HttpServletResponseWrapper { private CountingServletOutputStream outputStream; private CountingHttpServletResponseWrapper(HttpServletResponse response) throws IOException { super(response); } /** * The default behavior of this method is to return getOutputStream() * on the wrapped response object. */ @Override public ServletOutputStream getOutputStream() throws IOException { if (outputStream == null) { outputStream = new CountingServletOutputStream(getResponse().getOutputStream()); } return outputStream; } /** * Get the number of bytes written to the response output stream. * * @return the number of bytes written to the response output stream */ public long getCount() { return outputStream == null ? 0L : outputStream.getCount(); } /** * The default behavior of this method is to call resetBuffer() on the wrapped response object. * * @see javax.servlet.http.HttpServletResponseWrapper#resetBuffer() */ @Override public void resetBuffer() { super.resetBuffer(); outputStream = null; } /** * The default behavior of this method is to call reset() on the wrapped response object. * * @see javax.servlet.http.HttpServletResponseWrapper#reset() */ @Override public void reset() { super.reset(); outputStream = null; } } }
true
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final Stopwatch stopwatch = new Stopwatch(); // It's quite safe to assume that we only receive HTTP requests final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; String address = httpRequest.getHeader(HttpHeaders.X_FORWARDED_FOR); if (address == null) { address = request.getRemoteAddr(); } MDC.put("remoteAddress", address); MDC.put("httpMethod", httpRequest.getMethod()); MDC.put("protocol", httpRequest.getProtocol()); MDC.put("requestUri", httpRequest.getRequestURI()); MDC.put("requestLength", String.valueOf(httpRequest.getContentLength())); MDC.put("requestContentType", httpRequest.getContentType()); MDC.put("requestEncoding", httpRequest.getCharacterEncoding()); final String userAgent = httpRequest.getHeader(HttpHeaders.USER_AGENT); if (userAgent != null) { MDC.put("userAgent", userAgent); } final String authType = httpRequest.getAuthType(); if (authType != null) { MDC.put("requestAuth", authType); MDC.put("userPrincipal", httpRequest.getUserPrincipal().getName()); } final CountingHttpServletResponseWrapper responseWrapper = new CountingHttpServletResponseWrapper(httpResponse); stopwatch.start(); chain.doFilter(request, responseWrapper); stopwatch.stop(); MDC.put("responseStatus", String.valueOf(httpResponse.getStatus())); MDC.put("responseContentType", httpResponse.getContentType()); MDC.put("responseEncoding", httpResponse.getCharacterEncoding()); MDC.put("responseTimeNanos", String.valueOf(stopwatch.elapsedTime(TimeUnit.NANOSECONDS))); MDC.put("responseLength", String.valueOf(responseWrapper.getCount())); LOG.info("{} {} {}", httpRequest.getMethod(), httpRequest.getRequestURI(), httpRequest.getProtocol()); // This should be safe since the request has been processed completely MDC.clear(); }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final Stopwatch stopwatch = new Stopwatch(); // It's quite safe to assume that we only receive HTTP requests final HttpServletRequest httpRequest = (HttpServletRequest) request; final HttpServletResponse httpResponse = (HttpServletResponse) response; String address = httpRequest.getHeader(HttpHeaders.X_FORWARDED_FOR); if (address == null) { address = request.getRemoteAddr(); } MDC.put("remoteAddress", address); MDC.put("httpMethod", httpRequest.getMethod()); MDC.put("protocol", httpRequest.getProtocol()); MDC.put("requestUri", httpRequest.getRequestURI()); MDC.put("requestLength", String.valueOf(httpRequest.getContentLength())); MDC.put("requestContentType", httpRequest.getContentType()); MDC.put("requestEncoding", httpRequest.getCharacterEncoding()); final String userAgent = httpRequest.getHeader(HttpHeaders.USER_AGENT); if (userAgent != null) { MDC.put("userAgent", userAgent); } final String authType = httpRequest.getAuthType(); if (authType != null) { MDC.put("requestAuth", authType); MDC.put("userPrincipal", httpRequest.getUserPrincipal().getName()); } final CountingHttpServletResponseWrapper responseWrapper = new CountingHttpServletResponseWrapper(httpResponse); stopwatch.start(); chain.doFilter(request, responseWrapper); stopwatch.stop(); MDC.put("responseStatus", String.valueOf(httpResponse.getStatus())); MDC.put("responseContentType", httpResponse.getContentType()); MDC.put("responseEncoding", httpResponse.getCharacterEncoding()); MDC.put("responseTimeNanos", String.valueOf(stopwatch.elapsed(TimeUnit.NANOSECONDS))); MDC.put("responseLength", String.valueOf(responseWrapper.getCount())); LOG.info("{} {} {}", httpRequest.getMethod(), httpRequest.getRequestURI(), httpRequest.getProtocol()); // This should be safe since the request has been processed completely MDC.clear(); }
diff --git a/src/driver/Driver.java b/src/driver/Driver.java index 17a2531..9d6e272 100644 --- a/src/driver/Driver.java +++ b/src/driver/Driver.java @@ -1,20 +1,20 @@ package driver; import world.Grid; import gui.GameDisplay; public class Driver { public static void main(String[] args) { Grid g = new Grid(); GameDisplay display = new GameDisplay(g); long s = System.currentTimeMillis(); while ((s - System.currentTimeMillis()) < 0){ - s = System.currentTimeMillis(); if ((System.currentTimeMillis() - s) >= 1000){ display.redraw(g); + s = System.currentTimeMillis(); } } } }
false
true
public static void main(String[] args) { Grid g = new Grid(); GameDisplay display = new GameDisplay(g); long s = System.currentTimeMillis(); while ((s - System.currentTimeMillis()) < 0){ s = System.currentTimeMillis(); if ((System.currentTimeMillis() - s) >= 1000){ display.redraw(g); } } }
public static void main(String[] args) { Grid g = new Grid(); GameDisplay display = new GameDisplay(g); long s = System.currentTimeMillis(); while ((s - System.currentTimeMillis()) < 0){ if ((System.currentTimeMillis() - s) >= 1000){ display.redraw(g); s = System.currentTimeMillis(); } } }
diff --git a/src/gwt/src/org/rstudio/core/client/widget/HtmlFormModalDialog.java b/src/gwt/src/org/rstudio/core/client/widget/HtmlFormModalDialog.java index 352162e9c4..38a73706c6 100644 --- a/src/gwt/src/org/rstudio/core/client/widget/HtmlFormModalDialog.java +++ b/src/gwt/src/org/rstudio/core/client/widget/HtmlFormModalDialog.java @@ -1,137 +1,136 @@ /* * HtmlFormModalDialog.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client.widget; import com.google.gwt.core.client.JavaScriptException; import com.google.gwt.core.client.Scheduler; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.FormPanel; import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent; import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler; import com.google.gwt.user.client.ui.FormPanel.SubmitEvent; import com.google.gwt.user.client.ui.FormPanel.SubmitHandler; import org.rstudio.core.client.Debug; import org.rstudio.core.client.StringUtil; public abstract class HtmlFormModalDialog<T> extends ModalDialogBase { public HtmlFormModalDialog(String title, final String progressMessage, String actionURL, final OperationWithInput<T> operation) { super(new FormPanel()); setText(title); final FormPanel formPanel = (FormPanel)getContainerPanel(); formPanel.getElement().getStyle().setProperty("margin", "0px"); formPanel.getElement().getStyle().setProperty("padding", "0px"); formPanel.setAction(actionURL); setFormPanelEncodingAndMethod(formPanel); final ProgressIndicator progressIndicator = addProgressIndicator(); ThemedButton okButton = new ThemedButton("OK", new ClickHandler() { public void onClick(ClickEvent event) { try { formPanel.submit(); } catch (final JavaScriptException e) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { if ("Access is denied.".equals( StringUtil.notNull(e.getDescription()).trim())) { progressIndicator.onError( - "For security reasons, you must click the " + - "Browse button and choose your file."); + "Please use a complete file path."); } else { Debug.log(e.toString()); progressIndicator.onError(e.getDescription()); } } }); } catch (final Exception e) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { Debug.log(e.toString()); progressIndicator.onError(e.getMessage()); } }); } } }); addOkButton(okButton); addCancelButton(); formPanel.addSubmitHandler(new SubmitHandler() { public void onSubmit(SubmitEvent event) { if (validate()) { progressIndicator.onProgress(progressMessage); } else { event.cancel(); } } }); formPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() { public void onSubmitComplete(SubmitCompleteEvent event) { String resultsText = event.getResults(); if (resultsText != null) { try { T results = parseResults(resultsText); progressIndicator.onCompleted(); operation.execute(results); } catch(Exception e) { progressIndicator.onError(e.getMessage()); } } else { progressIndicator.onError( "Unexpected empty response from server"); } } }); } protected void setFormPanelEncodingAndMethod(FormPanel formPanel) { formPanel.setEncoding(FormPanel.ENCODING_URLENCODED); formPanel.setMethod(FormPanel.METHOD_POST); } protected abstract boolean validate(); protected abstract T parseResults(String results) throws Exception; }
true
true
public HtmlFormModalDialog(String title, final String progressMessage, String actionURL, final OperationWithInput<T> operation) { super(new FormPanel()); setText(title); final FormPanel formPanel = (FormPanel)getContainerPanel(); formPanel.getElement().getStyle().setProperty("margin", "0px"); formPanel.getElement().getStyle().setProperty("padding", "0px"); formPanel.setAction(actionURL); setFormPanelEncodingAndMethod(formPanel); final ProgressIndicator progressIndicator = addProgressIndicator(); ThemedButton okButton = new ThemedButton("OK", new ClickHandler() { public void onClick(ClickEvent event) { try { formPanel.submit(); } catch (final JavaScriptException e) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { if ("Access is denied.".equals( StringUtil.notNull(e.getDescription()).trim())) { progressIndicator.onError( "For security reasons, you must click the " + "Browse button and choose your file."); } else { Debug.log(e.toString()); progressIndicator.onError(e.getDescription()); } } }); } catch (final Exception e) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { Debug.log(e.toString()); progressIndicator.onError(e.getMessage()); } }); } } }); addOkButton(okButton); addCancelButton(); formPanel.addSubmitHandler(new SubmitHandler() { public void onSubmit(SubmitEvent event) { if (validate()) { progressIndicator.onProgress(progressMessage); } else { event.cancel(); } } }); formPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() { public void onSubmitComplete(SubmitCompleteEvent event) { String resultsText = event.getResults(); if (resultsText != null) { try { T results = parseResults(resultsText); progressIndicator.onCompleted(); operation.execute(results); } catch(Exception e) { progressIndicator.onError(e.getMessage()); } } else { progressIndicator.onError( "Unexpected empty response from server"); } } }); }
public HtmlFormModalDialog(String title, final String progressMessage, String actionURL, final OperationWithInput<T> operation) { super(new FormPanel()); setText(title); final FormPanel formPanel = (FormPanel)getContainerPanel(); formPanel.getElement().getStyle().setProperty("margin", "0px"); formPanel.getElement().getStyle().setProperty("padding", "0px"); formPanel.setAction(actionURL); setFormPanelEncodingAndMethod(formPanel); final ProgressIndicator progressIndicator = addProgressIndicator(); ThemedButton okButton = new ThemedButton("OK", new ClickHandler() { public void onClick(ClickEvent event) { try { formPanel.submit(); } catch (final JavaScriptException e) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { if ("Access is denied.".equals( StringUtil.notNull(e.getDescription()).trim())) { progressIndicator.onError( "Please use a complete file path."); } else { Debug.log(e.toString()); progressIndicator.onError(e.getDescription()); } } }); } catch (final Exception e) { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { Debug.log(e.toString()); progressIndicator.onError(e.getMessage()); } }); } } }); addOkButton(okButton); addCancelButton(); formPanel.addSubmitHandler(new SubmitHandler() { public void onSubmit(SubmitEvent event) { if (validate()) { progressIndicator.onProgress(progressMessage); } else { event.cancel(); } } }); formPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() { public void onSubmitComplete(SubmitCompleteEvent event) { String resultsText = event.getResults(); if (resultsText != null) { try { T results = parseResults(resultsText); progressIndicator.onCompleted(); operation.execute(results); } catch(Exception e) { progressIndicator.onError(e.getMessage()); } } else { progressIndicator.onError( "Unexpected empty response from server"); } } }); }
diff --git a/src/main/java/cc/thedudeguy/xpinthejar/CommandHandler.java b/src/main/java/cc/thedudeguy/xpinthejar/CommandHandler.java index b28f189..aa1866d 100644 --- a/src/main/java/cc/thedudeguy/xpinthejar/CommandHandler.java +++ b/src/main/java/cc/thedudeguy/xpinthejar/CommandHandler.java @@ -1,36 +1,36 @@ package cc.thedudeguy.xpinthejar; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; /** * @author bendem */ public class CommandHandler implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { - if(!"xpjar".equalsIgnoreCase(label)) { + if(!command.getName().equalsIgnoreCase("xpinthejar")) { return false; } if(!sender.hasPermission("xpjar.command.debug")) { sender.sendMessage(ChatColor.RED + "You don't have the permission to use this command!"); return true; } if(args.length == 2 && "debug".equalsIgnoreCase(args[0])) { if("true".equalsIgnoreCase(args[1]) || "false".equalsIgnoreCase(args[1])) { XPInTheJar.instance.getConfig().set("debug", "true".equalsIgnoreCase(args[1])); XPInTheJar.instance.saveConfig(); sender.sendMessage("Debug " + (XPInTheJar.instance.getConfig().getBoolean("debug") ? "" : "de") + "activated"); } else { sender.sendMessage("Debug value can only be 'true' or 'false'"); } return true; } return false; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!"xpjar".equalsIgnoreCase(label)) { return false; } if(!sender.hasPermission("xpjar.command.debug")) { sender.sendMessage(ChatColor.RED + "You don't have the permission to use this command!"); return true; } if(args.length == 2 && "debug".equalsIgnoreCase(args[0])) { if("true".equalsIgnoreCase(args[1]) || "false".equalsIgnoreCase(args[1])) { XPInTheJar.instance.getConfig().set("debug", "true".equalsIgnoreCase(args[1])); XPInTheJar.instance.saveConfig(); sender.sendMessage("Debug " + (XPInTheJar.instance.getConfig().getBoolean("debug") ? "" : "de") + "activated"); } else { sender.sendMessage("Debug value can only be 'true' or 'false'"); } return true; } return false; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!command.getName().equalsIgnoreCase("xpinthejar")) { return false; } if(!sender.hasPermission("xpjar.command.debug")) { sender.sendMessage(ChatColor.RED + "You don't have the permission to use this command!"); return true; } if(args.length == 2 && "debug".equalsIgnoreCase(args[0])) { if("true".equalsIgnoreCase(args[1]) || "false".equalsIgnoreCase(args[1])) { XPInTheJar.instance.getConfig().set("debug", "true".equalsIgnoreCase(args[1])); XPInTheJar.instance.saveConfig(); sender.sendMessage("Debug " + (XPInTheJar.instance.getConfig().getBoolean("debug") ? "" : "de") + "activated"); } else { sender.sendMessage("Debug value can only be 'true' or 'false'"); } return true; } return false; }
diff --git a/hospiceApp/src/hospiceapp/HospiceApp.java b/hospiceApp/src/hospiceapp/HospiceApp.java index c9a20e5..19364dd 100644 --- a/hospiceApp/src/hospiceapp/HospiceApp.java +++ b/hospiceApp/src/hospiceapp/HospiceApp.java @@ -1,19 +1,20 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hospiceapp; /** * * @author workstation */ public class HospiceApp { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here + System.out.println("Hello world"); } }
true
true
public static void main(String[] args) { // TODO code application logic here }
public static void main(String[] args) { // TODO code application logic here System.out.println("Hello world"); }
diff --git a/PVUgame/src/no/hist/gruppe5/pvu/reqfinder/ReqFinderScreen.java b/PVUgame/src/no/hist/gruppe5/pvu/reqfinder/ReqFinderScreen.java index 83284a2..ef69e13 100644 --- a/PVUgame/src/no/hist/gruppe5/pvu/reqfinder/ReqFinderScreen.java +++ b/PVUgame/src/no/hist/gruppe5/pvu/reqfinder/ReqFinderScreen.java @@ -1,282 +1,281 @@ package no.hist.gruppe5.pvu.reqfinder; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; import no.hist.gruppe5.pvu.Assets; import no.hist.gruppe5.pvu.GameScreen; import no.hist.gruppe5.pvu.Input; import no.hist.gruppe5.pvu.PVU; import no.hist.gruppe5.pvu.ScoreHandler; import no.hist.gruppe5.pvu.quiz.QuizHandler; /** * * @author Martin */ public class ReqFinderScreen extends GameScreen { private String mCaseText; private Stage mStage;; private LabelStyle mLabelStyle; private LabelStyle mCorrectLabelStyle; private LabelStyle mWrongLabelStyle; private LabelStyle mHighlightedLabelStyle; private LabelStyle mLivesStyle; private ArrayList<Label> mLabels = new ArrayList<>(); private Label mHighlightedLabel; private int mHighlightedIndex; private String[] mCorrectWords= {"interaktivt", "skjema,", "kundeprofil", "profilside", "instant", "messaging-tjeneste", "(IM-tjeneste).", "prosjektbestillinger", "fysikksimulator"}; private Input mInput = new Input(); private int mLives = mCorrectWords.length; private Label mLivesLabel; private int mCorrectCounter = 0; public ReqFinderScreen(PVU pvu) { super(pvu); try { mCaseText = Assets.readFile("data/case.txt"); } catch (FileNotFoundException ex) { Logger.getLogger(ReqFinderScreen.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ReqFinderScreen.class.getName()).log(Level.SEVERE, null, ex); } BitmapFont kopiert = new BitmapFont( Gdx.files.internal("data/LucidaBitmap10px.fnt"), Gdx.files.internal("data/LucidaBitmap10px_0.png"), false); mLabelStyle = new LabelStyle(kopiert, Color.BLACK); mHighlightedLabelStyle = new LabelStyle(kopiert, Color.BLUE); mWrongLabelStyle = new LabelStyle(kopiert, Color.RED); mCorrectLabelStyle = new LabelStyle(kopiert, Color.GREEN); mLivesStyle = new LabelStyle(kopiert, Color.RED); mStage = new Stage(PVU.SCREEN_WIDTH, PVU.SCREEN_HEIGHT, true); mStage.setViewport(mStage.getWidth(), mStage.getHeight(), true, 0, 0, mStage.getWidth(), mStage.getHeight()); StringTokenizer st = new StringTokenizer(mCaseText); mLabelStyle.font.scale(1.5f); Label initLabel = new Label("Hei", mHighlightedLabelStyle); initLabel.setPosition(0, PVU.SCREEN_HEIGHT - initLabel.getHeight()); System.out.println(initLabel.getX() + " " + initLabel.getY()); mLabels.add(initLabel); mStage.addActor(initLabel); mHighlightedLabel = initLabel; mHighlightedIndex = 0; float labelLength = 0; while (st.hasMoreTokens()) { mLabels.add(new Label(st.nextToken(" "), mLabelStyle)); if (labelLength + mLabels.get(mLabels.size() - 1).getWidth() > PVU.SCREEN_WIDTH - 5) { mLabels.get(mLabels.size() - 1).setPosition(0, mLabels.get(mLabels.size() - 2).getY() - mLabels.get(mLabels.size() - 1).getHeight()); labelLength = 0; } else { mLabels.get(mLabels.size() - 1).setPosition(mLabels.get(mLabels.size() - 2).getX() + mLabels.get(mLabels.size() - 2).getWidth() + 5, mLabels.get(mLabels.size() - 2).getY()); } labelLength = mLabels.get(mLabels.size() - 1).getX() + mLabels.get(mLabels.size() - 1).getWidth(); mStage.addActor(mLabels.get(mLabels.size() - 1)); } mLivesLabel = new Label(""+mLives, mLivesStyle); mLivesLabel.setPosition(PVU.SCREEN_WIDTH-mLivesLabel.getWidth() - 5, 5); mStage.addActor(mLivesLabel); } @Override protected void draw(float delta) { clearCamera(1, 1, 1, 1); // Important mStage.draw(); } @Override protected void update(float delta) { if (mCorrectCounter == mCorrectWords.length) { //won reportScore(); game.setScreen(new ReqFinderEndScreen(game, mLives, mCorrectWords.length)); } if (mLives <= 0) { reportScore(); game.setScreen(new ReqFinderEndScreen(game, mLives, mCorrectWords.length)); } if (mInput.right() && !isRightmost()) { mHighlightedIndex++; if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mInput.left() && !isLeftmost()) { mHighlightedIndex--; if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mInput.down() && !isBotmost()) { mHighlightedIndex = findLabelUnder(mHighlightedLabel); if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mInput.up() && !isUpmost()) { mHighlightedIndex = findLabelAbove(mHighlightedLabel); if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mLives != 0 && mInput.action()) { if(isCorrect()) { mHighlightedLabel.setStyle(mCorrectLabelStyle); mCorrectCounter++; } else { mHighlightedLabel.setStyle(mWrongLabelStyle); mLives--; mLivesLabel.setText(""+mLives); } } else if (mInput.alternateAction()) { - QuizHandler.updateFinishedMiniGame(); ScoreHandler.updateScore(ScoreHandler.REQ, 10); game.setScreen(PVU.MAIN_SCREEN); reportScore(); } } @Override protected void cleanUp() { } private boolean isLeftmost() { if (mHighlightedLabel.getX() == 0) { return true; } else { return false; } } private boolean isRightmost() { for (int i = 0; i < mLabels.size(); i++) { if (mHighlightedLabel == mLabels.get(i)) { if (mLabels.get(i + 1).getY() != mHighlightedLabel.getY()) { return true; } else { return false; } } } return false; } private boolean isUpmost() { if (mHighlightedLabel.getY() - mHighlightedLabel.getHeight() >= PVU.SCREEN_HEIGHT) { return true; } else { return false; } } private boolean isBotmost() { for (int i = 0; i < mLabels.size(); i++) { if(mHighlightedLabel == mLabels.get(i)) { for(int j = 0; j < mLabels.size(); j++) { if(mLabels.get(j).getY() != mHighlightedLabel.getY()) return false; } } } return true; } private int findLabelUnder(Label current) { int nextRowStart = 0; int nextRowEnd = 0; for(int i = mHighlightedIndex; i < mLabels.size(); i++) { if(mLabels.get(i).getY() != mHighlightedLabel.getY()) { nextRowStart = i; break; } } for(int i = nextRowStart; i < mLabels.size(); i++) { if(mLabels.get(i).getY() != mLabels.get(nextRowStart).getY()) { nextRowEnd = i-1; break; } } float currentXAvg = (current.getX() + (current.getX()+current.getWidth()))/2; float shortestDistance = Math.abs(currentXAvg-(mLabels.get(nextRowStart).getX() + (mLabels.get(nextRowStart).getX() + mLabels.get(nextRowStart).getWidth()))/2); int shortestIndex = nextRowStart; for(int i = nextRowStart+1; i <= nextRowEnd; i++) { float distance = Math.abs(currentXAvg-(mLabels.get(i).getX() + (mLabels.get(i).getX() + mLabels.get(i).getWidth()))/2); if(distance < shortestDistance) { shortestDistance = distance; shortestIndex = i; } } return shortestIndex; } private int findLabelAbove(Label current) { int nextRowStart = 0; int nextRowEnd = 0; for(int i = mHighlightedIndex; i > 0; i--) { if(mLabels.get(i).getY() != mHighlightedLabel.getY()) { nextRowEnd = i; break; } } for(int i = nextRowEnd; i > 0; i--) { if(mLabels.get(i).getY() != mLabels.get(nextRowEnd).getY()) { nextRowStart = i+1; break; } } float currentXAvg = (current.getX() + (current.getX()+current.getWidth()))/2; float shortestDistance = Math.abs(currentXAvg-(mLabels.get(nextRowStart).getX() + (mLabels.get(nextRowStart).getX() + mLabels.get(nextRowStart).getWidth()))/2); int shortestIndex = nextRowStart; for(int i = nextRowStart+1; i <= nextRowEnd; i++) { float distance = Math.abs(currentXAvg-(mLabels.get(i).getX() + (mLabels.get(i).getX() + mLabels.get(i).getWidth()))/2); if(distance < shortestDistance) { shortestDistance = distance; shortestIndex = i; } } return shortestIndex; } private boolean isCorrect() { for(int i = 0; i < mCorrectWords.length; i++) { if(mCorrectWords[i].equalsIgnoreCase(mHighlightedLabel.getText().toString())) { return true; } } return false; } private void reportScore() { float score = (float) (1.0-((float)mCorrectWords.length-(float)mLives)/(float)mCorrectWords.length); System.out.println((int)(score*100)); QuizHandler.updateQuizScore((int)(score*100), ScoreHandler.REQ); ScoreHandler.updateScore(ScoreHandler.REQ, score); } }
true
true
protected void update(float delta) { if (mCorrectCounter == mCorrectWords.length) { //won reportScore(); game.setScreen(new ReqFinderEndScreen(game, mLives, mCorrectWords.length)); } if (mLives <= 0) { reportScore(); game.setScreen(new ReqFinderEndScreen(game, mLives, mCorrectWords.length)); } if (mInput.right() && !isRightmost()) { mHighlightedIndex++; if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mInput.left() && !isLeftmost()) { mHighlightedIndex--; if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mInput.down() && !isBotmost()) { mHighlightedIndex = findLabelUnder(mHighlightedLabel); if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mInput.up() && !isUpmost()) { mHighlightedIndex = findLabelAbove(mHighlightedLabel); if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mLives != 0 && mInput.action()) { if(isCorrect()) { mHighlightedLabel.setStyle(mCorrectLabelStyle); mCorrectCounter++; } else { mHighlightedLabel.setStyle(mWrongLabelStyle); mLives--; mLivesLabel.setText(""+mLives); } } else if (mInput.alternateAction()) { QuizHandler.updateFinishedMiniGame(); ScoreHandler.updateScore(ScoreHandler.REQ, 10); game.setScreen(PVU.MAIN_SCREEN); reportScore(); } }
protected void update(float delta) { if (mCorrectCounter == mCorrectWords.length) { //won reportScore(); game.setScreen(new ReqFinderEndScreen(game, mLives, mCorrectWords.length)); } if (mLives <= 0) { reportScore(); game.setScreen(new ReqFinderEndScreen(game, mLives, mCorrectWords.length)); } if (mInput.right() && !isRightmost()) { mHighlightedIndex++; if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mInput.left() && !isLeftmost()) { mHighlightedIndex--; if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mInput.down() && !isBotmost()) { mHighlightedIndex = findLabelUnder(mHighlightedLabel); if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mInput.up() && !isUpmost()) { mHighlightedIndex = findLabelAbove(mHighlightedLabel); if(mHighlightedLabel.getStyle().equals(mHighlightedLabelStyle)) { mHighlightedLabel.setStyle(mLabelStyle); } mHighlightedLabel = mLabels.get(mHighlightedIndex); if(mHighlightedLabel.getStyle().equals(mLabelStyle)) { mHighlightedLabel.setStyle(mHighlightedLabelStyle); } } else if (mLives != 0 && mInput.action()) { if(isCorrect()) { mHighlightedLabel.setStyle(mCorrectLabelStyle); mCorrectCounter++; } else { mHighlightedLabel.setStyle(mWrongLabelStyle); mLives--; mLivesLabel.setText(""+mLives); } } else if (mInput.alternateAction()) { ScoreHandler.updateScore(ScoreHandler.REQ, 10); game.setScreen(PVU.MAIN_SCREEN); reportScore(); } }
diff --git a/xwiki-commons-core/xwiki-commons-velocity/src/test/java/org/xwiki/velocity/internal/DefaultVelocityEngineTest.java b/xwiki-commons-core/xwiki-commons-velocity/src/test/java/org/xwiki/velocity/internal/DefaultVelocityEngineTest.java index 49c902b41..9a75ef7ef 100644 --- a/xwiki-commons-core/xwiki-commons-velocity/src/test/java/org/xwiki/velocity/internal/DefaultVelocityEngineTest.java +++ b/xwiki-commons-core/xwiki-commons-velocity/src/test/java/org/xwiki/velocity/internal/DefaultVelocityEngineTest.java @@ -1,176 +1,177 @@ /* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.velocity.internal; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.velocity.context.Context; import org.apache.velocity.util.introspection.SecureUberspector; import org.jmock.Expectations; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.xwiki.test.AbstractMockingComponentTestCase; import org.xwiki.test.annotation.MockingRequirement; import org.xwiki.velocity.VelocityConfiguration; import org.xwiki.velocity.VelocityEngine; import org.xwiki.velocity.introspection.ChainingUberspector; import org.xwiki.velocity.introspection.DeprecatedCheckUberspector; /** * Unit tests for {@link DefaultVelocityEngine}. */ @MockingRequirement(DefaultVelocityEngine.class) public class DefaultVelocityEngineTest extends AbstractMockingComponentTestCase { private VelocityEngine engine; @Before public void configure() throws Exception { final Properties properties = new Properties(); properties.put("runtime.introspector.uberspect", ChainingUberspector.class.getName()); properties.put("runtime.introspector.uberspect.chainClasses", SecureUberspector.class.getName() + "," + DeprecatedCheckUberspector.class.getName()); properties.put("directive.set.null.allowed", Boolean.TRUE.toString()); properties.put("velocimacro.permissions.allow.inline.local.scope", Boolean.TRUE.toString()); final VelocityConfiguration configuration = getComponentManager().getInstance(VelocityConfiguration.class); getMockery().checking(new Expectations() {{ oneOf(configuration).getProperties(); will(returnValue(properties)); // Ignore all calls to debug() and enable all logs so that we can assert info(), warn() and error() // calls. + ignoring(any(Logger.class)).method("trace"); ignoring(any(Logger.class)).method("debug"); allowing(any(Logger.class)).method("is.*Enabled"); will(returnValue(true)); }}); this.engine = getComponentManager().getInstance(VelocityEngine.class); } @Test public void testEvaluateReader() throws Exception { this.engine.initialize(new Properties()); StringWriter writer = new StringWriter(); this.engine.evaluate(new org.apache.velocity.VelocityContext(), writer, "mytemplate", new StringReader("#set($foo='hello')$foo World")); Assert.assertEquals("hello World", writer.toString()); } @Test public void testEvaluateString() throws Exception { this.engine.initialize(new Properties()); StringWriter writer = new StringWriter(); this.engine.evaluate(new org.apache.velocity.VelocityContext(), writer, "mytemplate", "#set($foo='hello')$foo World"); Assert.assertEquals("hello World", writer.toString()); } /** * Verify that the default configuration doesn't allow calling Class.forName. */ @Test public void testSecureUberspectorActiveByDefault() throws Exception { this.engine.initialize(new Properties()); StringWriter writer = new StringWriter(); // Verify that we log a warning and verify the message. final Logger logger = getMockLogger(); getMockery().checking(new Expectations() {{ oneOf(logger).warn("Cannot retrieve method forName from object of class java.lang.Class due to security " + "restrictions."); }}); this.engine.evaluate(new org.apache.velocity.VelocityContext(), writer, "mytemplate", "#set($foo = 'test')#set($object = $foo.class.forName('java.util.ArrayList')" + ".newInstance())$object.size()"); Assert.assertEquals("$object.size()", writer.toString()); } /** * Verify that the default configuration allows #setting existing variables to null. */ @Test public void testSettingNullAllowedByDefault() throws Exception { this.engine.initialize(new Properties()); StringWriter writer = new StringWriter(); Context context = new org.apache.velocity.VelocityContext(); context.put("null", null); List<String> list = new ArrayList<String>(); list.add("1"); list.add(null); list.add("3"); context.put("list", list); this.engine.evaluate(context, writer, "mytemplate", "#set($foo = true)${foo}#set($foo = $null)${foo}\n" + "#foreach($i in $list)${velocityCount}=$!{i} #end"); Assert.assertEquals("true${foo}\n1=1 2= 3=3 ", writer.toString()); } @Test public void testOverrideConfiguration() throws Exception { // For example try setting a non secure Uberspector. Properties properties = new Properties(); properties.setProperty("runtime.introspector.uberspect", "org.apache.velocity.util.introspection.UberspectImpl"); this.engine.initialize(properties); StringWriter writer = new StringWriter(); this.engine.evaluate(new org.apache.velocity.VelocityContext(), writer, "mytemplate", "#set($foo = 'test')#set($object = $foo.class.forName('java.util.ArrayList')" + ".newInstance())$object.size()"); Assert.assertEquals("0", writer.toString()); } @Test public void testMacroIsolation() throws Exception { this.engine.initialize(new Properties()); Context context = new org.apache.velocity.VelocityContext(); this.engine.evaluate(context, new StringWriter(), "template1", "#macro(mymacro)test#end"); StringWriter writer = new StringWriter(); this.engine.evaluate(context, writer, "template2", "#mymacro"); Assert.assertEquals("#mymacro", writer.toString()); } @Test public void testConfigureMacrosToBeGlobal() throws Exception { Properties properties = new Properties(); // Force macros to be global properties.put("velocimacro.permissions.allow.inline.local.scope", "false"); this.engine.initialize(properties); Context context = new org.apache.velocity.VelocityContext(); this.engine.evaluate(context, new StringWriter(), "template1", "#macro(mymacro)test#end"); StringWriter writer = new StringWriter(); this.engine.evaluate(context, writer, "template2", "#mymacro"); Assert.assertEquals("test", writer.toString()); } }
true
true
public void configure() throws Exception { final Properties properties = new Properties(); properties.put("runtime.introspector.uberspect", ChainingUberspector.class.getName()); properties.put("runtime.introspector.uberspect.chainClasses", SecureUberspector.class.getName() + "," + DeprecatedCheckUberspector.class.getName()); properties.put("directive.set.null.allowed", Boolean.TRUE.toString()); properties.put("velocimacro.permissions.allow.inline.local.scope", Boolean.TRUE.toString()); final VelocityConfiguration configuration = getComponentManager().getInstance(VelocityConfiguration.class); getMockery().checking(new Expectations() {{ oneOf(configuration).getProperties(); will(returnValue(properties)); // Ignore all calls to debug() and enable all logs so that we can assert info(), warn() and error() // calls. ignoring(any(Logger.class)).method("debug"); allowing(any(Logger.class)).method("is.*Enabled"); will(returnValue(true)); }}); this.engine = getComponentManager().getInstance(VelocityEngine.class); }
public void configure() throws Exception { final Properties properties = new Properties(); properties.put("runtime.introspector.uberspect", ChainingUberspector.class.getName()); properties.put("runtime.introspector.uberspect.chainClasses", SecureUberspector.class.getName() + "," + DeprecatedCheckUberspector.class.getName()); properties.put("directive.set.null.allowed", Boolean.TRUE.toString()); properties.put("velocimacro.permissions.allow.inline.local.scope", Boolean.TRUE.toString()); final VelocityConfiguration configuration = getComponentManager().getInstance(VelocityConfiguration.class); getMockery().checking(new Expectations() {{ oneOf(configuration).getProperties(); will(returnValue(properties)); // Ignore all calls to debug() and enable all logs so that we can assert info(), warn() and error() // calls. ignoring(any(Logger.class)).method("trace"); ignoring(any(Logger.class)).method("debug"); allowing(any(Logger.class)).method("is.*Enabled"); will(returnValue(true)); }}); this.engine = getComponentManager().getInstance(VelocityEngine.class); }
diff --git a/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/MavenGoals.java b/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/MavenGoals.java index 84a0cb99..2f273ef6 100644 --- a/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/MavenGoals.java +++ b/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/MavenGoals.java @@ -1,816 +1,816 @@ package com.atlassian.maven.plugins.amps; import com.atlassian.core.util.FileUtils; import com.atlassian.maven.plugins.amps.product.ProductHandlerFactory; import com.atlassian.maven.plugins.amps.util.VersionUtils; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.PluginManager; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.apache.maven.model.Resource; import static org.twdata.maven.mojoexecutor.MojoExecutor.Element; import static org.twdata.maven.mojoexecutor.MojoExecutor.artifactId; import static org.twdata.maven.mojoexecutor.MojoExecutor.configuration; import static org.twdata.maven.mojoexecutor.MojoExecutor.element; import static org.twdata.maven.mojoexecutor.MojoExecutor.executeMojo; import static org.twdata.maven.mojoexecutor.MojoExecutor.executionEnvironment; import static org.twdata.maven.mojoexecutor.MojoExecutor.goal; import static org.twdata.maven.mojoexecutor.MojoExecutor.groupId; import static org.twdata.maven.mojoexecutor.MojoExecutor.name; import static org.twdata.maven.mojoexecutor.MojoExecutor.plugin; import static org.twdata.maven.mojoexecutor.MojoExecutor.version; import java.io.File; import java.io.IOException; import java.net.ServerSocket; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * Executes specific maven goals */ public class MavenGoals { private final MavenProject project; private final List<MavenProject> reactor; private final MavenSession session; private final PluginManager pluginManager; private final Log log; private final Map<String, String> pluginArtifactIdToVersionMap; private final Map<String, Container> idToContainerMap = new HashMap<String, Container>() {{ put("tomcat5x", new Container("tomcat5x", "org.apache.tomcat", "apache-tomcat", "5.5.26")); put("tomcat6x", new Container("tomcat6x", "org.apache.tomcat", "apache-tomcat", "6.0.20")); put("resin3x", new Container("resin3x", "com.caucho", "resin", "3.0.26")); put("jboss42x", new Container("jboss42x", "org.jboss.jbossas", "jbossas", "4.2.3.GA")); put("jetty6x", new Container("jetty6x")); }}; private final Map<String, String> defaultArtifactIdToVersionMap = new HashMap<String, String>() {{ put("maven-cli-plugin", "0.7"); put("cargo-maven2-plugin", "1.0-beta-2-db2"); put("atlassian-pdk", "2.1.6"); put("maven-archetype-plugin", "2.0-alpha-4"); put("maven-bundle-plugin", "2.0.0"); // You can't actually override the version a plugin if defined in the project, so these don't actually do // anything, since the super pom already defines versions. put("maven-dependency-plugin", "2.0"); put("maven-resources-plugin", "2.3"); put("maven-jar-plugin", "2.2"); put("maven-surefire-plugin", "2.4.3"); }}; public MavenGoals(final MavenContext ctx) { this(ctx, Collections.<String, String>emptyMap()); } public MavenGoals(final MavenContext ctx, final Map<String, String> pluginToVersionMap) { this.project = ctx.getProject(); this.reactor = ctx.getReactor(); this.session = ctx.getSession(); this.pluginManager = ctx.getPluginManager(); this.log = ctx.getLog(); final Map<String, String> map = new HashMap<String, String>(defaultArtifactIdToVersionMap); map.putAll(pluginToVersionMap); this.pluginArtifactIdToVersionMap = Collections.unmodifiableMap(map); } public void startCli(final PluginInformation pluginInformation, final int port) throws MojoExecutionException { final String pluginId = pluginInformation.getId(); final List<Element> configs = new ArrayList<Element>(); configs.add(element(name("commands"), element(name("pi"), new StringBuilder() .append("resources").append(" ") .append("com.atlassian.maven.plugins:maven-").append(pluginId).append("-plugin:filter-plugin-descriptor").append(" ") .append("compile").append(" ") .append("com.atlassian.maven.plugins:maven-").append(pluginId).append("-plugin:copy-bundled-dependencies").append(" ") .append("com.atlassian.maven.plugins:maven-").append(pluginId).append("-plugin:generate-manifest").append(" ") .append("com.atlassian.maven.plugins:maven-").append(pluginId).append("-plugin:validate-manifest").append(" ") .append("com.atlassian.maven.plugins:maven-").append(pluginId).append("-plugin:jar").append(" ") .append("com.atlassian.maven.plugins:maven-").append(pluginId).append("-plugin:install").toString()), element(name("pu"), new StringBuilder() .append("com.atlassian.maven.plugins:maven-").append(pluginId).append("-plugin:uninstall").toString()))); if (port > 0) { configs.add(element(name("port"), String.valueOf(port))); } executeMojo( plugin( groupId("org.twdata.maven"), artifactId("maven-cli-plugin"), version(pluginArtifactIdToVersionMap.get("maven-cli-plugin")) ), goal("execute"), configuration(configs.toArray(new Element[0])), executionEnvironment(project, session, pluginManager)); } public void createPlugin(final String productId) throws MojoExecutionException { executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-archetype-plugin"), version(defaultArtifactIdToVersionMap.get("maven-archetype-plugin")) ), goal("generate"), configuration( element(name("archetypeGroupId"), "com.atlassian.maven.archetypes"), element(name("archetypeArtifactId"), productId + "-plugin-archetype"), element(name("archetypeVersion"), VersionUtils.getVersion()) ), executionEnvironment(project, session, pluginManager)); } public void copyBundledDependencies() throws MojoExecutionException { executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version(defaultArtifactIdToVersionMap.get("maven-dependency-plugin")) ), goal("copy-dependencies"), configuration( element(name("includeScope"), "runtime"), element(name("excludeScope"), "provided"), element(name("excludeScope"), "test"), element(name("includeTypes"), "jar"), element(name("outputDirectory"), "${project.build.outputDirectory}/META-INF/lib") ), executionEnvironment(project, session, pluginManager) ); } public void filterPluginDescriptor() throws MojoExecutionException { executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-resources-plugin"), version(defaultArtifactIdToVersionMap.get("maven-resources-plugin")) ), goal("copy-resources"), configuration( element(name("encoding"), "UTF-8"), element(name("resources"), element(name("resource"), element(name("directory"), "src/main/resources"), element(name("filtering"), "true"), element(name("includes"), element(name("include"), "atlassian-plugin.xml")) ) ), element(name("outputDirectory"), "${project.build.outputDirectory}") ), executionEnvironment(project, session, pluginManager) ); } public void runUnitTests() throws MojoExecutionException { executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-surefire-plugin"), version(defaultArtifactIdToVersionMap.get("maven-surefire-plugin")) ), goal("test"), configuration( element(name("excludes"), element(name("exclude"), "it/**"), element(name("exclude"), "**/*$*")) ), executionEnvironment(project, session, pluginManager) ); } public File copyWebappWar(final String productId, final File targetDirectory, final ProductArtifact artifact) throws MojoExecutionException { final File webappWarFile = new File(targetDirectory, productId + "-original.war"); executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version(defaultArtifactIdToVersionMap.get("maven-dependency-plugin")) ), goal("copy"), configuration( element(name("artifactItems"), element(name("artifactItem"), element(name("groupId"), artifact.getGroupId()), element(name("artifactId"), artifact.getArtifactId()), element(name("type"), "war"), element(name("version"), artifact.getVersion()), element(name("destFileName"), webappWarFile.getName()))), element(name("outputDirectory"), targetDirectory.getPath()) ), executionEnvironment(project, session, pluginManager) ); return webappWarFile; } /** * Copies {@code artifacts} to the {@code outputDirectory}. Artifacts are looked up in order: <ol> <li>in the maven * reactor</li> <li>in the maven repositories</li> </ol> This can't be used in a goal that happens before the * <em>package</em> phase as artifacts in the reactor will be not be packaged (and therefore 'copiable') until this * phase. * * @param outputDirectory the directory to copy artifacts to * @param artifacts the list of artifact to copy to the given directory */ public void copyPlugins(final File outputDirectory, final List<ProductArtifact> artifacts) throws MojoExecutionException { for (ProductArtifact artifact : artifacts) { final MavenProject artifactReactorProject = getReactorProjectForArtifact(artifact); if (artifactReactorProject != null) { log.debug(artifact + " will be copied from reactor project " + artifactReactorProject); final File artifactFile = artifactReactorProject.getArtifact().getFile(); if (artifactFile == null) { log.warn("The plugin " + artifact + " is in the reactor but not the file hasn't been attached. Skipping."); } else { log.debug("Copying " + artifactFile + " to " + outputDirectory); try { FileUtils.copyFile(artifactFile, new File(outputDirectory, artifactFile.getName())); } catch (IOException e) { throw new MojoExecutionException("Could not copy " + artifact + " to " + outputDirectory, e); } } } else { executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version(defaultArtifactIdToVersionMap.get("maven-dependency-plugin")) ), goal("copy"), configuration( element(name("artifactItems"), element(name("artifactItem"), element(name("groupId"), artifact.getGroupId()), element(name("artifactId"), artifact.getArtifactId()), element(name("version"), artifact.getVersion()))), element(name("outputDirectory"), outputDirectory.getPath()) ), executionEnvironment(project, session, pluginManager)); } } } private MavenProject getReactorProjectForArtifact(ProductArtifact artifact) { for (final MavenProject project : reactor) { if (project.getGroupId().equals(artifact.getGroupId()) && project.getArtifactId().equals(artifact.getArtifactId()) && project.getVersion().equals(artifact.getVersion())) { return project; } } return null; } private void unpackContainer(final Container container) throws MojoExecutionException { executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version(defaultArtifactIdToVersionMap.get("maven-dependency-plugin")) ), goal("unpack"), configuration( element(name("artifactItems"), element(name("artifactItem"), element(name("groupId"), container.getGroupId()), element(name("artifactId"), container.getArtifactId()), element(name("version"), container.getVersion()), element(name("type"), "zip"))), element(name("outputDirectory"), container.getRootDirectory(getBuildDirectory())) ), executionEnvironment(project, session, pluginManager)); } private String getBuildDirectory() { return project.getBuild().getDirectory(); } public int startWebapp(final String productId, final File war, final Map<String, String> systemProperties, final List<ProductArtifact> extraContainerDependencies, final Product webappContext) throws MojoExecutionException { final Container container = findContainer(webappContext.getContainerId()); File containerDir = new File(container.getRootDirectory(getBuildDirectory())); // retrieve non-embedded containers if (!container.isEmbedded()) { if (containerDir.exists()) { log.info("Reusing unpacked container '" + container.getId() + "' from " + containerDir.getPath()); } else { log.info("Unpacking container '" + container.getId() + "' from container artifact: " + container.toString()); unpackContainer(container); } } final int rmiPort = pickFreePort(0); final int actualHttpPort = pickFreePort(webappContext.getHttpPort()); final List<Element> sysProps = new ArrayList<Element>(); if (webappContext.getJvmArgs() == null) { webappContext.setJvmArgs("-Xmx512m -XX:MaxPermSize=160m"); } Map<String, String> sysPropsMap = new HashMap<String, String>(systemProperties); sysPropsMap.put("atlassian.dev.mode", System.getProperty("atlassian.dev.mode", "true")); if (!sysPropsMap.containsKey("plugin.resource.directories")) { // collect all resource directories and make them available for // on-the-fly reloading StringBuilder resourceProp = new StringBuilder(); @SuppressWarnings("unchecked") List<Resource> resList = project.getResources(); for (int i = 0; i < resList.size(); i++) { resourceProp.append(resList.get(i).getDirectory()); if (i + 1 != resList.size()) { resourceProp.append(","); } } sysPropsMap.put("plugin.resource.directories", resourceProp.toString()); } for (final Map.Entry<String, String> entry : sysPropsMap.entrySet()) { webappContext.setJvmArgs(webappContext.getJvmArgs() + " -D" + entry.getKey() + "=" + entry.getValue()); sysProps.add(element(name(entry.getKey()), entry.getValue())); } log.info("Starting " + productId + " on the " + container.getId() + " container on ports " + actualHttpPort + " (http) and " + rmiPort + " (rmi)"); final String baseUrl = getBaseUrl(webappContext.getServer(), actualHttpPort, webappContext.getContextPath()); sysProps.add(element(name("baseurl"), baseUrl)); final List<Element> deps = new ArrayList<Element>(); for (final ProductArtifact dep : extraContainerDependencies) { deps.add(element(name("dependency"), element(name("location"), webappContext.getArtifactRetriever().resolve(dep)) )); } final List<Element> props = new ArrayList<Element>(); for (final Map.Entry<String, String> entry : systemProperties.entrySet()) { - sysProps.add(element(name(entry.getKey()), entry.getValue())); + props.add(element(name(entry.getKey()), entry.getValue())); } props.add(element(name("cargo.servlet.port"), String.valueOf(actualHttpPort))); props.add(element(name("cargo.rmi.port"), String.valueOf(rmiPort))); props.add(element(name("cargo.jvmargs"), webappContext.getJvmArgs())); executeMojo( plugin( groupId("org.twdata.maven"), artifactId("cargo-maven2-plugin"), version(pluginArtifactIdToVersionMap.get("cargo-maven2-plugin")) ), goal("start"), configuration( element(name("wait"), "false"), element(name("container"), element(name("containerId"), container.getId()), element(name("type"), container.getType()), element(name("home"), container.getInstallDirectory(getBuildDirectory())), element(name("systemProperties"), sysProps.toArray(new Element[sysProps.size()])), element(name("dependencies"), deps.toArray(new Element[deps.size()])) ), element(name("configuration"), element(name("home"), container.getConfigDirectory(getBuildDirectory(), productId)), element(name("type"), "standalone"), element(name("properties"), props.toArray(new Element[props.size()])), element(name("deployables"), element(name("deployable"), element(name("groupId"), "foo"), element(name("artifactId"), "bar"), element(name("type"), "war"), element(name("location"), war.getPath()), element(name("properties"), element(name("context"), webappContext.getContextPath()) ) ) ) ) ), executionEnvironment(project, session, pluginManager) ); return actualHttpPort; } private String getBaseUrl(final String server, final int actualHttpPort, final String contextPath) { return "http://" + server + ":" + actualHttpPort + contextPath; } public void runTests(final String productId, final String containerId, final String functionalTestPattern, Properties systemProperties) throws MojoExecutionException { // Automatically exclude tests for other products final List<Element> excludes = new ArrayList<Element>(); excludes.add(element(name("exclude"), "**/*$*")); excludes.add(element(name("exclude"), "**/Abstract*")); for (final String type : ProductHandlerFactory.getIds()) { if (!type.equals(productId)) { excludes.add(element(name("exclude"), "**/" + type + "/**")); } } final Element systemProps = convertPropsToEelements(systemProperties); executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-surefire-plugin"), version(defaultArtifactIdToVersionMap.get("maven-surefire-plugin")) ), goal("test"), configuration( element(name("includes"), element(name("include"), functionalTestPattern) ), element(name("excludes"), excludes.toArray(new Element[excludes.size()]) ), systemProps, element(name("reportsDirectory"), "${project.build.directory}/" + productId + "/" + containerId + "/surefire-reports") ), executionEnvironment(project, session, pluginManager) ); } /** * Converts a map of System properties to maven config elements */ private Element convertPropsToEelements(Properties systemProperties) { ArrayList<Element> properties = new ArrayList<Element>(); // add extra system properties... overwriting any of the hard coded values above. for (Map.Entry entry: systemProperties.entrySet()) { properties.add( element(name("property"), element(name("name"), (String)entry.getKey()), element(name("value"), (String)entry.getValue()))); } return element(name("systemProperties"), properties.toArray(new Element[properties.size()])); } private Container findContainer(final String containerId) { final Container container = idToContainerMap.get(containerId); if (container == null) { throw new IllegalArgumentException("Container " + containerId + " not supported"); } return container; } private int pickFreePort(final int requestedPort) { if (requestedPort > 0) { return requestedPort; } ServerSocket socket = null; try { socket = new ServerSocket(0); return socket.getLocalPort(); } catch (final IOException e) { throw new RuntimeException("Error opening socket", e); } finally { if (socket != null) { try { socket.close(); } catch (final IOException e) { throw new RuntimeException("Error closing socket", e); } } } } public void stopWebapp(final String productId, final String containerId) throws MojoExecutionException { final Container container = findContainer(containerId); executeMojo( plugin( groupId("org.twdata.maven"), artifactId("cargo-maven2-plugin"), version(pluginArtifactIdToVersionMap.get("cargo-maven2-plugin")) ), goal("stop"), configuration( element(name("container"), element(name("containerId"), container.getId()), element(name("type"), container.getType()) ), element(name("configuration"), element(name("home"), container.getConfigDirectory(getBuildDirectory(), productId)) ) ), executionEnvironment(project, session, pluginManager) ); } public void installPlugin(final String pluginKey, final String server, final int port, final String contextPath, final String username, final String password) throws MojoExecutionException { final String baseUrl = getBaseUrl(server, port, contextPath); executeMojo( plugin( groupId("com.atlassian.maven.plugins"), artifactId("atlassian-pdk"), version(pluginArtifactIdToVersionMap.get("atlassian-pdk")) ), goal("install"), configuration( element(name("username"), username), element(name("password"), password), element(name("serverUrl"), baseUrl), element(name("pluginKey"), pluginKey) ), executionEnvironment(project, session, pluginManager) ); } public void uninstallPlugin(final String pluginKey, final String server, final int port, final String contextPath) throws MojoExecutionException { final String baseUrl = getBaseUrl(server, port, contextPath); executeMojo( plugin( groupId("com.atlassian.maven.plugins"), artifactId("atlassian-pdk"), version(pluginArtifactIdToVersionMap.get("atlassian-pdk")) ), goal("uninstall"), configuration( element(name("username"), "admin"), element(name("password"), "admin"), element(name("serverUrl"), baseUrl), element(name("pluginKey"), pluginKey) ), executionEnvironment(project, session, pluginManager) ); } public void installIdeaPlugin() throws MojoExecutionException { executeMojo( plugin( groupId("org.twdata.maven"), artifactId("maven-cli-plugin"), version(pluginArtifactIdToVersionMap.get("maven-cli-plugin")) ), goal("idea"), configuration(), executionEnvironment(project, session, pluginManager) ); } public File copyDist(final File targetDirectory, final ProductArtifact artifact) throws MojoExecutionException { return copyZip(targetDirectory, artifact, "test-dist.zip"); } public File copyHome(final File targetDirectory, final ProductArtifact artifact) throws MojoExecutionException { return copyZip(targetDirectory, artifact, "test-resources.zip"); } public File copyZip(final File targetDirectory, final ProductArtifact artifact, final String localName) throws MojoExecutionException { final File artifactZip = new File(targetDirectory, localName); executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version(defaultArtifactIdToVersionMap.get("maven-dependency-plugin")) ), goal("copy"), configuration( element(name("artifactItems"), element(name("artifactItem"), element(name("groupId"), artifact.getGroupId()), element(name("artifactId"), artifact.getArtifactId()), element(name("type"), "zip"), element(name("version"), artifact.getVersion()), element(name("destFileName"), artifactZip.getName()))), element(name("outputDirectory"), artifactZip.getParent()) ), executionEnvironment(project, session, pluginManager) ); return artifactZip; } public void generateManifest(final Map<String, String> instructions) throws MojoExecutionException { final List<Element> instlist = new ArrayList<Element>(); for (final Map.Entry<String, String> entry : instructions.entrySet()) { instlist.add(element(entry.getKey(), entry.getValue())); } executeMojo( plugin( groupId("org.apache.felix"), artifactId("maven-bundle-plugin"), version(defaultArtifactIdToVersionMap.get("maven-bundle-plugin")) ), goal("manifest"), configuration( element(name("supportedProjectTypes"), element(name("supportedProjectType"), "jar"), element(name("supportedProjectType"), "bundle"), element(name("supportedProjectType"), "war"), element(name("supportedProjectType"), "atlassian-plugin")), element(name("instructions"), instlist.toArray(new Element[instlist.size()])) ), executionEnvironment(project, session, pluginManager) ); } public void jarWithOptionalManifest(final boolean manifestExists) throws MojoExecutionException { Element[] archive = new Element[0]; if (manifestExists) { archive = new Element[]{element(name("manifestFile"), "${project.build.outputDirectory}/META-INF/MANIFEST.MF")}; } executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-jar-plugin"), version(defaultArtifactIdToVersionMap.get("maven-jar-plugin")) ), goal("jar"), configuration( element(name("archive"), archive) ), executionEnvironment(project, session, pluginManager) ); } public void generateObrXml(File dep, File obrXml) throws MojoExecutionException { executeMojo( plugin( groupId("org.apache.felix"), artifactId("maven-bundle-plugin"), version(defaultArtifactIdToVersionMap.get("maven-bundle-plugin")) ), goal("install-file"), configuration( element(name("obrRepository"), obrXml.getPath()), // the following three settings are required but not really used element(name("groupId"), "doesntmatter"), element(name("artifactId"), "doesntmatter"), element(name("version"), "doesntmatter"), element(name("packaging"), "jar"), element(name("file"), dep.getPath()) ), executionEnvironment(project, session, pluginManager) ); } private static class Container extends ProductArtifact { private final String id; private final String type; /** * Installable container that can be downloaded by Maven. * * @param id identifier of container, eg. "tomcat5x". * @param groupId groupId of container. * @param artifactId artifactId of container. * @param version version number of container. */ public Container(final String id, final String groupId, final String artifactId, final String version) { super(groupId, artifactId, version); this.id = id; this.type = "installed"; } /** * Embedded container packaged with Cargo. * * @param id identifier of container, eg. "jetty6x". */ public Container(final String id) { this.id = id; this.type = "embedded"; } /** * @return identifier of container. */ public String getId() { return id; } /** * @return "installed" or "embedded". */ public String getType() { return type; } /** * @return <code>true</code> if the container type is "embedded". */ public boolean isEmbedded() { return "embedded".equals(type); } /** * @param buildDir project.build.directory. * @return root directory of the container that will house the container installation and configuration. */ public String getRootDirectory(String buildDir) { return buildDir + File.separator + "container" + File.separator + getId(); } /** * @param buildDir project.build.directory. * @return directory housing the installed container. */ public String getInstallDirectory(String buildDir) { return getRootDirectory(buildDir) + File.separator + getArtifactId() + "-" + getVersion(); } /** * @param buildDir project.build.directory. * @param productId product name. * @return directory to house the container configuration for the specified product. */ public String getConfigDirectory(String buildDir, String productId) { return getRootDirectory(buildDir) + File.separator + "cargo-" + productId + "-home"; } } }
true
true
public int startWebapp(final String productId, final File war, final Map<String, String> systemProperties, final List<ProductArtifact> extraContainerDependencies, final Product webappContext) throws MojoExecutionException { final Container container = findContainer(webappContext.getContainerId()); File containerDir = new File(container.getRootDirectory(getBuildDirectory())); // retrieve non-embedded containers if (!container.isEmbedded()) { if (containerDir.exists()) { log.info("Reusing unpacked container '" + container.getId() + "' from " + containerDir.getPath()); } else { log.info("Unpacking container '" + container.getId() + "' from container artifact: " + container.toString()); unpackContainer(container); } } final int rmiPort = pickFreePort(0); final int actualHttpPort = pickFreePort(webappContext.getHttpPort()); final List<Element> sysProps = new ArrayList<Element>(); if (webappContext.getJvmArgs() == null) { webappContext.setJvmArgs("-Xmx512m -XX:MaxPermSize=160m"); } Map<String, String> sysPropsMap = new HashMap<String, String>(systemProperties); sysPropsMap.put("atlassian.dev.mode", System.getProperty("atlassian.dev.mode", "true")); if (!sysPropsMap.containsKey("plugin.resource.directories")) { // collect all resource directories and make them available for // on-the-fly reloading StringBuilder resourceProp = new StringBuilder(); @SuppressWarnings("unchecked") List<Resource> resList = project.getResources(); for (int i = 0; i < resList.size(); i++) { resourceProp.append(resList.get(i).getDirectory()); if (i + 1 != resList.size()) { resourceProp.append(","); } } sysPropsMap.put("plugin.resource.directories", resourceProp.toString()); } for (final Map.Entry<String, String> entry : sysPropsMap.entrySet()) { webappContext.setJvmArgs(webappContext.getJvmArgs() + " -D" + entry.getKey() + "=" + entry.getValue()); sysProps.add(element(name(entry.getKey()), entry.getValue())); } log.info("Starting " + productId + " on the " + container.getId() + " container on ports " + actualHttpPort + " (http) and " + rmiPort + " (rmi)"); final String baseUrl = getBaseUrl(webappContext.getServer(), actualHttpPort, webappContext.getContextPath()); sysProps.add(element(name("baseurl"), baseUrl)); final List<Element> deps = new ArrayList<Element>(); for (final ProductArtifact dep : extraContainerDependencies) { deps.add(element(name("dependency"), element(name("location"), webappContext.getArtifactRetriever().resolve(dep)) )); } final List<Element> props = new ArrayList<Element>(); for (final Map.Entry<String, String> entry : systemProperties.entrySet()) { sysProps.add(element(name(entry.getKey()), entry.getValue())); } props.add(element(name("cargo.servlet.port"), String.valueOf(actualHttpPort))); props.add(element(name("cargo.rmi.port"), String.valueOf(rmiPort))); props.add(element(name("cargo.jvmargs"), webappContext.getJvmArgs())); executeMojo( plugin( groupId("org.twdata.maven"), artifactId("cargo-maven2-plugin"), version(pluginArtifactIdToVersionMap.get("cargo-maven2-plugin")) ), goal("start"), configuration( element(name("wait"), "false"), element(name("container"), element(name("containerId"), container.getId()), element(name("type"), container.getType()), element(name("home"), container.getInstallDirectory(getBuildDirectory())), element(name("systemProperties"), sysProps.toArray(new Element[sysProps.size()])), element(name("dependencies"), deps.toArray(new Element[deps.size()])) ), element(name("configuration"), element(name("home"), container.getConfigDirectory(getBuildDirectory(), productId)), element(name("type"), "standalone"), element(name("properties"), props.toArray(new Element[props.size()])), element(name("deployables"), element(name("deployable"), element(name("groupId"), "foo"), element(name("artifactId"), "bar"), element(name("type"), "war"), element(name("location"), war.getPath()), element(name("properties"), element(name("context"), webappContext.getContextPath()) ) ) ) ) ), executionEnvironment(project, session, pluginManager) ); return actualHttpPort; }
public int startWebapp(final String productId, final File war, final Map<String, String> systemProperties, final List<ProductArtifact> extraContainerDependencies, final Product webappContext) throws MojoExecutionException { final Container container = findContainer(webappContext.getContainerId()); File containerDir = new File(container.getRootDirectory(getBuildDirectory())); // retrieve non-embedded containers if (!container.isEmbedded()) { if (containerDir.exists()) { log.info("Reusing unpacked container '" + container.getId() + "' from " + containerDir.getPath()); } else { log.info("Unpacking container '" + container.getId() + "' from container artifact: " + container.toString()); unpackContainer(container); } } final int rmiPort = pickFreePort(0); final int actualHttpPort = pickFreePort(webappContext.getHttpPort()); final List<Element> sysProps = new ArrayList<Element>(); if (webappContext.getJvmArgs() == null) { webappContext.setJvmArgs("-Xmx512m -XX:MaxPermSize=160m"); } Map<String, String> sysPropsMap = new HashMap<String, String>(systemProperties); sysPropsMap.put("atlassian.dev.mode", System.getProperty("atlassian.dev.mode", "true")); if (!sysPropsMap.containsKey("plugin.resource.directories")) { // collect all resource directories and make them available for // on-the-fly reloading StringBuilder resourceProp = new StringBuilder(); @SuppressWarnings("unchecked") List<Resource> resList = project.getResources(); for (int i = 0; i < resList.size(); i++) { resourceProp.append(resList.get(i).getDirectory()); if (i + 1 != resList.size()) { resourceProp.append(","); } } sysPropsMap.put("plugin.resource.directories", resourceProp.toString()); } for (final Map.Entry<String, String> entry : sysPropsMap.entrySet()) { webappContext.setJvmArgs(webappContext.getJvmArgs() + " -D" + entry.getKey() + "=" + entry.getValue()); sysProps.add(element(name(entry.getKey()), entry.getValue())); } log.info("Starting " + productId + " on the " + container.getId() + " container on ports " + actualHttpPort + " (http) and " + rmiPort + " (rmi)"); final String baseUrl = getBaseUrl(webappContext.getServer(), actualHttpPort, webappContext.getContextPath()); sysProps.add(element(name("baseurl"), baseUrl)); final List<Element> deps = new ArrayList<Element>(); for (final ProductArtifact dep : extraContainerDependencies) { deps.add(element(name("dependency"), element(name("location"), webappContext.getArtifactRetriever().resolve(dep)) )); } final List<Element> props = new ArrayList<Element>(); for (final Map.Entry<String, String> entry : systemProperties.entrySet()) { props.add(element(name(entry.getKey()), entry.getValue())); } props.add(element(name("cargo.servlet.port"), String.valueOf(actualHttpPort))); props.add(element(name("cargo.rmi.port"), String.valueOf(rmiPort))); props.add(element(name("cargo.jvmargs"), webappContext.getJvmArgs())); executeMojo( plugin( groupId("org.twdata.maven"), artifactId("cargo-maven2-plugin"), version(pluginArtifactIdToVersionMap.get("cargo-maven2-plugin")) ), goal("start"), configuration( element(name("wait"), "false"), element(name("container"), element(name("containerId"), container.getId()), element(name("type"), container.getType()), element(name("home"), container.getInstallDirectory(getBuildDirectory())), element(name("systemProperties"), sysProps.toArray(new Element[sysProps.size()])), element(name("dependencies"), deps.toArray(new Element[deps.size()])) ), element(name("configuration"), element(name("home"), container.getConfigDirectory(getBuildDirectory(), productId)), element(name("type"), "standalone"), element(name("properties"), props.toArray(new Element[props.size()])), element(name("deployables"), element(name("deployable"), element(name("groupId"), "foo"), element(name("artifactId"), "bar"), element(name("type"), "war"), element(name("location"), war.getPath()), element(name("properties"), element(name("context"), webappContext.getContextPath()) ) ) ) ) ), executionEnvironment(project, session, pluginManager) ); return actualHttpPort; }
diff --git a/mdiss-core/src/main/java/org/mdissjava/mdisscore/filter/RestrictPageAccessFilter.java b/mdiss-core/src/main/java/org/mdissjava/mdisscore/filter/RestrictPageAccessFilter.java index b0735b7..374fa04 100644 --- a/mdiss-core/src/main/java/org/mdissjava/mdisscore/filter/RestrictPageAccessFilter.java +++ b/mdiss-core/src/main/java/org/mdissjava/mdisscore/filter/RestrictPageAccessFilter.java @@ -1,108 +1,108 @@ package org.mdissjava.mdisscore.filter; import java.io.IOException; import java.util.HashMap; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mdissjava.mdisscore.model.dao.UserDao; import org.mdissjava.mdisscore.model.dao.impl.UserDaoImpl; import org.mdissjava.mdisscore.model.pojo.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import com.ocpsoft.pretty.PrettyContext; import com.ocpsoft.pretty.faces.config.mapping.UrlMapping; import com.ocpsoft.pretty.faces.util.PrettyURLBuilder; public class RestrictPageAccessFilter implements Filter { final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Get the current logged user's username Authentication auth = SecurityContextHolder.getContext() .getAuthentication(); String loggedUser = auth.getName(); // get the user access page String username = request.getParameter("user"); // TODO: Check if the requested user exists in DB. If it doesn't exist // send to 404 Error page? UserDao udao = new UserDaoImpl(); User requestedUser = udao.getUserByNick(username); User userLogged = udao.getUserByNick(loggedUser); userLogged.equals(userLogged); // TODO: userLogged needed? if (requestedUser != null) { // boolean isFollowing = udao.followsUser(username, userLogged); boolean isFollowing = udao.followsUser(loggedUser, requestedUser); if ((!isFollowing) && (requestedUser.getConfiguration().isIsPrivate()) && (!requestedUser.getNick().equals(loggedUser))) { // If they don't match send the naughty user to error page. this.logger .error("FORBIDDEN ACCESS EVENT: User {} tried to access restricted area.", loggedUser); PrettyContext context = PrettyContext .getCurrentInstance((HttpServletRequest) request); PrettyURLBuilder builder = new PrettyURLBuilder(); UrlMapping mapping = context.getConfig().getMappingById( "restricted-error"); - String targetURL = builder.build(mapping, true, - new HashMap<String, String[]>()); + Object[] objs = {requestedUser.getNick()}; + String targetURL = builder.build(mapping, true, objs); HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.sendRedirect("/mdissphoto" + targetURL); } else { chain.doFilter(request, response); } } else { this.logger.error( "FORBIDDEN ACCESS EVENT: User {} does not exists.", loggedUser); PrettyContext context = PrettyContext .getCurrentInstance((HttpServletRequest) request); PrettyURLBuilder builder = new PrettyURLBuilder(); UrlMapping mapping = context.getConfig().getMappingById( "restricted-error"); String targetURL = builder.build(mapping, true, new HashMap<String, String[]>()); HttpServletResponse httpResponse = (HttpServletResponse) response; // TODO: delete "/mdissphoto" when moving to custom subdomain httpResponse.sendRedirect("/mdissphoto" + targetURL); } } @Override public void init(FilterConfig arg0) throws ServletException { this.logger.info("APPLYING RestrictPageAccessFilter"); } }
true
true
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Get the current logged user's username Authentication auth = SecurityContextHolder.getContext() .getAuthentication(); String loggedUser = auth.getName(); // get the user access page String username = request.getParameter("user"); // TODO: Check if the requested user exists in DB. If it doesn't exist // send to 404 Error page? UserDao udao = new UserDaoImpl(); User requestedUser = udao.getUserByNick(username); User userLogged = udao.getUserByNick(loggedUser); userLogged.equals(userLogged); // TODO: userLogged needed? if (requestedUser != null) { // boolean isFollowing = udao.followsUser(username, userLogged); boolean isFollowing = udao.followsUser(loggedUser, requestedUser); if ((!isFollowing) && (requestedUser.getConfiguration().isIsPrivate()) && (!requestedUser.getNick().equals(loggedUser))) { // If they don't match send the naughty user to error page. this.logger .error("FORBIDDEN ACCESS EVENT: User {} tried to access restricted area.", loggedUser); PrettyContext context = PrettyContext .getCurrentInstance((HttpServletRequest) request); PrettyURLBuilder builder = new PrettyURLBuilder(); UrlMapping mapping = context.getConfig().getMappingById( "restricted-error"); String targetURL = builder.build(mapping, true, new HashMap<String, String[]>()); HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.sendRedirect("/mdissphoto" + targetURL); } else { chain.doFilter(request, response); } } else { this.logger.error( "FORBIDDEN ACCESS EVENT: User {} does not exists.", loggedUser); PrettyContext context = PrettyContext .getCurrentInstance((HttpServletRequest) request); PrettyURLBuilder builder = new PrettyURLBuilder(); UrlMapping mapping = context.getConfig().getMappingById( "restricted-error"); String targetURL = builder.build(mapping, true, new HashMap<String, String[]>()); HttpServletResponse httpResponse = (HttpServletResponse) response; // TODO: delete "/mdissphoto" when moving to custom subdomain httpResponse.sendRedirect("/mdissphoto" + targetURL); } }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Get the current logged user's username Authentication auth = SecurityContextHolder.getContext() .getAuthentication(); String loggedUser = auth.getName(); // get the user access page String username = request.getParameter("user"); // TODO: Check if the requested user exists in DB. If it doesn't exist // send to 404 Error page? UserDao udao = new UserDaoImpl(); User requestedUser = udao.getUserByNick(username); User userLogged = udao.getUserByNick(loggedUser); userLogged.equals(userLogged); // TODO: userLogged needed? if (requestedUser != null) { // boolean isFollowing = udao.followsUser(username, userLogged); boolean isFollowing = udao.followsUser(loggedUser, requestedUser); if ((!isFollowing) && (requestedUser.getConfiguration().isIsPrivate()) && (!requestedUser.getNick().equals(loggedUser))) { // If they don't match send the naughty user to error page. this.logger .error("FORBIDDEN ACCESS EVENT: User {} tried to access restricted area.", loggedUser); PrettyContext context = PrettyContext .getCurrentInstance((HttpServletRequest) request); PrettyURLBuilder builder = new PrettyURLBuilder(); UrlMapping mapping = context.getConfig().getMappingById( "restricted-error"); Object[] objs = {requestedUser.getNick()}; String targetURL = builder.build(mapping, true, objs); HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.sendRedirect("/mdissphoto" + targetURL); } else { chain.doFilter(request, response); } } else { this.logger.error( "FORBIDDEN ACCESS EVENT: User {} does not exists.", loggedUser); PrettyContext context = PrettyContext .getCurrentInstance((HttpServletRequest) request); PrettyURLBuilder builder = new PrettyURLBuilder(); UrlMapping mapping = context.getConfig().getMappingById( "restricted-error"); String targetURL = builder.build(mapping, true, new HashMap<String, String[]>()); HttpServletResponse httpResponse = (HttpServletResponse) response; // TODO: delete "/mdissphoto" when moving to custom subdomain httpResponse.sendRedirect("/mdissphoto" + targetURL); } }
diff --git a/activemq-broker/src/main/java/org/apache/activemq/broker/region/Topic.java b/activemq-broker/src/main/java/org/apache/activemq/broker/region/Topic.java index 401e7661f..7e4460513 100755 --- a/activemq-broker/src/main/java/org/apache/activemq/broker/region/Topic.java +++ b/activemq-broker/src/main/java/org/apache/activemq/broker/region/Topic.java @@ -1,789 +1,790 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.broker.region; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Future; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.activemq.advisory.AdvisorySupport; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.broker.ProducerBrokerExchange; import org.apache.activemq.broker.region.policy.DispatchPolicy; import org.apache.activemq.broker.region.policy.LastImageSubscriptionRecoveryPolicy; import org.apache.activemq.broker.region.policy.NoSubscriptionRecoveryPolicy; import org.apache.activemq.broker.region.policy.SimpleDispatchPolicy; import org.apache.activemq.broker.region.policy.SubscriptionRecoveryPolicy; import org.apache.activemq.broker.util.InsertionCountList; import org.apache.activemq.command.ActiveMQDestination; import org.apache.activemq.command.ExceptionResponse; import org.apache.activemq.command.Message; import org.apache.activemq.command.MessageAck; import org.apache.activemq.command.MessageId; import org.apache.activemq.command.ProducerAck; import org.apache.activemq.command.ProducerInfo; import org.apache.activemq.command.Response; import org.apache.activemq.command.SubscriptionInfo; import org.apache.activemq.filter.MessageEvaluationContext; import org.apache.activemq.filter.NonCachedMessageEvaluationContext; import org.apache.activemq.store.MessageRecoveryListener; import org.apache.activemq.store.TopicMessageStore; import org.apache.activemq.thread.Task; import org.apache.activemq.thread.TaskRunner; import org.apache.activemq.thread.TaskRunnerFactory; import org.apache.activemq.transaction.Synchronization; import org.apache.activemq.util.SubscriptionKey; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Topic is a destination that sends a copy of a message to every active * Subscription registered. */ public class Topic extends BaseDestination implements Task { protected static final Logger LOG = LoggerFactory.getLogger(Topic.class); private final TopicMessageStore topicStore; protected final CopyOnWriteArrayList<Subscription> consumers = new CopyOnWriteArrayList<Subscription>(); private final ReentrantReadWriteLock dispatchLock = new ReentrantReadWriteLock(); private DispatchPolicy dispatchPolicy = new SimpleDispatchPolicy(); private SubscriptionRecoveryPolicy subscriptionRecoveryPolicy; private final ConcurrentHashMap<SubscriptionKey, DurableTopicSubscription> durableSubscribers = new ConcurrentHashMap<SubscriptionKey, DurableTopicSubscription>(); private final TaskRunner taskRunner; private final LinkedList<Runnable> messagesWaitingForSpace = new LinkedList<Runnable>(); private final Runnable sendMessagesWaitingForSpaceTask = new Runnable() { public void run() { try { Topic.this.taskRunner.wakeup(); } catch (InterruptedException e) { } }; }; public Topic(BrokerService brokerService, ActiveMQDestination destination, TopicMessageStore store, DestinationStatistics parentStats, TaskRunnerFactory taskFactory) throws Exception { super(brokerService, store, destination, parentStats); this.topicStore = store; // set default subscription recovery policy if (AdvisorySupport.isMasterBrokerAdvisoryTopic(destination)) { subscriptionRecoveryPolicy = new LastImageSubscriptionRecoveryPolicy(); setAlwaysRetroactive(true); } else { subscriptionRecoveryPolicy = new NoSubscriptionRecoveryPolicy(); } this.taskRunner = taskFactory.createTaskRunner(this, "Topic " + destination.getPhysicalName()); } @Override public void initialize() throws Exception { super.initialize(); if (store != null) { // AMQ-2586: Better to leave this stat at zero than to give the user // misleading metrics. // int messageCount = store.getMessageCount(); // destinationStatistics.getMessages().setCount(messageCount); } } public List<Subscription> getConsumers() { synchronized (consumers) { return new ArrayList<Subscription>(consumers); } } public boolean lock(MessageReference node, LockOwner sub) { return true; } public void addSubscription(ConnectionContext context, final Subscription sub) throws Exception { if (!sub.getConsumerInfo().isDurable()) { // Do a retroactive recovery if needed. if (sub.getConsumerInfo().isRetroactive() || isAlwaysRetroactive()) { // synchronize with dispatch method so that no new messages are sent // while we are recovering a subscription to avoid out of order messages. dispatchLock.writeLock().lock(); try { boolean applyRecovery = false; synchronized (consumers) { if (!consumers.contains(sub)){ sub.add(context, this); consumers.add(sub); applyRecovery=true; super.addSubscription(context, sub); } } if (applyRecovery){ subscriptionRecoveryPolicy.recover(context, this, sub); } } finally { dispatchLock.writeLock().unlock(); } } else { synchronized (consumers) { if (!consumers.contains(sub)){ sub.add(context, this); consumers.add(sub); super.addSubscription(context, sub); } } } } else { DurableTopicSubscription dsub = (DurableTopicSubscription) sub; super.addSubscription(context, sub); sub.add(context, this); if(dsub.isActive()) { synchronized (consumers) { boolean hasSubscription = false; if (consumers.size() == 0) { hasSubscription = false; } else { for (Subscription currentSub : consumers) { if (currentSub.getConsumerInfo().isDurable()) { DurableTopicSubscription dcurrentSub = (DurableTopicSubscription) currentSub; if (dcurrentSub.getSubscriptionKey().equals(dsub.getSubscriptionKey())) { hasSubscription = true; break; } } } } if (!hasSubscription) { consumers.add(sub); } } } durableSubscribers.put(dsub.getSubscriptionKey(), dsub); } } public void removeSubscription(ConnectionContext context, Subscription sub, long lastDeliveredSequenceId) throws Exception { if (!sub.getConsumerInfo().isDurable()) { super.removeSubscription(context, sub, lastDeliveredSequenceId); synchronized (consumers) { consumers.remove(sub); } } sub.remove(context, this); } public void deleteSubscription(ConnectionContext context, SubscriptionKey key) throws Exception { if (topicStore != null) { topicStore.deleteSubscription(key.clientId, key.subscriptionName); DurableTopicSubscription removed = durableSubscribers.remove(key); if (removed != null) { destinationStatistics.getConsumers().decrement(); // deactivate and remove removed.deactivate(false); consumers.remove(removed); } } } public void activate(ConnectionContext context, final DurableTopicSubscription subscription) throws Exception { // synchronize with dispatch method so that no new messages are sent // while we are recovering a subscription to avoid out of order messages. dispatchLock.writeLock().lock(); try { if (topicStore == null) { return; } // Recover the durable subscription. String clientId = subscription.getSubscriptionKey().getClientId(); String subscriptionName = subscription.getSubscriptionKey().getSubscriptionName(); String selector = subscription.getConsumerInfo().getSelector(); SubscriptionInfo info = topicStore.lookupSubscription(clientId, subscriptionName); if (info != null) { // Check to see if selector changed. String s1 = info.getSelector(); if (s1 == null ^ selector == null || (s1 != null && !s1.equals(selector))) { // Need to delete the subscription topicStore.deleteSubscription(clientId, subscriptionName); info = null; synchronized (consumers) { consumers.remove(subscription); } } else { synchronized (consumers) { if (!consumers.contains(subscription)) { consumers.add(subscription); } } } } // Do we need to create the subscription? if (info == null) { info = new SubscriptionInfo(); info.setClientId(clientId); info.setSelector(selector); info.setSubscriptionName(subscriptionName); info.setDestination(getActiveMQDestination()); // This destination is an actual destination id. info.setSubscribedDestination(subscription.getConsumerInfo().getDestination()); // This destination might be a pattern synchronized (consumers) { consumers.add(subscription); topicStore.addSubsciption(info, subscription.getConsumerInfo().isRetroactive()); } } final MessageEvaluationContext msgContext = new NonCachedMessageEvaluationContext(); msgContext.setDestination(destination); if (subscription.isRecoveryRequired()) { topicStore.recoverSubscription(clientId, subscriptionName, new MessageRecoveryListener() { public boolean recoverMessage(Message message) throws Exception { message.setRegionDestination(Topic.this); try { msgContext.setMessageReference(message); if (subscription.matches(message, msgContext)) { subscription.add(message); } } catch (IOException e) { LOG.error("Failed to recover this message " + message); } return true; } public boolean recoverMessageReference(MessageId messageReference) throws Exception { throw new RuntimeException("Should not be called."); } public boolean hasSpace() { return true; } public boolean isDuplicate(MessageId id) { return false; } }); } } finally { dispatchLock.writeLock().unlock(); } } public void deactivate(ConnectionContext context, DurableTopicSubscription sub) throws Exception { synchronized (consumers) { consumers.remove(sub); } sub.remove(context, this); } protected void recoverRetroactiveMessages(ConnectionContext context, Subscription subscription) throws Exception { if (subscription.getConsumerInfo().isRetroactive()) { subscriptionRecoveryPolicy.recover(context, this, subscription); } } public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception { final ConnectionContext context = producerExchange.getConnectionContext(); final ProducerInfo producerInfo = producerExchange.getProducerState().getInfo(); final boolean sendProducerAck = !message.isResponseRequired() && producerInfo.getWindowSize() > 0 && !context.isInRecoveryMode(); // There is delay between the client sending it and it arriving at the // destination.. it may have expired. if (message.isExpired()) { broker.messageExpired(context, message, null); getDestinationStatistics().getExpired().increment(); if (sendProducerAck) { ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize()); context.getConnection().dispatchAsync(ack); } return; } if (memoryUsage.isFull()) { isFull(context, memoryUsage); fastProducer(context, producerInfo); if (isProducerFlowControl() && context.isProducerFlowControl()) { if (warnOnProducerFlowControl) { warnOnProducerFlowControl = false; LOG.info(memoryUsage + ", Usage Manager memory limit reached for " + getActiveMQDestination().getQualifiedName() + ". Producers will be throttled to the rate at which messages are removed from this destination to prevent flooding it." + " See http://activemq.apache.org/producer-flow-control.html for more info"); } if (!context.isNetworkConnection() && systemUsage.isSendFailIfNoSpace()) { throw new javax.jms.ResourceAllocationException("Usage Manager memory limit (" + memoryUsage.getLimit() + ") reached. Rejecting send for producer (" + message.getProducerId() + ") to prevent flooding " + getActiveMQDestination().getQualifiedName() + "." + " See http://activemq.apache.org/producer-flow-control.html for more info"); } // We can avoid blocking due to low usage if the producer is sending a sync message or // if it is using a producer window if (producerInfo.getWindowSize() > 0 || message.isResponseRequired()) { synchronized (messagesWaitingForSpace) { messagesWaitingForSpace.add(new Runnable() { public void run() { try { // While waiting for space to free up... the // message may have expired. if (message.isExpired()) { broker.messageExpired(context, message, null); getDestinationStatistics().getExpired().increment(); } else { doMessageSend(producerExchange, message); } if (sendProducerAck) { ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message .getSize()); context.getConnection().dispatchAsync(ack); } else { Response response = new Response(); response.setCorrelationId(message.getCommandId()); context.getConnection().dispatchAsync(response); } } catch (Exception e) { if (!sendProducerAck && !context.isInRecoveryMode()) { ExceptionResponse response = new ExceptionResponse(e); response.setCorrelationId(message.getCommandId()); context.getConnection().dispatchAsync(response); } } } }); registerCallbackForNotFullNotification(); context.setDontSendReponse(true); return; } } else { // Producer flow control cannot be used, so we have do the flow control // at the broker by blocking this thread until there is space available. if (memoryUsage.isFull()) { if (context.isInTransaction()) { int count = 0; while (!memoryUsage.waitForSpace(1000)) { if (context.getStopping().get()) { throw new IOException("Connection closed, send aborted."); } if (count > 2 && context.isInTransaction()) { count = 0; int size = context.getTransaction().size(); LOG.warn("Waiting for space to send transacted message - transaction elements = " + size + " need more space to commit. Message = " + message); } + count++; } } else { waitForSpace( context, memoryUsage, "Usage Manager Memory Usage limit reached. Stopping producer (" + message.getProducerId() + ") to prevent flooding " + getActiveMQDestination().getQualifiedName() + "." + " See http://activemq.apache.org/producer-flow-control.html for more info"); } } // The usage manager could have delayed us by the time // we unblock the message could have expired.. if (message.isExpired()) { getDestinationStatistics().getExpired().increment(); if (LOG.isDebugEnabled()) { LOG.debug("Expired message: " + message); } return; } } } } doMessageSend(producerExchange, message); messageDelivered(context, message); if (sendProducerAck) { ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize()); context.getConnection().dispatchAsync(ack); } } /** * do send the message - this needs to be synchronized to ensure messages * are stored AND dispatched in the right order * * @param producerExchange * @param message * @throws IOException * @throws Exception */ synchronized void doMessageSend(final ProducerBrokerExchange producerExchange, final Message message) throws IOException, Exception { final ConnectionContext context = producerExchange.getConnectionContext(); message.setRegionDestination(this); message.getMessageId().setBrokerSequenceId(getDestinationSequenceId()); Future<Object> result = null; if (topicStore != null && message.isPersistent() && !canOptimizeOutPersistence()) { if (systemUsage.getStoreUsage().isFull(getStoreUsageHighWaterMark())) { final String logMessage = "Persistent store is Full, " + getStoreUsageHighWaterMark() + "% of " + systemUsage.getStoreUsage().getLimit() + ". Stopping producer (" + message.getProducerId() + ") to prevent flooding " + getActiveMQDestination().getQualifiedName() + "." + " See http://activemq.apache.org/producer-flow-control.html for more info"; if (!context.isNetworkConnection() && systemUsage.isSendFailIfNoSpace()) { throw new javax.jms.ResourceAllocationException(logMessage); } waitForSpace(context, systemUsage.getStoreUsage(), getStoreUsageHighWaterMark(), logMessage); } result = topicStore.asyncAddTopicMessage(context, message,isOptimizeStorage()); } message.incrementReferenceCount(); if (context.isInTransaction()) { context.getTransaction().addSynchronization(new Synchronization() { @Override public void afterCommit() throws Exception { // It could take while before we receive the commit // operation.. by that time the message could have // expired.. if (broker.isExpired(message)) { getDestinationStatistics().getExpired().increment(); broker.messageExpired(context, message, null); message.decrementReferenceCount(); return; } try { dispatch(context, message); } finally { message.decrementReferenceCount(); } } }); } else { try { dispatch(context, message); } finally { message.decrementReferenceCount(); } } if (result != null && !result.isCancelled()) { try { result.get(); } catch (CancellationException e) { // ignore - the task has been cancelled if the message // has already been deleted } } } private boolean canOptimizeOutPersistence() { return durableSubscribers.size() == 0; } @Override public String toString() { return "Topic: destination=" + destination.getPhysicalName() + ", subscriptions=" + consumers.size(); } public void acknowledge(ConnectionContext context, Subscription sub, final MessageAck ack, final MessageReference node) throws IOException { if (topicStore != null && node.isPersistent()) { DurableTopicSubscription dsub = (DurableTopicSubscription) sub; SubscriptionKey key = dsub.getSubscriptionKey(); topicStore.acknowledge(context, key.getClientId(), key.getSubscriptionName(), node.getMessageId(), convertToNonRangedAck(ack, node)); } messageConsumed(context, node); } public void gc() { } public Message loadMessage(MessageId messageId) throws IOException { return topicStore != null ? topicStore.getMessage(messageId) : null; } public void start() throws Exception { this.subscriptionRecoveryPolicy.start(); if (memoryUsage != null) { memoryUsage.start(); } if (getExpireMessagesPeriod() > 0) { scheduler.schedualPeriodically(expireMessagesTask, getExpireMessagesPeriod()); } } public void stop() throws Exception { if (taskRunner != null) { taskRunner.shutdown(); } this.subscriptionRecoveryPolicy.stop(); if (memoryUsage != null) { memoryUsage.stop(); } if (this.topicStore != null) { this.topicStore.stop(); } scheduler.cancel(expireMessagesTask); } public Message[] browse() { final List<Message> result = new ArrayList<Message>(); doBrowse(result, getMaxBrowsePageSize()); return result.toArray(new Message[result.size()]); } private void doBrowse(final List<Message> browseList, final int max) { try { if (topicStore != null) { final List<Message> toExpire = new ArrayList<Message>(); topicStore.recover(new MessageRecoveryListener() { public boolean recoverMessage(Message message) throws Exception { if (message.isExpired()) { toExpire.add(message); } browseList.add(message); return true; } public boolean recoverMessageReference(MessageId messageReference) throws Exception { return true; } public boolean hasSpace() { return browseList.size() < max; } public boolean isDuplicate(MessageId id) { return false; } }); final ConnectionContext connectionContext = createConnectionContext(); for (Message message : toExpire) { for (DurableTopicSubscription sub : durableSubscribers.values()) { if (!sub.isActive()) { messageExpired(connectionContext, sub, message); } } } Message[] msgs = subscriptionRecoveryPolicy.browse(getActiveMQDestination()); if (msgs != null) { for (int i = 0; i < msgs.length && browseList.size() < max; i++) { browseList.add(msgs[i]); } } } } catch (Throwable e) { LOG.warn("Failed to browse Topic: " + getActiveMQDestination().getPhysicalName(), e); } } public boolean iterate() { synchronized (messagesWaitingForSpace) { while (!memoryUsage.isFull() && !messagesWaitingForSpace.isEmpty()) { Runnable op = messagesWaitingForSpace.removeFirst(); op.run(); } if (!messagesWaitingForSpace.isEmpty()) { registerCallbackForNotFullNotification(); } } return false; } private void registerCallbackForNotFullNotification() { // If the usage manager is not full, then the task will not // get called.. if (!memoryUsage.notifyCallbackWhenNotFull(sendMessagesWaitingForSpaceTask)) { // so call it directly here. sendMessagesWaitingForSpaceTask.run(); } } // Properties // ------------------------------------------------------------------------- public DispatchPolicy getDispatchPolicy() { return dispatchPolicy; } public void setDispatchPolicy(DispatchPolicy dispatchPolicy) { this.dispatchPolicy = dispatchPolicy; } public SubscriptionRecoveryPolicy getSubscriptionRecoveryPolicy() { return subscriptionRecoveryPolicy; } public void setSubscriptionRecoveryPolicy(SubscriptionRecoveryPolicy subscriptionRecoveryPolicy) { this.subscriptionRecoveryPolicy = subscriptionRecoveryPolicy; } // Implementation methods // ------------------------------------------------------------------------- public final void wakeup() { } protected void dispatch(final ConnectionContext context, Message message) throws Exception { // AMQ-2586: Better to leave this stat at zero than to give the user // misleading metrics. // destinationStatistics.getMessages().increment(); destinationStatistics.getEnqueues().increment(); MessageEvaluationContext msgContext = null; dispatchLock.readLock().lock(); try { if (!subscriptionRecoveryPolicy.add(context, message)) { return; } synchronized (consumers) { if (consumers.isEmpty()) { onMessageWithNoConsumers(context, message); return; } } msgContext = context.getMessageEvaluationContext(); msgContext.setDestination(destination); msgContext.setMessageReference(message); if (!dispatchPolicy.dispatch(message, msgContext, consumers)) { onMessageWithNoConsumers(context, message); } } finally { dispatchLock.readLock().unlock(); if (msgContext != null) { msgContext.clear(); } } } private final Runnable expireMessagesTask = new Runnable() { public void run() { List<Message> browsedMessages = new InsertionCountList<Message>(); doBrowse(browsedMessages, getMaxExpirePageSize()); } }; public void messageExpired(ConnectionContext context, Subscription subs, MessageReference reference) { broker.messageExpired(context, reference, subs); // AMQ-2586: Better to leave this stat at zero than to give the user // misleading metrics. // destinationStatistics.getMessages().decrement(); destinationStatistics.getEnqueues().decrement(); destinationStatistics.getExpired().increment(); MessageAck ack = new MessageAck(); ack.setAckType(MessageAck.STANDARD_ACK_TYPE); ack.setDestination(destination); ack.setMessageID(reference.getMessageId()); try { if (subs instanceof DurableTopicSubscription) { ((DurableTopicSubscription)subs).removePending(reference); } acknowledge(context, subs, ack, reference); } catch (Exception e) { LOG.error("Failed to remove expired Message from the store ", e); } } @Override protected Logger getLog() { return LOG; } protected boolean isOptimizeStorage(){ boolean result = false; if (isDoOptimzeMessageStorage() && durableSubscribers.isEmpty()==false){ result = true; for (DurableTopicSubscription s : durableSubscribers.values()) { if (s.isActive()== false){ result = false; break; } if (s.getPrefetchSize()==0){ result = false; break; } if (s.isSlowConsumer()){ result = false; break; } if (s.getInFlightUsage() > getOptimizeMessageStoreInFlightLimit()){ result = false; break; } } } return result; } /** * force a reread of the store - after transaction recovery completion */ public void clearPendingMessages() { dispatchLock.readLock().lock(); try { for (DurableTopicSubscription durableTopicSubscription : durableSubscribers.values()) { clearPendingAndDispatch(durableTopicSubscription); } } finally { dispatchLock.readLock().unlock(); } } private void clearPendingAndDispatch(DurableTopicSubscription durableTopicSubscription) { synchronized (durableTopicSubscription.pendingLock) { durableTopicSubscription.pending.clear(); try { durableTopicSubscription.dispatchPending(); } catch (IOException exception) { LOG.warn("After clear of pending, failed to dispatch to: " + durableTopicSubscription + ", for :" + destination + ", pending: " + durableTopicSubscription.pending, exception); } } } public Map<SubscriptionKey, DurableTopicSubscription> getDurableTopicSubs() { return durableSubscribers; } }
true
true
public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception { final ConnectionContext context = producerExchange.getConnectionContext(); final ProducerInfo producerInfo = producerExchange.getProducerState().getInfo(); final boolean sendProducerAck = !message.isResponseRequired() && producerInfo.getWindowSize() > 0 && !context.isInRecoveryMode(); // There is delay between the client sending it and it arriving at the // destination.. it may have expired. if (message.isExpired()) { broker.messageExpired(context, message, null); getDestinationStatistics().getExpired().increment(); if (sendProducerAck) { ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize()); context.getConnection().dispatchAsync(ack); } return; } if (memoryUsage.isFull()) { isFull(context, memoryUsage); fastProducer(context, producerInfo); if (isProducerFlowControl() && context.isProducerFlowControl()) { if (warnOnProducerFlowControl) { warnOnProducerFlowControl = false; LOG.info(memoryUsage + ", Usage Manager memory limit reached for " + getActiveMQDestination().getQualifiedName() + ". Producers will be throttled to the rate at which messages are removed from this destination to prevent flooding it." + " See http://activemq.apache.org/producer-flow-control.html for more info"); } if (!context.isNetworkConnection() && systemUsage.isSendFailIfNoSpace()) { throw new javax.jms.ResourceAllocationException("Usage Manager memory limit (" + memoryUsage.getLimit() + ") reached. Rejecting send for producer (" + message.getProducerId() + ") to prevent flooding " + getActiveMQDestination().getQualifiedName() + "." + " See http://activemq.apache.org/producer-flow-control.html for more info"); } // We can avoid blocking due to low usage if the producer is sending a sync message or // if it is using a producer window if (producerInfo.getWindowSize() > 0 || message.isResponseRequired()) { synchronized (messagesWaitingForSpace) { messagesWaitingForSpace.add(new Runnable() { public void run() { try { // While waiting for space to free up... the // message may have expired. if (message.isExpired()) { broker.messageExpired(context, message, null); getDestinationStatistics().getExpired().increment(); } else { doMessageSend(producerExchange, message); } if (sendProducerAck) { ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message .getSize()); context.getConnection().dispatchAsync(ack); } else { Response response = new Response(); response.setCorrelationId(message.getCommandId()); context.getConnection().dispatchAsync(response); } } catch (Exception e) { if (!sendProducerAck && !context.isInRecoveryMode()) { ExceptionResponse response = new ExceptionResponse(e); response.setCorrelationId(message.getCommandId()); context.getConnection().dispatchAsync(response); } } } }); registerCallbackForNotFullNotification(); context.setDontSendReponse(true); return; } } else { // Producer flow control cannot be used, so we have do the flow control // at the broker by blocking this thread until there is space available. if (memoryUsage.isFull()) { if (context.isInTransaction()) { int count = 0; while (!memoryUsage.waitForSpace(1000)) { if (context.getStopping().get()) { throw new IOException("Connection closed, send aborted."); } if (count > 2 && context.isInTransaction()) { count = 0; int size = context.getTransaction().size(); LOG.warn("Waiting for space to send transacted message - transaction elements = " + size + " need more space to commit. Message = " + message); } } } else { waitForSpace( context, memoryUsage, "Usage Manager Memory Usage limit reached. Stopping producer (" + message.getProducerId() + ") to prevent flooding " + getActiveMQDestination().getQualifiedName() + "." + " See http://activemq.apache.org/producer-flow-control.html for more info"); } } // The usage manager could have delayed us by the time // we unblock the message could have expired.. if (message.isExpired()) { getDestinationStatistics().getExpired().increment(); if (LOG.isDebugEnabled()) { LOG.debug("Expired message: " + message); } return; } } } } doMessageSend(producerExchange, message); messageDelivered(context, message); if (sendProducerAck) { ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize()); context.getConnection().dispatchAsync(ack); } }
public void send(final ProducerBrokerExchange producerExchange, final Message message) throws Exception { final ConnectionContext context = producerExchange.getConnectionContext(); final ProducerInfo producerInfo = producerExchange.getProducerState().getInfo(); final boolean sendProducerAck = !message.isResponseRequired() && producerInfo.getWindowSize() > 0 && !context.isInRecoveryMode(); // There is delay between the client sending it and it arriving at the // destination.. it may have expired. if (message.isExpired()) { broker.messageExpired(context, message, null); getDestinationStatistics().getExpired().increment(); if (sendProducerAck) { ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize()); context.getConnection().dispatchAsync(ack); } return; } if (memoryUsage.isFull()) { isFull(context, memoryUsage); fastProducer(context, producerInfo); if (isProducerFlowControl() && context.isProducerFlowControl()) { if (warnOnProducerFlowControl) { warnOnProducerFlowControl = false; LOG.info(memoryUsage + ", Usage Manager memory limit reached for " + getActiveMQDestination().getQualifiedName() + ". Producers will be throttled to the rate at which messages are removed from this destination to prevent flooding it." + " See http://activemq.apache.org/producer-flow-control.html for more info"); } if (!context.isNetworkConnection() && systemUsage.isSendFailIfNoSpace()) { throw new javax.jms.ResourceAllocationException("Usage Manager memory limit (" + memoryUsage.getLimit() + ") reached. Rejecting send for producer (" + message.getProducerId() + ") to prevent flooding " + getActiveMQDestination().getQualifiedName() + "." + " See http://activemq.apache.org/producer-flow-control.html for more info"); } // We can avoid blocking due to low usage if the producer is sending a sync message or // if it is using a producer window if (producerInfo.getWindowSize() > 0 || message.isResponseRequired()) { synchronized (messagesWaitingForSpace) { messagesWaitingForSpace.add(new Runnable() { public void run() { try { // While waiting for space to free up... the // message may have expired. if (message.isExpired()) { broker.messageExpired(context, message, null); getDestinationStatistics().getExpired().increment(); } else { doMessageSend(producerExchange, message); } if (sendProducerAck) { ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message .getSize()); context.getConnection().dispatchAsync(ack); } else { Response response = new Response(); response.setCorrelationId(message.getCommandId()); context.getConnection().dispatchAsync(response); } } catch (Exception e) { if (!sendProducerAck && !context.isInRecoveryMode()) { ExceptionResponse response = new ExceptionResponse(e); response.setCorrelationId(message.getCommandId()); context.getConnection().dispatchAsync(response); } } } }); registerCallbackForNotFullNotification(); context.setDontSendReponse(true); return; } } else { // Producer flow control cannot be used, so we have do the flow control // at the broker by blocking this thread until there is space available. if (memoryUsage.isFull()) { if (context.isInTransaction()) { int count = 0; while (!memoryUsage.waitForSpace(1000)) { if (context.getStopping().get()) { throw new IOException("Connection closed, send aborted."); } if (count > 2 && context.isInTransaction()) { count = 0; int size = context.getTransaction().size(); LOG.warn("Waiting for space to send transacted message - transaction elements = " + size + " need more space to commit. Message = " + message); } count++; } } else { waitForSpace( context, memoryUsage, "Usage Manager Memory Usage limit reached. Stopping producer (" + message.getProducerId() + ") to prevent flooding " + getActiveMQDestination().getQualifiedName() + "." + " See http://activemq.apache.org/producer-flow-control.html for more info"); } } // The usage manager could have delayed us by the time // we unblock the message could have expired.. if (message.isExpired()) { getDestinationStatistics().getExpired().increment(); if (LOG.isDebugEnabled()) { LOG.debug("Expired message: " + message); } return; } } } } doMessageSend(producerExchange, message); messageDelivered(context, message); if (sendProducerAck) { ProducerAck ack = new ProducerAck(producerInfo.getProducerId(), message.getSize()); context.getConnection().dispatchAsync(ack); } }
diff --git a/core/src/main/java/org/springframework/security/ui/AuthenticationDetailsSourceImpl.java b/core/src/main/java/org/springframework/security/ui/AuthenticationDetailsSourceImpl.java index 2508cd6ab..676bbee97 100755 --- a/core/src/main/java/org/springframework/security/ui/AuthenticationDetailsSourceImpl.java +++ b/core/src/main/java/org/springframework/security/ui/AuthenticationDetailsSourceImpl.java @@ -1,81 +1,81 @@ package org.springframework.security.ui; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import org.springframework.security.ui.AuthenticationDetailsSource; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; /** * Base implementation of {@link AuthenticationDetailsSource}. * <p> * By default will create an instance of <code>AuthenticationDetails</code>. * Any object that accepts an <code>Object</code> as its sole constructor can * be used instead of this default. * </p> * * @author Ruud Senden * @since 2.0 */ public class AuthenticationDetailsSourceImpl implements AuthenticationDetailsSource { //~ Instance fields ================================================================================================ private Class clazz = AuthenticationDetails.class; //~ Methods ======================================================================================================== public Object buildDetails(Object context) { try { Constructor constructor = getFirstMatchingConstructor(context); return constructor.newInstance(new Object[] { context }); } catch (NoSuchMethodException ex) { ReflectionUtils.handleReflectionException(ex); } catch (InvocationTargetException ex) { ReflectionUtils.handleReflectionException(ex); } catch (InstantiationException ex) { ReflectionUtils.handleReflectionException(ex); } catch (IllegalAccessException ex) { ReflectionUtils.handleReflectionException(ex); } return null; } /** * Return the first matching constructor that can take the given object * as an argument. Please note that we cannot use * getDeclaredConstructor(new Class[]{object.getClass()}) * as this will only match if the constructor argument type matches * the object type exactly (instead of checking whether it is assignable) * * @param object the object for which to find a matching constructor * @return a matching constructor for the given object * @throws NoSuchMethodException if no matching constructor can be found */ private Constructor getFirstMatchingConstructor(Object object) throws NoSuchMethodException { Constructor[] constructors = clazz.getDeclaredConstructors(); Constructor constructor = null; for (int i = 0; i < constructors.length; i++) { Class[] parameterTypes = constructors[i].getParameterTypes(); - if (parameterTypes.length == 1 && (object == null || parameterTypes[i].isInstance(object))) { + if (parameterTypes.length == 1 && (object == null || parameterTypes[0].isInstance(object))) { constructor = constructors[i]; break; } } if (constructor == null) { if (object == null) { throw new NoSuchMethodException("No constructor found that can take a single argument"); } else { throw new NoSuchMethodException("No constructor found that can take a single argument of type " + object.getClass()); } } return constructor; } public void setClazz(Class clazz) { Assert.notNull(clazz, "Class required"); this.clazz = clazz; } }
true
true
private Constructor getFirstMatchingConstructor(Object object) throws NoSuchMethodException { Constructor[] constructors = clazz.getDeclaredConstructors(); Constructor constructor = null; for (int i = 0; i < constructors.length; i++) { Class[] parameterTypes = constructors[i].getParameterTypes(); if (parameterTypes.length == 1 && (object == null || parameterTypes[i].isInstance(object))) { constructor = constructors[i]; break; } } if (constructor == null) { if (object == null) { throw new NoSuchMethodException("No constructor found that can take a single argument"); } else { throw new NoSuchMethodException("No constructor found that can take a single argument of type " + object.getClass()); } } return constructor; }
private Constructor getFirstMatchingConstructor(Object object) throws NoSuchMethodException { Constructor[] constructors = clazz.getDeclaredConstructors(); Constructor constructor = null; for (int i = 0; i < constructors.length; i++) { Class[] parameterTypes = constructors[i].getParameterTypes(); if (parameterTypes.length == 1 && (object == null || parameterTypes[0].isInstance(object))) { constructor = constructors[i]; break; } } if (constructor == null) { if (object == null) { throw new NoSuchMethodException("No constructor found that can take a single argument"); } else { throw new NoSuchMethodException("No constructor found that can take a single argument of type " + object.getClass()); } } return constructor; }
diff --git a/src/java/org/apache/commons/beanutils/locale/converters/FloatLocaleConverter.java b/src/java/org/apache/commons/beanutils/locale/converters/FloatLocaleConverter.java index a60fe7f..5e66d9a 100755 --- a/src/java/org/apache/commons/beanutils/locale/converters/FloatLocaleConverter.java +++ b/src/java/org/apache/commons/beanutils/locale/converters/FloatLocaleConverter.java @@ -1,224 +1,224 @@ /* * 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.commons.beanutils.locale.converters; import org.apache.commons.beanutils.ConversionException; import java.util.Locale; import java.text.ParseException; /** * <p>Standard {@link org.apache.commons.beanutils.locale.LocaleConverter} * implementation that converts an incoming * locale-sensitive String into a <code>java.math.BigDecimal</code> object, * optionally using a default value or throwing a * {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs.</p> * * @author Yauheny Mikulski */ public class FloatLocaleConverter extends DecimalLocaleConverter { // ----------------------------------------------------------- Constructors /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * */ public FloatLocaleConverter() { this(false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(boolean locPattern) { this(Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale */ public FloatLocaleConverter(Locale locale) { this(locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(Locale locale, boolean locPattern) { this(locale, (String) null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param locale The locale * @param pattern The convertion pattern */ public FloatLocaleConverter(Locale locale, String pattern) { this(locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will throw a {@link org.apache.commons.beanutils.ConversionException} * if a conversion error occurs. * * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(Locale locale, String pattern, boolean locPattern) { super(locale, pattern, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine and an unlocalized pattern is used * for the convertion. * * @param defaultValue The default value to be returned */ public FloatLocaleConverter(Object defaultValue) { this(defaultValue, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. The locale is the default locale for * this instance of the Java Virtual Machine. * * @param defaultValue The default value to be returned * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(Object defaultValue, boolean locPattern) { this(defaultValue, Locale.getDefault(), locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale */ public FloatLocaleConverter(Object defaultValue, Locale locale) { this(defaultValue, locale, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(Object defaultValue, Locale locale, boolean locPattern) { this(defaultValue, locale, null, locPattern); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. An unlocalized pattern is used for the convertion. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern */ public FloatLocaleConverter(Object defaultValue, Locale locale, String pattern) { this(defaultValue, locale, pattern, false); } /** * Create a {@link org.apache.commons.beanutils.locale.LocaleConverter} * that will return the specified default value * if a conversion error occurs. * * @param defaultValue The default value to be returned * @param locale The locale * @param pattern The convertion pattern * @param locPattern Indicate whether the pattern is localized or not */ public FloatLocaleConverter(Object defaultValue, Locale locale, String pattern, boolean locPattern) { super(defaultValue, locale, pattern, locPattern); } /** * Convert the specified locale-sensitive input object into an output object of the * specified type. This method will return Float value or throw exception if value * can not be stored in the Float. * * @param value The input object to be converted * @param pattern The pattern is used for the convertion * * @exception ConversionException if conversion cannot be performed * successfully */ protected Object parse(Object value, String pattern) throws ParseException { final Number parsed = (Number) super.parse(value, pattern); double doubleValue = parsed.doubleValue(); double posDouble = (doubleValue >= (double)0) ? doubleValue : (doubleValue * (double)-1); if (posDouble < Float.MIN_VALUE || posDouble > Float.MAX_VALUE) { - throw new ConversionException("Suplied number is not of type Float: "+parsed); + throw new ConversionException("Supplied number is not of type Float: "+parsed); } return new Float(parsed.floatValue()); // unlike superclass it returns Float type } }
true
true
protected Object parse(Object value, String pattern) throws ParseException { final Number parsed = (Number) super.parse(value, pattern); double doubleValue = parsed.doubleValue(); double posDouble = (doubleValue >= (double)0) ? doubleValue : (doubleValue * (double)-1); if (posDouble < Float.MIN_VALUE || posDouble > Float.MAX_VALUE) { throw new ConversionException("Suplied number is not of type Float: "+parsed); } return new Float(parsed.floatValue()); // unlike superclass it returns Float type }
protected Object parse(Object value, String pattern) throws ParseException { final Number parsed = (Number) super.parse(value, pattern); double doubleValue = parsed.doubleValue(); double posDouble = (doubleValue >= (double)0) ? doubleValue : (doubleValue * (double)-1); if (posDouble < Float.MIN_VALUE || posDouble > Float.MAX_VALUE) { throw new ConversionException("Supplied number is not of type Float: "+parsed); } return new Float(parsed.floatValue()); // unlike superclass it returns Float type }
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/editor/semantic/MarkOccurrencesHighlighter.java b/javafx.editor/src/org/netbeans/modules/javafx/editor/semantic/MarkOccurrencesHighlighter.java index b6c12454..83f0eda1 100644 --- a/javafx.editor/src/org/netbeans/modules/javafx/editor/semantic/MarkOccurrencesHighlighter.java +++ b/javafx.editor/src/org/netbeans/modules/javafx/editor/semantic/MarkOccurrencesHighlighter.java @@ -1,545 +1,545 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.javafx.editor.semantic; import com.sun.javafx.api.tree.*; import com.sun.javafx.api.tree.Tree.JavaFXKind; import com.sun.tools.javafx.tree.JFXClassDeclaration; import com.sun.tools.javafx.tree.JFXFunctionDefinition; import org.netbeans.api.editor.settings.AttributesUtilities; import org.netbeans.api.javafx.lexer.JFXTokenId; import org.netbeans.api.javafx.source.CancellableTask; import org.netbeans.api.javafx.source.CompilationInfo; import org.netbeans.api.javafx.source.TreeUtilities; import org.netbeans.api.lexer.Token; import org.netbeans.api.lexer.TokenHierarchy; import org.netbeans.api.lexer.TokenSequence; import org.netbeans.modules.editor.errorstripe.privatespi.Mark; import org.netbeans.modules.javafx.editor.options.MarkOccurencesSettings; import org.netbeans.spi.editor.highlighting.support.OffsetsBag; import org.openide.filesystems.FileObject; import org.openide.util.NbBundle; import javax.lang.model.element.Element; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.AttributeSet; import javax.swing.text.Document; import javax.swing.text.StyleConstants; import java.awt.*; import java.io.IOException; import java.util.*; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.prefs.Preferences; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.util.ElementFilter; /** * * @author Jan Lahoda, Anton Chechel */ public class MarkOccurrencesHighlighter implements CancellableTask<CompilationInfo> { public static final Color ES_COLOR = new Color(175, 172, 102); // new Color(244, 164, 113); private FileObject file; MarkOccurrencesHighlighter(FileObject file) { this.file = file; } public void run(CompilationInfo info) throws IOException { resume(); Document doc = info.getJavaFXSource().getDocument(); if (doc == null) { Logger.getLogger(MarkOccurrencesHighlighter.class.getName()).log(Level.FINE, "SemanticHighlighter: Cannot get document!"); // NOI18N return; } Preferences pref = MarkOccurencesSettings.getCurrentNode(); if (!pref.getBoolean(MarkOccurencesSettings.ON_OFF, true)) { getHighlightsBag(doc).clear(); OccurrencesMarkProvider.get(doc).setOccurrences(Collections.<Mark>emptySet()); return; } int caretPosition = MarkOccurrencesHighlighterFactory.getLastPosition(file); if (isCancelled()) { return; } List<int[]> bag = processImpl(info, pref, doc, caretPosition); if (isCancelled()) { return; } if (bag == null) { if (pref.getBoolean(MarkOccurencesSettings.KEEP_MARKS, true)) { return; } bag = new ArrayList<int[]>(); } Collections.sort(bag, new Comparator<int[]>() { public int compare(int[] o1, int[] o2) { return o1[0] - o2[0]; } }); Iterator<int[]> it = bag.iterator(); int[] last = it.hasNext() ? it.next() : null; List<int[]> result = new ArrayList<int[]>(bag.size()); while (it.hasNext()) { int[] current = it.next(); if (current[0] < last[1]) { //merge the highlights: last[1] = Math.max(current[1], last[1]); } else { result.add(last); last = current; } } if (last != null) { result.add(last); } OffsetsBag obag = new OffsetsBag(doc); obag.clear(); AttributeSet attributes = AttributesUtilities.createImmutable(StyleConstants.Background, new Color(236, 235, 163)); for (int[] span : result) { int convertedStart = span[0]; int convertedEnd = span[1]; if (convertedStart != (-1) && convertedEnd != (-1)) { obag.addHighlight(convertedStart, convertedEnd, attributes); } } getHighlightsBag(doc).setHighlights(obag); OccurrencesMarkProvider.get(doc).setOccurrences(OccurrencesMarkProvider.createMarks(doc, bag, ES_COLOR, NbBundle.getMessage(MarkOccurrencesHighlighter.class, "LBL_ES_TOOLTIP"))); // NOI18N } private boolean isIn(UnitTree cu, SourcePositions sp, Tree tree, int position) { return sp.getStartPosition(cu, tree) <= position && position <= sp.getEndPosition(cu, tree); } private boolean isIn(int caretPosition, Token<?> span) { if (span == null) { return false; } return span.offset(null) <= caretPosition && caretPosition <= span.offset(null) + span.length(); } List<int[]> processImpl(CompilationInfo info, Preferences pref, Document doc, int caretPosition) { UnitTree cu = info.getCompilationUnit(); // TreePath tp = info.getTreeUtilities().pathFor(caretPosition); TreeUtilities tu = new TreeUtilities(info); JavaFXTreePath tp = tu.pathFor(caretPosition); JavaFXTreePath typePath = findTypePath(tp); if (isCancelled()) { return null; } //detect caret inside the return type or throws clause: // manowar: a bit of FX magic if (typePath != null) { JavaFXTreePath pTypePath = typePath.getParentPath(); if (pTypePath != null) { JavaFXTreePath gpTypePath = pTypePath.getParentPath(); if (gpTypePath != null) { JavaFXTreePath ggpTypePath = gpTypePath.getParentPath(); if (getJFXKind(ggpTypePath) == JavaFXKind.FUNCTION_DEFINITION && getJFXKind(gpTypePath) == JavaFXKind.FUNCTION_VALUE && getJFXKind(pTypePath) == JavaFXKind.TYPE_CLASS && getJFXKind(typePath) == JavaFXKind.IDENTIFIER) { JFXFunctionDefinition decl = (JFXFunctionDefinition) ggpTypePath.getLeaf(); Tree type = decl.getJFXReturnType(); if (pref.getBoolean(MarkOccurencesSettings.EXIT, true) && isIn(cu, info.getTrees().getSourcePositions(), type, caretPosition)) { MethodExitDetector med = new MethodExitDetector(); setExitDetector(med); try { return med.process(info, doc, decl, null); } finally { setExitDetector(null); } } if (pref.getBoolean(MarkOccurencesSettings.EXCEPTIONS, true)) { for (Tree exc : decl.getErrorTrees()) { if (isIn(cu, info.getTrees().getSourcePositions(), exc, caretPosition)) { MethodExitDetector med = new MethodExitDetector(); setExitDetector(med); try { return med.process(info, doc, decl, Collections.singletonList(exc)); } finally { setExitDetector(null); } } } } } } } } if (isCancelled()) { return null; } // extends/implements clause if (pref.getBoolean(MarkOccurencesSettings.IMPLEMENTS, true)) { if (typePath != null && getJFXKind(typePath) == JavaFXKind.TYPE_CLASS) { boolean isExtends = true; boolean isImplements = false; // boolean isExtends = ctree.getExtendsClause() == typePath.getLeaf(); // boolean isImplements = false; // // for (Tree t : ctree.getImplementsClause()) { // if (t == typePath.getLeaf()) { // isImplements = true; // break; // } // } if ((isExtends && pref.getBoolean(MarkOccurencesSettings.OVERRIDES, true)) || (isImplements && pref.getBoolean(MarkOccurencesSettings.IMPLEMENTS, true))) { Element superType = info.getTrees().getElement(typePath); Element thisType = info.getTrees().getElement(typePath.getParentPath()); if (isClass(superType) && isClass(thisType)) return detectMethodsForClass(info, doc, typePath.getParentPath(), (TypeElement) superType, (TypeElement) thisType); } } if (isCancelled()) return null; TokenSequence<JFXTokenId> ts = info.getTokenHierarchy().tokenSequence(JFXTokenId.language()); if (ts != null && tp.getLeaf().getJavaFXKind() == JavaFXKind.CLASS_DECLARATION) { int bodyStart = Utilities.findBodyStart(tp.getLeaf(), cu, info.getTrees().getSourcePositions(), doc); if (caretPosition < bodyStart) { ts.move(caretPosition); if (ts.moveNext()) { if (pref.getBoolean(MarkOccurencesSettings.OVERRIDES, true) && ts.token().id() == JFXTokenId.EXTENDS) { // Tree superClass = ((ClassTree) tp.getLeaf()).getExtendsClause(); - Tree superClass = (JFXClassDeclaration) typePath.getParentPath().getLeaf(); + Tree superClass = typePath.getParentPath() != null ? (JFXClassDeclaration) typePath.getParentPath().getLeaf() : null; if (superClass != null) { Element superType = info.getTrees().getElement(new JavaFXTreePath(tp, superClass)); Element thisType = info.getTrees().getElement(tp); if (isClass(superType) && isClass(thisType)) return detectMethodsForClass(info, doc, tp, (TypeElement) superType, (TypeElement) thisType); } } // if (pref.getBoolean(MarkOccurencesSettings.IMPLEMENTS, true) && ts.token().id() == JFXTokenId.IMPLEMENTS) { // List<? extends Tree> superClasses = ((ClassTree) tp.getLeaf()).getImplementsClause(); // // if (superClasses != null) { // List<TypeElement> superTypes = new ArrayList<TypeElement>(); // // for (Tree superTypeTree : superClasses) { // if (superTypeTree != null) { // Element superType = info.getTrees().getElement(new JavaFXTreePath(tp, superTypeTree)); // // if (isClass(superType)) // superTypes.add((TypeElement) superType); // } // } // // Element thisType = info.getTrees().getElement(tp); // // if (!superTypes.isEmpty() && isClass(thisType)) // return detectMethodsForClass(info, doc, tp, superTypes, (TypeElement) thisType); // } // // } } } } } if (isCancelled()) { return null; } Tree tree = tp.getLeaf(); if (pref.getBoolean(MarkOccurencesSettings.BREAK_CONTINUE, true) && (tree.getJavaFXKind() == JavaFXKind.BREAK || tree.getJavaFXKind() == JavaFXKind.CONTINUE)) { return detectBreakOrContinueTarget(info, doc, tp); } if (isCancelled()) { return null; } // TODO inside javadoc // variable declaration Element el = info.getTrees().getElement(tp); if (el != null && !Utilities.isKeyword(tree) && isEnabled(pref, el) && (tree.getJavaFXKind() != JavaFXKind.CLASS_DECLARATION || isIn(caretPosition, Utilities.findIdentifierSpan(info, doc, tp))) && (tree.getJavaFXKind() != JavaFXKind.FUNCTION_DEFINITION || isIn(caretPosition, Utilities.findIdentifierSpan(info, doc, tp)))) { FindLocalUsagesQuery fluq = new FindLocalUsagesQuery(); setLocalUsages(fluq); try { List<int[]> bag = new ArrayList<int[]>(); for (Token<?> t : fluq.findUsages(el, info, doc)) { bag.add(new int[]{t.offset(null), t.offset(null) + t.length()}); } return bag; } finally { setLocalUsages(null); } } return null; } private List<int[]> detectMethodsForClass(CompilationInfo info, Document document, JavaFXTreePath clazz, TypeElement superType, TypeElement thisType) { return detectMethodsForClass(info, document, clazz, Collections.singletonList(superType), thisType); } private List<int[]> detectMethodsForClass(CompilationInfo info, Document document, JavaFXTreePath clazz, List<TypeElement> superTypes, TypeElement thisType) { List<int[]> highlights = new ArrayList<int[]>(); JFXClassDeclaration clazzTree = (JFXClassDeclaration) clazz.getLeaf(); TypeElement jlObject = info.getElements().getTypeElement("java.lang.Object"); // NOI18N OUTER: for (Tree member: clazzTree.getMembers()) { if (isCancelled()) { return null; } if (member.getJavaFXKind() == JavaFXKind.FUNCTION_DEFINITION) { JavaFXTreePath path = new JavaFXTreePath(clazz, member); Element el = info.getTrees().getElement(path); if (el.getKind() == ElementKind.METHOD) { for (TypeElement superType : superTypes) { for (ExecutableElement ee : ElementFilter.methodsIn(info.getElements().getAllMembers(superType))) { if (info.getElements().overrides((ExecutableElement) el, ee, thisType) && (superType.getKind().isClass() || !ee.getEnclosingElement().equals(jlObject))) { Token t = Utilities.getToken(info, document, path); if (t != null) { highlights.add(new int[] {t.offset(null), t.offset(null) + t.length()}); } continue OUTER; } } } } } } return highlights; } private static final Set<JavaFXKind> TYPE_PATH_ELEMENT = EnumSet.of(JavaFXKind.IDENTIFIER, JavaFXKind.MEMBER_SELECT); private static JavaFXTreePath findTypePath(JavaFXTreePath tp) { if (!TYPE_PATH_ELEMENT.contains(tp.getLeaf().getJavaFXKind())) { return null; } while (TYPE_PATH_ELEMENT.contains(tp.getParentPath().getLeaf().getJavaFXKind())) { tp = tp.getParentPath(); } return tp; } private static boolean isClass(Element el) { return el != null && (el.getKind().isClass() || el.getKind().isInterface()); } private static boolean isEnabled(Preferences pref, Element el) { switch (el.getKind()) { case ANNOTATION_TYPE: case CLASS: case ENUM: case INTERFACE: case TYPE_PARAMETER: return pref.getBoolean(MarkOccurencesSettings.TYPES, true); case CONSTRUCTOR: case METHOD: return pref.getBoolean(MarkOccurencesSettings.METHODS, true); case ENUM_CONSTANT: return pref.getBoolean(MarkOccurencesSettings.CONSTANTS, true); case FIELD: if (el.getModifiers().containsAll(EnumSet.of(Modifier.STATIC, Modifier.FINAL))) { return pref.getBoolean(MarkOccurencesSettings.CONSTANTS, true); } else { return pref.getBoolean(MarkOccurencesSettings.FIELDS, true); } case LOCAL_VARIABLE: case PARAMETER: case EXCEPTION_PARAMETER: return pref.getBoolean(MarkOccurencesSettings.LOCAL_VARIABLES, true); case PACKAGE: return false; // never mark occurrence packages default: Logger.getLogger(MarkOccurrencesHighlighter.class.getName()).log(Level.INFO, "Unknow element type: {0}.", el.getKind()); return true; } } private boolean canceled; private MethodExitDetector exitDetector; private FindLocalUsagesQuery localUsages; private final synchronized void setExitDetector(MethodExitDetector detector) { this.exitDetector = detector; } private final synchronized void setLocalUsages(FindLocalUsagesQuery localUsages) { this.localUsages = localUsages; } public final synchronized void cancel() { canceled = true; if (exitDetector != null) { exitDetector.cancel(); } if (localUsages != null) { localUsages.cancel(); } } protected final synchronized boolean isCancelled() { return canceled; } protected final synchronized void resume() { canceled = false; } private List<int[]> detectBreakOrContinueTarget(CompilationInfo info, Document document, JavaFXTreePath breakOrContinue) { List<int[]> result = new ArrayList<int[]>(); ExpressionTree target = new TreeUtilities(info).getBreakContinueTarget(breakOrContinue); if (target == null) { return null; } TokenSequence<JFXTokenId> ts = ((TokenHierarchy<?>) info.getTokenHierarchy()).tokenSequence(JFXTokenId.language()); ts.move((int) info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), target)); if (ts.moveNext()) { result.add(new int[]{ts.offset(), ts.offset() + ts.token().length()}); } ExpressionTree statement = target; Tree block = null; switch (statement.getJavaFXKind()) { case WHILE_LOOP: if (((WhileLoopTree) statement).getStatement().getJavaFXKind() == JavaFXKind.BLOCK_EXPRESSION) { block = ((WhileLoopTree) statement).getStatement(); } break; case FOR_EXPRESSION_FOR: if (((ForExpressionTree) statement).getBodyExpression().getJavaFXKind() == JavaFXKind.BLOCK_EXPRESSION) { block = ((ForExpressionTree) statement).getBodyExpression(); } break; } if (block != null) { ts.move((int) info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), block)); if (ts.movePrevious() && ts.token().id() == JFXTokenId.RBRACE) { result.add(new int[]{ts.offset(), ts.offset() + ts.token().length()}); } } return result; } static OffsetsBag getHighlightsBag(Document doc) { OffsetsBag bag = (OffsetsBag) doc.getProperty(MarkOccurrencesHighlighter.class); if (bag == null) { doc.putProperty(MarkOccurrencesHighlighter.class, bag = new OffsetsBag(doc, false)); final OffsetsBag bagFin = bag; DocumentListener l = new DocumentListener() { public void insertUpdate(DocumentEvent e) { bagFin.removeHighlights(e.getOffset(), e.getOffset(), false); } public void removeUpdate(DocumentEvent e) { bagFin.removeHighlights(e.getOffset(), e.getOffset(), false); } public void changedUpdate(DocumentEvent e) { } }; doc.addDocumentListener(l); } return bag; } private static JavaFXKind getJFXKind(JavaFXTreePath tp) { return (tp == null || tp.getLeaf() == null) ? null : tp.getLeaf().getJavaFXKind(); } }
true
true
List<int[]> processImpl(CompilationInfo info, Preferences pref, Document doc, int caretPosition) { UnitTree cu = info.getCompilationUnit(); // TreePath tp = info.getTreeUtilities().pathFor(caretPosition); TreeUtilities tu = new TreeUtilities(info); JavaFXTreePath tp = tu.pathFor(caretPosition); JavaFXTreePath typePath = findTypePath(tp); if (isCancelled()) { return null; } //detect caret inside the return type or throws clause: // manowar: a bit of FX magic if (typePath != null) { JavaFXTreePath pTypePath = typePath.getParentPath(); if (pTypePath != null) { JavaFXTreePath gpTypePath = pTypePath.getParentPath(); if (gpTypePath != null) { JavaFXTreePath ggpTypePath = gpTypePath.getParentPath(); if (getJFXKind(ggpTypePath) == JavaFXKind.FUNCTION_DEFINITION && getJFXKind(gpTypePath) == JavaFXKind.FUNCTION_VALUE && getJFXKind(pTypePath) == JavaFXKind.TYPE_CLASS && getJFXKind(typePath) == JavaFXKind.IDENTIFIER) { JFXFunctionDefinition decl = (JFXFunctionDefinition) ggpTypePath.getLeaf(); Tree type = decl.getJFXReturnType(); if (pref.getBoolean(MarkOccurencesSettings.EXIT, true) && isIn(cu, info.getTrees().getSourcePositions(), type, caretPosition)) { MethodExitDetector med = new MethodExitDetector(); setExitDetector(med); try { return med.process(info, doc, decl, null); } finally { setExitDetector(null); } } if (pref.getBoolean(MarkOccurencesSettings.EXCEPTIONS, true)) { for (Tree exc : decl.getErrorTrees()) { if (isIn(cu, info.getTrees().getSourcePositions(), exc, caretPosition)) { MethodExitDetector med = new MethodExitDetector(); setExitDetector(med); try { return med.process(info, doc, decl, Collections.singletonList(exc)); } finally { setExitDetector(null); } } } } } } } } if (isCancelled()) { return null; } // extends/implements clause if (pref.getBoolean(MarkOccurencesSettings.IMPLEMENTS, true)) { if (typePath != null && getJFXKind(typePath) == JavaFXKind.TYPE_CLASS) { boolean isExtends = true; boolean isImplements = false; // boolean isExtends = ctree.getExtendsClause() == typePath.getLeaf(); // boolean isImplements = false; // // for (Tree t : ctree.getImplementsClause()) { // if (t == typePath.getLeaf()) { // isImplements = true; // break; // } // } if ((isExtends && pref.getBoolean(MarkOccurencesSettings.OVERRIDES, true)) || (isImplements && pref.getBoolean(MarkOccurencesSettings.IMPLEMENTS, true))) { Element superType = info.getTrees().getElement(typePath); Element thisType = info.getTrees().getElement(typePath.getParentPath()); if (isClass(superType) && isClass(thisType)) return detectMethodsForClass(info, doc, typePath.getParentPath(), (TypeElement) superType, (TypeElement) thisType); } } if (isCancelled()) return null; TokenSequence<JFXTokenId> ts = info.getTokenHierarchy().tokenSequence(JFXTokenId.language()); if (ts != null && tp.getLeaf().getJavaFXKind() == JavaFXKind.CLASS_DECLARATION) { int bodyStart = Utilities.findBodyStart(tp.getLeaf(), cu, info.getTrees().getSourcePositions(), doc); if (caretPosition < bodyStart) { ts.move(caretPosition); if (ts.moveNext()) { if (pref.getBoolean(MarkOccurencesSettings.OVERRIDES, true) && ts.token().id() == JFXTokenId.EXTENDS) { // Tree superClass = ((ClassTree) tp.getLeaf()).getExtendsClause(); Tree superClass = (JFXClassDeclaration) typePath.getParentPath().getLeaf(); if (superClass != null) { Element superType = info.getTrees().getElement(new JavaFXTreePath(tp, superClass)); Element thisType = info.getTrees().getElement(tp); if (isClass(superType) && isClass(thisType)) return detectMethodsForClass(info, doc, tp, (TypeElement) superType, (TypeElement) thisType); } } // if (pref.getBoolean(MarkOccurencesSettings.IMPLEMENTS, true) && ts.token().id() == JFXTokenId.IMPLEMENTS) { // List<? extends Tree> superClasses = ((ClassTree) tp.getLeaf()).getImplementsClause(); // // if (superClasses != null) { // List<TypeElement> superTypes = new ArrayList<TypeElement>(); // // for (Tree superTypeTree : superClasses) { // if (superTypeTree != null) { // Element superType = info.getTrees().getElement(new JavaFXTreePath(tp, superTypeTree)); // // if (isClass(superType)) // superTypes.add((TypeElement) superType); // } // } // // Element thisType = info.getTrees().getElement(tp); // // if (!superTypes.isEmpty() && isClass(thisType)) // return detectMethodsForClass(info, doc, tp, superTypes, (TypeElement) thisType); // } // // } } } } } if (isCancelled()) { return null; } Tree tree = tp.getLeaf(); if (pref.getBoolean(MarkOccurencesSettings.BREAK_CONTINUE, true) && (tree.getJavaFXKind() == JavaFXKind.BREAK || tree.getJavaFXKind() == JavaFXKind.CONTINUE)) { return detectBreakOrContinueTarget(info, doc, tp); } if (isCancelled()) { return null; } // TODO inside javadoc // variable declaration Element el = info.getTrees().getElement(tp); if (el != null && !Utilities.isKeyword(tree) && isEnabled(pref, el) && (tree.getJavaFXKind() != JavaFXKind.CLASS_DECLARATION || isIn(caretPosition, Utilities.findIdentifierSpan(info, doc, tp))) && (tree.getJavaFXKind() != JavaFXKind.FUNCTION_DEFINITION || isIn(caretPosition, Utilities.findIdentifierSpan(info, doc, tp)))) { FindLocalUsagesQuery fluq = new FindLocalUsagesQuery(); setLocalUsages(fluq); try { List<int[]> bag = new ArrayList<int[]>(); for (Token<?> t : fluq.findUsages(el, info, doc)) { bag.add(new int[]{t.offset(null), t.offset(null) + t.length()}); } return bag; } finally { setLocalUsages(null); } } return null; }
List<int[]> processImpl(CompilationInfo info, Preferences pref, Document doc, int caretPosition) { UnitTree cu = info.getCompilationUnit(); // TreePath tp = info.getTreeUtilities().pathFor(caretPosition); TreeUtilities tu = new TreeUtilities(info); JavaFXTreePath tp = tu.pathFor(caretPosition); JavaFXTreePath typePath = findTypePath(tp); if (isCancelled()) { return null; } //detect caret inside the return type or throws clause: // manowar: a bit of FX magic if (typePath != null) { JavaFXTreePath pTypePath = typePath.getParentPath(); if (pTypePath != null) { JavaFXTreePath gpTypePath = pTypePath.getParentPath(); if (gpTypePath != null) { JavaFXTreePath ggpTypePath = gpTypePath.getParentPath(); if (getJFXKind(ggpTypePath) == JavaFXKind.FUNCTION_DEFINITION && getJFXKind(gpTypePath) == JavaFXKind.FUNCTION_VALUE && getJFXKind(pTypePath) == JavaFXKind.TYPE_CLASS && getJFXKind(typePath) == JavaFXKind.IDENTIFIER) { JFXFunctionDefinition decl = (JFXFunctionDefinition) ggpTypePath.getLeaf(); Tree type = decl.getJFXReturnType(); if (pref.getBoolean(MarkOccurencesSettings.EXIT, true) && isIn(cu, info.getTrees().getSourcePositions(), type, caretPosition)) { MethodExitDetector med = new MethodExitDetector(); setExitDetector(med); try { return med.process(info, doc, decl, null); } finally { setExitDetector(null); } } if (pref.getBoolean(MarkOccurencesSettings.EXCEPTIONS, true)) { for (Tree exc : decl.getErrorTrees()) { if (isIn(cu, info.getTrees().getSourcePositions(), exc, caretPosition)) { MethodExitDetector med = new MethodExitDetector(); setExitDetector(med); try { return med.process(info, doc, decl, Collections.singletonList(exc)); } finally { setExitDetector(null); } } } } } } } } if (isCancelled()) { return null; } // extends/implements clause if (pref.getBoolean(MarkOccurencesSettings.IMPLEMENTS, true)) { if (typePath != null && getJFXKind(typePath) == JavaFXKind.TYPE_CLASS) { boolean isExtends = true; boolean isImplements = false; // boolean isExtends = ctree.getExtendsClause() == typePath.getLeaf(); // boolean isImplements = false; // // for (Tree t : ctree.getImplementsClause()) { // if (t == typePath.getLeaf()) { // isImplements = true; // break; // } // } if ((isExtends && pref.getBoolean(MarkOccurencesSettings.OVERRIDES, true)) || (isImplements && pref.getBoolean(MarkOccurencesSettings.IMPLEMENTS, true))) { Element superType = info.getTrees().getElement(typePath); Element thisType = info.getTrees().getElement(typePath.getParentPath()); if (isClass(superType) && isClass(thisType)) return detectMethodsForClass(info, doc, typePath.getParentPath(), (TypeElement) superType, (TypeElement) thisType); } } if (isCancelled()) return null; TokenSequence<JFXTokenId> ts = info.getTokenHierarchy().tokenSequence(JFXTokenId.language()); if (ts != null && tp.getLeaf().getJavaFXKind() == JavaFXKind.CLASS_DECLARATION) { int bodyStart = Utilities.findBodyStart(tp.getLeaf(), cu, info.getTrees().getSourcePositions(), doc); if (caretPosition < bodyStart) { ts.move(caretPosition); if (ts.moveNext()) { if (pref.getBoolean(MarkOccurencesSettings.OVERRIDES, true) && ts.token().id() == JFXTokenId.EXTENDS) { // Tree superClass = ((ClassTree) tp.getLeaf()).getExtendsClause(); Tree superClass = typePath.getParentPath() != null ? (JFXClassDeclaration) typePath.getParentPath().getLeaf() : null; if (superClass != null) { Element superType = info.getTrees().getElement(new JavaFXTreePath(tp, superClass)); Element thisType = info.getTrees().getElement(tp); if (isClass(superType) && isClass(thisType)) return detectMethodsForClass(info, doc, tp, (TypeElement) superType, (TypeElement) thisType); } } // if (pref.getBoolean(MarkOccurencesSettings.IMPLEMENTS, true) && ts.token().id() == JFXTokenId.IMPLEMENTS) { // List<? extends Tree> superClasses = ((ClassTree) tp.getLeaf()).getImplementsClause(); // // if (superClasses != null) { // List<TypeElement> superTypes = new ArrayList<TypeElement>(); // // for (Tree superTypeTree : superClasses) { // if (superTypeTree != null) { // Element superType = info.getTrees().getElement(new JavaFXTreePath(tp, superTypeTree)); // // if (isClass(superType)) // superTypes.add((TypeElement) superType); // } // } // // Element thisType = info.getTrees().getElement(tp); // // if (!superTypes.isEmpty() && isClass(thisType)) // return detectMethodsForClass(info, doc, tp, superTypes, (TypeElement) thisType); // } // // } } } } } if (isCancelled()) { return null; } Tree tree = tp.getLeaf(); if (pref.getBoolean(MarkOccurencesSettings.BREAK_CONTINUE, true) && (tree.getJavaFXKind() == JavaFXKind.BREAK || tree.getJavaFXKind() == JavaFXKind.CONTINUE)) { return detectBreakOrContinueTarget(info, doc, tp); } if (isCancelled()) { return null; } // TODO inside javadoc // variable declaration Element el = info.getTrees().getElement(tp); if (el != null && !Utilities.isKeyword(tree) && isEnabled(pref, el) && (tree.getJavaFXKind() != JavaFXKind.CLASS_DECLARATION || isIn(caretPosition, Utilities.findIdentifierSpan(info, doc, tp))) && (tree.getJavaFXKind() != JavaFXKind.FUNCTION_DEFINITION || isIn(caretPosition, Utilities.findIdentifierSpan(info, doc, tp)))) { FindLocalUsagesQuery fluq = new FindLocalUsagesQuery(); setLocalUsages(fluq); try { List<int[]> bag = new ArrayList<int[]>(); for (Token<?> t : fluq.findUsages(el, info, doc)) { bag.add(new int[]{t.offset(null), t.offset(null) + t.length()}); } return bag; } finally { setLocalUsages(null); } } return null; }
diff --git a/src/com/ianhanniballake/recipebook/ui/RecipeDetailActivity.java b/src/com/ianhanniballake/recipebook/ui/RecipeDetailActivity.java index f0495b0..aa69a7b 100644 --- a/src/com/ianhanniballake/recipebook/ui/RecipeDetailActivity.java +++ b/src/com/ianhanniballake/recipebook/ui/RecipeDetailActivity.java @@ -1,215 +1,218 @@ package com.ianhanniballake.recipebook.ui; import java.util.Locale; import android.app.ActionBar; import android.app.FragmentTransaction; import android.content.AsyncQueryHandler; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.NavUtils; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.ianhanniballake.recipebook.R; import com.ianhanniballake.recipebook.auth.AuthorizedActivity; import com.ianhanniballake.recipebook.provider.RecipeContract; /** * An activity representing a single Recipe detail screen. This activity is only used on handset devices. On tablet-size * devices, item details are presented side-by-side with a list of items in a {@link RecipeListActivity}. */ public class RecipeDetailActivity extends AuthorizedActivity { /** * A {@link FragmentPagerAdapter} that returns a fragment corresponding to one of the sections/tabs/pages. We use a * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will keep every loaded fragment in memory. * If this becomes too memory intensive, it may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ public static class RecipeDetailTabsAdapter extends FragmentPagerAdapter implements ActionBar.TabListener, ViewPager.OnPageChangeListener { private final ActionBar actionBar; private final Context context; private final ViewPager pager; /** * Manages the set of static tabs * * @param activity * Activity showing these swipeable tabs * @param pager * Pager displaying the tabs */ public RecipeDetailTabsAdapter(final FragmentActivity activity, final ViewPager pager) { super(activity.getSupportFragmentManager()); context = activity; actionBar = activity.getActionBar(); this.pager = pager; } @Override public int getCount() { // Show 3 total pages. return 3; } @Override public Fragment getItem(final int position) { switch (position) { case 0: return new RecipeDetailSummaryFragment(); case 1: return new RecipeDetailIngredientFragment(); case 2: return new RecipeDetailInstructionFragment(); default: return null; } } @Override public CharSequence getPageTitle(final int position) { final Locale l = Locale.getDefault(); switch (position) { case 0: return context.getString(R.string.title_summary).toUpperCase(l); case 1: return context.getString(R.string.title_ingredient_list).toUpperCase(l); case 2: return context.getString(R.string.title_instruction_list).toUpperCase(l); default: return null; } } @Override public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) { // Nothing to do } @Override public void onPageScrollStateChanged(final int state) { // Nothing to do } @Override public void onPageSelected(final int position) { actionBar.setSelectedNavigationItem(position); } @Override public void onTabReselected(final ActionBar.Tab tab, final FragmentTransaction fragmentTransaction) { // Nothing to do } @Override public void onTabSelected(final ActionBar.Tab tab, final FragmentTransaction fragmentTransaction) { // When the given tab is selected, switch to the corresponding page in the ViewPager. pager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(final ActionBar.Tab tab, final FragmentTransaction fragmentTransaction) { // Nothing to do } /** * Ties the pager and tabs together */ public void setup() { pager.setAdapter(this); pager.setOnPageChangeListener(this); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // For each of the sections in the app, add a tab to the action bar. for (int i = 0; i < getCount(); i++) actionBar.addTab(actionBar.newTab().setText(getPageTitle(i)).setTabListener(this)); } } private AsyncQueryHandler recipeDeleteHandler; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_detail); // Query for the recipe's title new AsyncQueryHandler(getContentResolver()) { @Override protected void onQueryComplete(final int token, final Object cookie, final Cursor cursor) { - final int titleColumnIndex = cursor.getColumnIndex(RecipeContract.Recipes.COLUMN_NAME_TITLE); - setTitle(cursor.getString(titleColumnIndex)); + if (cursor.moveToFirst()) + { + final int titleColumnIndex = cursor.getColumnIndex(RecipeContract.Recipes.COLUMN_NAME_TITLE); + setTitle(cursor.getString(titleColumnIndex)); + } } }.startQuery(0, 0, getIntent().getData(), new String[] { RecipeContract.Recipes.COLUMN_NAME_TITLE }, null, null, null); // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); final ViewPager pager = (ViewPager) findViewById(R.id.pager); // Create the adapter that will return a fragment for each of the three tabs final RecipeDetailTabsAdapter tabsAdapter = new RecipeDetailTabsAdapter(this, pager); tabsAdapter.setup(); recipeDeleteHandler = new AsyncQueryHandler(getContentResolver()) { @Override protected void onDeleteComplete(final int token, final Object cookie, final int result) { Toast.makeText(RecipeDetailActivity.this, R.string.deleted, Toast.LENGTH_SHORT).show(); finish(); } }; } @Override public boolean onCreateOptionsMenu(final Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.recipe_detail, menu); return true; } @Override public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this activity, the Up button is shown. Use // NavUtils to allow users to navigate up one level in the application structure. NavUtils.navigateUpTo(this, new Intent(this, RecipeListActivity.class)); return true; case R.id.edit: final Intent editIntent = new Intent(Intent.ACTION_EDIT, getIntent().getData()); startActivity(editIntent); return true; case R.id.delete: recipeDeleteHandler.startDelete(0, null, getIntent().getData(), null, null); return true; default: return super.onOptionsItemSelected(item); } } }
true
true
protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_detail); // Query for the recipe's title new AsyncQueryHandler(getContentResolver()) { @Override protected void onQueryComplete(final int token, final Object cookie, final Cursor cursor) { final int titleColumnIndex = cursor.getColumnIndex(RecipeContract.Recipes.COLUMN_NAME_TITLE); setTitle(cursor.getString(titleColumnIndex)); } }.startQuery(0, 0, getIntent().getData(), new String[] { RecipeContract.Recipes.COLUMN_NAME_TITLE }, null, null, null); // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); final ViewPager pager = (ViewPager) findViewById(R.id.pager); // Create the adapter that will return a fragment for each of the three tabs final RecipeDetailTabsAdapter tabsAdapter = new RecipeDetailTabsAdapter(this, pager); tabsAdapter.setup(); recipeDeleteHandler = new AsyncQueryHandler(getContentResolver()) { @Override protected void onDeleteComplete(final int token, final Object cookie, final int result) { Toast.makeText(RecipeDetailActivity.this, R.string.deleted, Toast.LENGTH_SHORT).show(); finish(); } }; }
protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recipe_detail); // Query for the recipe's title new AsyncQueryHandler(getContentResolver()) { @Override protected void onQueryComplete(final int token, final Object cookie, final Cursor cursor) { if (cursor.moveToFirst()) { final int titleColumnIndex = cursor.getColumnIndex(RecipeContract.Recipes.COLUMN_NAME_TITLE); setTitle(cursor.getString(titleColumnIndex)); } } }.startQuery(0, 0, getIntent().getData(), new String[] { RecipeContract.Recipes.COLUMN_NAME_TITLE }, null, null, null); // Show the Up button in the action bar. getActionBar().setDisplayHomeAsUpEnabled(true); final ViewPager pager = (ViewPager) findViewById(R.id.pager); // Create the adapter that will return a fragment for each of the three tabs final RecipeDetailTabsAdapter tabsAdapter = new RecipeDetailTabsAdapter(this, pager); tabsAdapter.setup(); recipeDeleteHandler = new AsyncQueryHandler(getContentResolver()) { @Override protected void onDeleteComplete(final int token, final Object cookie, final int result) { Toast.makeText(RecipeDetailActivity.this, R.string.deleted, Toast.LENGTH_SHORT).show(); finish(); } }; }
diff --git a/src/main/java/com/github/rnewson/couchdb/lucene/rhino/RhinoDocument.java b/src/main/java/com/github/rnewson/couchdb/lucene/rhino/RhinoDocument.java index 2009e61..c0583c1 100644 --- a/src/main/java/com/github/rnewson/couchdb/lucene/rhino/RhinoDocument.java +++ b/src/main/java/com/github/rnewson/couchdb/lucene/rhino/RhinoDocument.java @@ -1,184 +1,185 @@ package com.github.rnewson.couchdb.lucene.rhino; /** * Copyright 2009 Robert Newson, Paul Davis * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.lucene.document.Document; import org.apache.lucene.queryParser.ParseException; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.NativeObject; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.Undefined; import com.github.rnewson.couchdb.lucene.Tika; import com.github.rnewson.couchdb.lucene.couchdb.Database; import com.github.rnewson.couchdb.lucene.couchdb.FieldType; import com.github.rnewson.couchdb.lucene.couchdb.ViewSettings; import com.github.rnewson.couchdb.lucene.util.Utils; /** * Collect data from the user. * * @author rnewson * */ public final class RhinoDocument extends ScriptableObject { private static class RhinoAttachment { private String attachmentName; private String fieldName; } private static class RhinoField { private NativeObject settings; private Object value; } private static final long serialVersionUID = 1L; public static Scriptable jsConstructor(final Context cx, final Object[] args, final Function ctorObj, final boolean inNewExpr) { final RhinoDocument doc = new RhinoDocument(); if (args.length >= 2) { jsFunction_add(cx, doc, args, ctorObj); } return doc; } public static void jsFunction_add(final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj) { final RhinoDocument doc = checkInstance(thisObj); if (args.length < 1 || args.length > 2) { throw Context.reportRuntimeError("Invalid number of arguments."); } if (args[0] == null) { - throw Context.reportRuntimeError("first argument must be non-null."); + // Ignore. + return; } if (args[0] instanceof Undefined) { // Ignore return; } final String className = args[0].getClass().getName(); if (className.equals("org.mozilla.javascript.NativeDate")) { args[0] = (Date) Context.jsToJava(args[0], Date.class); } if (!className.startsWith("java.lang.") && !className.equals("org.mozilla.javascript.NativeObject") && !className.equals("org.mozilla.javascript.NativeDate")) { throw Context.reportRuntimeError(className + " is not supported."); } if (args.length == 2 && (args[1] == null || args[1] instanceof NativeObject == false)) { throw Context.reportRuntimeError("second argument must be an object."); } final RhinoField field = new RhinoField(); field.value = args[0]; if (args.length == 2) { field.settings = (NativeObject) args[1]; } doc.fields.add(field); } public static void jsFunction_attachment(final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj) throws IOException { final RhinoDocument doc = checkInstance(thisObj); if (args.length < 2) { throw Context.reportRuntimeError("Invalid number of arguments."); } final RhinoAttachment attachment = new RhinoAttachment(); attachment.fieldName = args[0].toString(); attachment.attachmentName = args[1].toString(); doc.attachments.add(attachment); } private static RhinoDocument checkInstance(final Scriptable obj) { if (obj == null || !(obj instanceof RhinoDocument)) { throw Context.reportRuntimeError("called on incompatible object."); } return (RhinoDocument) obj; } private final List<RhinoAttachment> attachments = new ArrayList<RhinoAttachment>(); private final List<RhinoField> fields = new ArrayList<RhinoField>(); public RhinoDocument() { } public Document toDocument(final String id, final ViewSettings defaults, final Database database) throws IOException, ParseException { final Document result = new Document(); // Add id. result.add(Utils.token("_id", id, true)); // Add user-supplied fields. for (final RhinoField field : fields) { addField(field, defaults, result); } // Parse user-requested attachments. for (final RhinoAttachment attachment : attachments) { addAttachment(attachment, id, database, result); } return result; } @Override public String getClassName() { return "Document"; } private void addAttachment(final RhinoAttachment attachment, final String id, final Database database, final Document out) throws IOException { final ResponseHandler<Void> handler = new ResponseHandler<Void>() { public Void handleResponse(final HttpResponse response) throws ClientProtocolException, IOException { final HttpEntity entity = response.getEntity(); Tika.INSTANCE.parse(entity.getContent(), entity.getContentType().getValue(), attachment.fieldName, out); return null; } }; database.handleAttachment(id, attachment.attachmentName, handler); } private void addField(final RhinoField field, final ViewSettings defaults, final Document out) throws ParseException { final ViewSettings settings = new ViewSettings(field.settings, defaults); final FieldType type = settings.getFieldType(); out.add(type.toField(settings.getField(), field.value, settings)); } }
true
true
public static void jsFunction_add(final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj) { final RhinoDocument doc = checkInstance(thisObj); if (args.length < 1 || args.length > 2) { throw Context.reportRuntimeError("Invalid number of arguments."); } if (args[0] == null) { throw Context.reportRuntimeError("first argument must be non-null."); } if (args[0] instanceof Undefined) { // Ignore return; } final String className = args[0].getClass().getName(); if (className.equals("org.mozilla.javascript.NativeDate")) { args[0] = (Date) Context.jsToJava(args[0], Date.class); } if (!className.startsWith("java.lang.") && !className.equals("org.mozilla.javascript.NativeObject") && !className.equals("org.mozilla.javascript.NativeDate")) { throw Context.reportRuntimeError(className + " is not supported."); } if (args.length == 2 && (args[1] == null || args[1] instanceof NativeObject == false)) { throw Context.reportRuntimeError("second argument must be an object."); } final RhinoField field = new RhinoField(); field.value = args[0]; if (args.length == 2) { field.settings = (NativeObject) args[1]; } doc.fields.add(field); }
public static void jsFunction_add(final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj) { final RhinoDocument doc = checkInstance(thisObj); if (args.length < 1 || args.length > 2) { throw Context.reportRuntimeError("Invalid number of arguments."); } if (args[0] == null) { // Ignore. return; } if (args[0] instanceof Undefined) { // Ignore return; } final String className = args[0].getClass().getName(); if (className.equals("org.mozilla.javascript.NativeDate")) { args[0] = (Date) Context.jsToJava(args[0], Date.class); } if (!className.startsWith("java.lang.") && !className.equals("org.mozilla.javascript.NativeObject") && !className.equals("org.mozilla.javascript.NativeDate")) { throw Context.reportRuntimeError(className + " is not supported."); } if (args.length == 2 && (args[1] == null || args[1] instanceof NativeObject == false)) { throw Context.reportRuntimeError("second argument must be an object."); } final RhinoField field = new RhinoField(); field.value = args[0]; if (args.length == 2) { field.settings = (NativeObject) args[1]; } doc.fields.add(field); }
diff --git a/src/di/kdd/smartmonitor/protocol/BroadcastAsyncTask.java b/src/di/kdd/smartmonitor/protocol/BroadcastAsyncTask.java index d7a6604..9ea26f9 100644 --- a/src/di/kdd/smartmonitor/protocol/BroadcastAsyncTask.java +++ b/src/di/kdd/smartmonitor/protocol/BroadcastAsyncTask.java @@ -1,38 +1,39 @@ package di.kdd.smartmonitor.protocol; import android.os.AsyncTask; import android.util.Log; import java.io.IOException; import java.net.Socket; import java.util.List; public class BroadcastAsyncTask extends AsyncTask<Void, Void, Void> { private List<Socket> sockets; private Message message; private static final String TAG = "broadcast task"; public BroadcastAsyncTask(List<Socket> sockets, Message message) { this.sockets = sockets; this.message = message; } @Override protected Void doInBackground(Void... arg0) { for(Socket peer : sockets) { try { DistributedSystemNode.send(peer, message); } catch(IOException e) { - Log.i(TAG, "Failed to broadcast at node " + e.getMessage()); + Log.i(TAG, "Failed to broadcast at node"); + e.printStackTrace(); } } return null; } }
true
true
protected Void doInBackground(Void... arg0) { for(Socket peer : sockets) { try { DistributedSystemNode.send(peer, message); } catch(IOException e) { Log.i(TAG, "Failed to broadcast at node " + e.getMessage()); } } return null; }
protected Void doInBackground(Void... arg0) { for(Socket peer : sockets) { try { DistributedSystemNode.send(peer, message); } catch(IOException e) { Log.i(TAG, "Failed to broadcast at node"); e.printStackTrace(); } } return null; }
diff --git a/java/src/com/android/inputmethod/deprecated/languageswitcher/LanguageSwitcher.java b/java/src/com/android/inputmethod/deprecated/languageswitcher/LanguageSwitcher.java index e4b2e035..1a606eaa 100644 --- a/java/src/com/android/inputmethod/deprecated/languageswitcher/LanguageSwitcher.java +++ b/java/src/com/android/inputmethod/deprecated/languageswitcher/LanguageSwitcher.java @@ -1,236 +1,237 @@ /* * Copyright (C) 2010 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.android.inputmethod.deprecated.languageswitcher; import com.android.inputmethod.compat.InputMethodSubtypeCompatWrapper; import com.android.inputmethod.latin.LatinIME; import com.android.inputmethod.latin.LatinImeLogger; import com.android.inputmethod.latin.Settings; import com.android.inputmethod.latin.SharedPreferencesCompat; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.text.TextUtils; import android.util.Log; import java.util.ArrayList; import java.util.Locale; /** * Keeps track of list of selected input languages and the current * input language that the user has selected. */ public class LanguageSwitcher { private static final String TAG = LanguageSwitcher.class.getSimpleName(); private static final String KEYBOARD_MODE = "keyboard"; private static final String[] EMPTY_STIRNG_ARRAY = new String[0]; private final ArrayList<Locale> mLocales = new ArrayList<Locale>(); private final LatinIME mIme; private String[] mSelectedLanguageArray = EMPTY_STIRNG_ARRAY; private String mSelectedLanguages; private int mCurrentIndex = 0; private String mDefaultInputLanguage; private Locale mDefaultInputLocale; private Locale mSystemLocale; public LanguageSwitcher(LatinIME ime) { mIme = ime; } public int getLocaleCount() { return mLocales.size(); } public void onConfigurationChanged(Configuration conf, SharedPreferences prefs) { final Locale newLocale = conf.locale; if (!getSystemLocale().toString().equals(newLocale.toString())) { loadLocales(prefs, newLocale); } } /** * Loads the currently selected input languages from shared preferences. * @param sp shared preference for getting the current input language and enabled languages * @param systemLocale the current system locale, stored for changing the current input language * based on the system current system locale. * @return whether there was any change */ public boolean loadLocales(SharedPreferences sp, Locale systemLocale) { if (LatinImeLogger.sDBG) { Log.d(TAG, "load locales"); } if (systemLocale != null) { setSystemLocale(systemLocale); } String selectedLanguages = sp.getString(Settings.PREF_SELECTED_LANGUAGES, null); String currentLanguage = sp.getString(Settings.PREF_INPUT_LANGUAGE, null); if (TextUtils.isEmpty(selectedLanguages)) { mSelectedLanguageArray = EMPTY_STIRNG_ARRAY; + mSelectedLanguages = null; loadDefaults(); if (mLocales.size() == 0) { return false; } mLocales.clear(); return true; } if (selectedLanguages.equals(mSelectedLanguages)) { return false; } mSelectedLanguageArray = selectedLanguages.split(","); mSelectedLanguages = selectedLanguages; // Cache it for comparison later constructLocales(); mCurrentIndex = 0; if (currentLanguage != null) { // Find the index mCurrentIndex = 0; for (int i = 0; i < mLocales.size(); i++) { if (mSelectedLanguageArray[i].equals(currentLanguage)) { mCurrentIndex = i; break; } } // If we didn't find the index, use the first one } return true; } private void loadDefaults() { if (LatinImeLogger.sDBG) { Log.d(TAG, "load default locales:"); } mDefaultInputLocale = mIme.getResources().getConfiguration().locale; String country = mDefaultInputLocale.getCountry(); mDefaultInputLanguage = mDefaultInputLocale.getLanguage() + (TextUtils.isEmpty(country) ? "" : "_" + country); } private void constructLocales() { mLocales.clear(); for (final String lang : mSelectedLanguageArray) { final Locale locale = new Locale(lang.substring(0, 2), lang.length() > 4 ? lang.substring(3, 5) : ""); mLocales.add(locale); } } /** * Returns the currently selected input language code, or the display language code if * no specific locale was selected for input. */ public String getInputLanguage() { if (getLocaleCount() == 0) return mDefaultInputLanguage; return mSelectedLanguageArray[mCurrentIndex]; } /** * Returns the list of enabled language codes. */ public String[] getEnabledLanguages(boolean allowImplicitlySelectedLanguages) { if (mSelectedLanguageArray.length == 0 && allowImplicitlySelectedLanguages) { return new String[] { mDefaultInputLanguage }; } return mSelectedLanguageArray; } /** * Returns the currently selected input locale, or the display locale if no specific * locale was selected for input. * @return */ public Locale getInputLocale() { if (getLocaleCount() == 0) return mDefaultInputLocale; return mLocales.get(mCurrentIndex); } private int nextLocaleIndex() { final int size = mLocales.size(); return (mCurrentIndex + 1) % size; } private int prevLocaleIndex() { final int size = mLocales.size(); return (mCurrentIndex - 1 + size) % size; } /** * Returns the next input locale in the list. Wraps around to the beginning of the * list if we're at the end of the list. * @return */ public Locale getNextInputLocale() { if (getLocaleCount() == 0) return mDefaultInputLocale; return mLocales.get(nextLocaleIndex()); } /** * Sets the system locale (display UI) used for comparing with the input language. * @param locale the locale of the system */ private void setSystemLocale(Locale locale) { mSystemLocale = locale; } /** * Returns the system locale. * @return the system locale */ private Locale getSystemLocale() { return mSystemLocale; } /** * Returns the previous input locale in the list. Wraps around to the end of the * list if we're at the beginning of the list. * @return */ public Locale getPrevInputLocale() { if (getLocaleCount() == 0) return mDefaultInputLocale; return mLocales.get(prevLocaleIndex()); } public void reset() { mCurrentIndex = 0; } public void next() { mCurrentIndex = nextLocaleIndex(); } public void prev() { mCurrentIndex = prevLocaleIndex(); } public void setLocale(String localeStr) { final int N = mLocales.size(); for (int i = 0; i < N; ++i) { if (mLocales.get(i).toString().equals(localeStr)) { mCurrentIndex = i; } } } public void persist(SharedPreferences prefs) { Editor editor = prefs.edit(); editor.putString(Settings.PREF_INPUT_LANGUAGE, getInputLanguage()); SharedPreferencesCompat.apply(editor); } }
true
true
public boolean loadLocales(SharedPreferences sp, Locale systemLocale) { if (LatinImeLogger.sDBG) { Log.d(TAG, "load locales"); } if (systemLocale != null) { setSystemLocale(systemLocale); } String selectedLanguages = sp.getString(Settings.PREF_SELECTED_LANGUAGES, null); String currentLanguage = sp.getString(Settings.PREF_INPUT_LANGUAGE, null); if (TextUtils.isEmpty(selectedLanguages)) { mSelectedLanguageArray = EMPTY_STIRNG_ARRAY; loadDefaults(); if (mLocales.size() == 0) { return false; } mLocales.clear(); return true; } if (selectedLanguages.equals(mSelectedLanguages)) { return false; } mSelectedLanguageArray = selectedLanguages.split(","); mSelectedLanguages = selectedLanguages; // Cache it for comparison later constructLocales(); mCurrentIndex = 0; if (currentLanguage != null) { // Find the index mCurrentIndex = 0; for (int i = 0; i < mLocales.size(); i++) { if (mSelectedLanguageArray[i].equals(currentLanguage)) { mCurrentIndex = i; break; } } // If we didn't find the index, use the first one } return true; }
public boolean loadLocales(SharedPreferences sp, Locale systemLocale) { if (LatinImeLogger.sDBG) { Log.d(TAG, "load locales"); } if (systemLocale != null) { setSystemLocale(systemLocale); } String selectedLanguages = sp.getString(Settings.PREF_SELECTED_LANGUAGES, null); String currentLanguage = sp.getString(Settings.PREF_INPUT_LANGUAGE, null); if (TextUtils.isEmpty(selectedLanguages)) { mSelectedLanguageArray = EMPTY_STIRNG_ARRAY; mSelectedLanguages = null; loadDefaults(); if (mLocales.size() == 0) { return false; } mLocales.clear(); return true; } if (selectedLanguages.equals(mSelectedLanguages)) { return false; } mSelectedLanguageArray = selectedLanguages.split(","); mSelectedLanguages = selectedLanguages; // Cache it for comparison later constructLocales(); mCurrentIndex = 0; if (currentLanguage != null) { // Find the index mCurrentIndex = 0; for (int i = 0; i < mLocales.size(); i++) { if (mSelectedLanguageArray[i].equals(currentLanguage)) { mCurrentIndex = i; break; } } // If we didn't find the index, use the first one } return true; }
diff --git a/melete-impl/src/java/org/sakaiproject/component/app/melete/MeleteCHServiceImpl.java b/melete-impl/src/java/org/sakaiproject/component/app/melete/MeleteCHServiceImpl.java index 3fe1e0da..c9cd869e 100644 --- a/melete-impl/src/java/org/sakaiproject/component/app/melete/MeleteCHServiceImpl.java +++ b/melete-impl/src/java/org/sakaiproject/component/app/melete/MeleteCHServiceImpl.java @@ -1,1349 +1,1347 @@ /********************************************************************************** * * $Header: * *********************************************************************************** * * Copyright (c) 2004, 2005, 2006, 2007 Foothill College, ETUDES 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 org.sakaiproject.component.app.melete; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.net.URLDecoder; import org.sakaiproject.api.app.melete.MeleteCHService; import org.sakaiproject.api.app.melete.MeleteSecurityService; import org.sakaiproject.component.app.melete.MeleteUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.api.app.melete.exception.MeleteException; import org.sakaiproject.content.api.ContentCollectionEdit; import org.sakaiproject.content.api.ContentCollection; import org.sakaiproject.content.api.ContentResource; import org.sakaiproject.content.api.ContentResourceEdit; import org.sakaiproject.content.api.ContentHostingService; import org.sakaiproject.content.api.ContentEntity; import org.sakaiproject.content.cover.ContentTypeImageService; import org.sakaiproject.entity.api.Entity; import org.sakaiproject.entity.api.ResourceProperties; import org.sakaiproject.entity.api.ResourcePropertiesEdit; import org.sakaiproject.exception.IdInvalidException; import org.sakaiproject.exception.IdLengthException; import org.sakaiproject.exception.IdUniquenessException; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.exception.InUseException; import org.sakaiproject.exception.IdUsedException; import org.sakaiproject.exception.TypeException; import org.sakaiproject.exception.InconsistentException; import org.sakaiproject.exception.OverQuotaException; import org.sakaiproject.exception.PermissionException; import org.sakaiproject.exception.ServerOverloadException; import org.sakaiproject.tool.cover.ToolManager; import org.sakaiproject.component.cover.ServerConfigurationService; import org.sakaiproject.entity.cover.EntityManager; import org.sakaiproject.entity.api.Reference; /* * Created on Sep 18, 2006 by rashmi * * This is a basic class to do all content hosting service work through melete * Rashmi - 12/8/06 - add checks for upload img being greater than 1Mb * Rashmi - 12/16/06 - fck editor upload image goes to melete collection and not resources. * Rashmi - 1/16/07 - remove word inserted comments * Mallika - 1/29/06 - Needed to add some new code to add url for embedded images * Rashmi - changed logic to get list of images and url * Rashmi - 2/12/07 - add alternate reference property at collection level too * Rashmi - 3/6/07 - revised display name of modules collection with no slashes * Rashmi - 5/9/07 - revised iteration to get listoflinks * Mallika - 5/31/07 - added Validator * Mallika - 6/4/07 - Added two new methods (copyIntoFolder,getCollection) * Mallika - 6/4/07 - Added logic to check for resource in findlocal */ public class MeleteCHServiceImpl implements MeleteCHService { /** Dependency: The logging service. */ public Log logger = LogFactory.getLog(MeleteCHServiceImpl.class); private ContentHostingService contentservice; private static final int MAXIMUM_ATTEMPTS_FOR_UNIQUENESS = 100; private SectionDB sectiondb; /** Dependency: The Melete Security service. */ private MeleteSecurityService meleteSecurityService; protected MeleteUtil meleteUtil = new MeleteUtil(); /** This string starts the references to resources in this service. */ static final String REFERENCE_ROOT = Entity.SEPARATOR+"meleteDocs"; /** * Check if the current user has permission as author. * @return true if the current user has permission to perform this action, false if not. */ public boolean isUserAuthor()throws Exception{ try { return meleteSecurityService.allowAuthor(); } catch (Exception e) { throw e; } } public boolean isUserStudent()throws Exception{ try { return meleteSecurityService.allowStudent(); } catch (Exception e) { throw e; } } private String addMeleteRootCollection(String rootCollectionRef, String collectionName, String description) { try { // Check to see if meleteDocs exists ContentCollection collection = getContentservice().getCollection(rootCollectionRef); return collection.getId(); } catch (IdUnusedException e) { //if not, create it if (logger.isDebugEnabled()) logger.debug("creating melete root collection "+rootCollectionRef); ContentCollectionEdit edit = null; try { edit = getContentservice().addCollection(rootCollectionRef); ResourcePropertiesEdit props = edit.getPropertiesEdit(); props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, collectionName); props.addProperty(ResourceProperties.PROP_DESCRIPTION, description); props.addProperty(getContentservice().PROP_ALTERNATE_REFERENCE, REFERENCE_ROOT); getContentservice().commitCollection(edit); return edit.getId(); } catch (Exception e2) { if(edit != null) getContentservice().cancelCollection(edit); logger.warn("creating melete root collection: " + e2.toString()); } } catch (Exception e) { logger.warn("checking melete root collection: " + e.toString()); } return null; } /* * */ public String addCollectionToMeleteCollection(String meleteItemColl,String CollName) { try { if (!isUserAuthor()) { logger.info("User is not authorized to access meleteDocs collection"); } // setup a security advisor meleteSecurityService.pushAdvisor(); try { // check if the root collection is available String rootCollectionRef = Entity.SEPARATOR+"private"+ REFERENCE_ROOT+ Entity.SEPARATOR; //Check to see if meleteDocs exists String rootMeleteCollId = addMeleteRootCollection(rootCollectionRef, "meleteDocs", "root collection"); // now sub collection for course String meleteItemDirCollId = rootMeleteCollId + meleteItemColl+ Entity.SEPARATOR; String subMeleteCollId = addMeleteRootCollection(meleteItemDirCollId, CollName, "module collection"); return subMeleteCollId; } catch(Exception ex) { logger.error("error while creating modules collection" + ex.toString()); } } catch (Throwable t) { logger.warn("init(): ", t); } finally { // clear the security advisor meleteSecurityService.popAdvisor(); } return null; } /* * */ public String getCollectionId( String contentType,Integer modId ) { String addToCollection =""; String collName =""; if(contentType.equals("typeEditor")){ addToCollection=ToolManager.getCurrentPlacement().getContext()+Entity.SEPARATOR+"module_"+ modId; collName = "module_"+ modId; } else { if (ToolManager.getCurrentPlacement()!=null) addToCollection=ToolManager.getCurrentPlacement().getContext()+Entity.SEPARATOR+"uploads"; else addToCollection=getMeleteSecurityService().getMeleteImportService().getDestinationContext()+Entity.SEPARATOR+"uploads"; collName = "uploads"; } // check if collection exists otherwise create it String addCollId = addCollectionToMeleteCollection(addToCollection,collName); return addCollId; } /* * */ public String getUploadCollectionId() { try{ String uploadCollectionId; uploadCollectionId=ToolManager.getCurrentPlacement().getContext()+Entity.SEPARATOR+"uploads"; String collName = "uploads"; // check if collection exists //read meletDocs dir name from web.xml String uploadCollId = addCollectionToMeleteCollection(uploadCollectionId, collName); return uploadCollId; }catch(Exception e) { logger.error("error accessing uploads directory"); return null; } } //Methods used by Migrate program - beginning public String getCollectionId(String courseId, String contentType,Integer modId ) { String addToCollection =""; String collName =""; if(contentType.equals("typeEditor")){ addToCollection=courseId+Entity.SEPARATOR+"module_"+ modId; collName = "module_"+ modId; } else { addToCollection=courseId+Entity.SEPARATOR+"uploads"; collName = "uploads"; } // check if collection exists otherwise create it String addCollId = addCollectionToMeleteCollection(addToCollection,collName); return addCollId; } public String getUploadCollectionId(String courseId) { try{ String uploadCollectionId=courseId+Entity.SEPARATOR+"uploads"; String collName = "uploads"; // check if collection exists //read meletDocs dir name from web.xml String uploadCollId = addCollectionToMeleteCollection(uploadCollectionId, collName); return uploadCollId; }catch(Exception e) { logger.error("error accessing uploads directory"); return null; } } // Methods used by Migrate program - End /* * for remote browser listing for sferyx editor just get the image files **/ public List getListofImagesFromCollection(String collId) { try { // setup a security advisor meleteSecurityService.pushAdvisor(); long starttime = System.currentTimeMillis(); logger.debug("time to get all collectionMap" + starttime); ContentCollection c = getContentservice().getCollection(collId); List mem = c.getMemberResources(); if (mem == null) return null; ListIterator memIt = mem.listIterator(); while (memIt != null && memIt.hasNext()) { ContentEntity ce = (ContentEntity) memIt.next(); if (ce.isResource()) { String contentextension = ((ContentResource) ce).getProperties().getProperty(ce.getProperties().getNamePropContentType()); if (!contentextension.startsWith("image")) { memIt.remove(); } } else memIt.remove(); } long endtime = System.currentTimeMillis(); logger.debug("end time to get all collectionMap" + (endtime - starttime)); return mem; } catch (Exception e) { logger.error(e.toString()); } finally { // clear the security advisor meleteSecurityService.popAdvisor(); } return null; } public List getListofFilesFromCollection(String collId) { try { // setup a security advisor meleteSecurityService.pushAdvisor(); long starttime = System.currentTimeMillis(); logger.debug("time to get all collectionMap" + starttime); ContentCollection c= getContentservice().getCollection(collId); List mem = c.getMemberResources(); if (mem == null) return null; ListIterator memIt = mem.listIterator(); while(memIt !=null && memIt.hasNext()) { ContentEntity ce = (ContentEntity)memIt.next(); if (ce.isResource()) { String contentextension = ((ContentResource)ce).getContentType(); if(contentextension.equals(MIME_TYPE_LINK) || contentextension.equals(MIME_TYPE_EDITOR)) { memIt.remove(); } } else memIt.remove(); } long endtime = System.currentTimeMillis(); logger.debug("end time to get all collectionMap" + (endtime - starttime)); return mem; } catch(Exception e) { logger.error(e.toString()); } finally { // clear the security advisor meleteSecurityService.popAdvisor(); } return null; } /* * for remote link browser listing for sferyx editor * just get the urls and links and not image files */ public List getListofLinksFromCollection(String collId) { try { if (!isUserAuthor()) { logger.info("User is not authorized to access meleteDocs collection"); } // setup a security advisor meleteSecurityService.pushAdvisor(); ContentCollection c= getContentservice().getCollection(collId); List mem = c.getMemberResources(); if (mem == null) return null; ListIterator memIt = mem.listIterator(); while(memIt !=null && memIt.hasNext()) { ContentEntity ce = (ContentEntity)memIt.next(); if (ce.isResource()) { String contentextension = ((ContentResource)ce).getContentType(); if(!contentextension.equals(MIME_TYPE_LINK)) memIt.remove(); }else memIt.remove(); } return mem; } catch(Exception e) { logger.error(e.toString()); } finally { // clear the security advisor meleteSecurityService.popAdvisor(); } return null; } public List getListofMediaFromCollection(String collId) { try { if (!isUserAuthor()) { logger.info("User is not authorized to access meleteDocs collection"); } // setup a security advisor meleteSecurityService.pushAdvisor(); ContentCollection c= getContentservice().getCollection(collId); List mem = c.getMemberResources(); if (mem == null) return null; ListIterator memIt = mem.listIterator(); while(memIt !=null && memIt.hasNext()) { ContentEntity ce = (ContentEntity)memIt.next(); if (ce.isResource()) { String contentextension = ((ContentResource)ce).getContentType(); if(contentextension.equals(MIME_TYPE_EDITOR)) memIt.remove(); }else memIt.remove(); } return mem; } catch(Exception e) { logger.error(e.toString()); } finally { // clear the security advisor meleteSecurityService.popAdvisor(); } return null; } /* * */ public ResourcePropertiesEdit fillInSectionResourceProperties(boolean encodingFlag,String secResourceName, String secResourceDescription) { ResourcePropertiesEdit resProperties = getContentservice().newResourceProperties(); // resProperties.addProperty (ResourceProperties.PROP_COPYRIGHT,); // resourceProperties.addProperty(ResourceProperties.PROP_COPYRIGHT_CHOICE,); //Glenn said to not set the two properties below // resProperties.addProperty(ResourceProperties.PROP_COPYRIGHT_ALERT,Boolean.TRUE.toString()); //resProperties.addProperty(ResourceProperties.PROP_IS_COLLECTION,Boolean.FALSE.toString()); resProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, secResourceName); resProperties.addProperty(ResourceProperties.PROP_DESCRIPTION, secResourceDescription); resProperties.addProperty(getContentservice().PROP_ALTERNATE_REFERENCE, REFERENCE_ROOT); //Glenn said the property below may not need to be set either, will leave it in //unless it creates problems if (encodingFlag) resProperties.addProperty(ResourceProperties.PROP_CONTENT_ENCODING, "UTF-8"); return resProperties; } /* * resource properties for images embedded in the editor content */ public ResourcePropertiesEdit fillEmbeddedImagesResourceProperties(String name) { ResourcePropertiesEdit resProperties = getContentservice().newResourceProperties(); //Glenn said to not set the two properties below //resProperties.addProperty(ResourceProperties.PROP_COPYRIGHT_ALERT,Boolean.TRUE.toString()); //resProperties.addProperty(ResourceProperties.PROP_IS_COLLECTION,Boolean.FALSE.toString()); resProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name); resProperties.addProperty(ResourceProperties.PROP_DESCRIPTION,"embedded image"); resProperties.addProperty(getContentservice().PROP_ALTERNATE_REFERENCE, REFERENCE_ROOT); return resProperties; } /* * */ public void editResourceProperties(String selResourceIdFromList, String secResourceName, String secResourceDescription) { if(selResourceIdFromList == null || selResourceIdFromList.length() == 0) return; ContentResourceEdit edit = null; try { if (!isUserAuthor()) { logger.info("User is not authorized to access meleteDocs collection"); } // setup a security advisor meleteSecurityService.pushAdvisor(); selResourceIdFromList = URLDecoder.decode(selResourceIdFromList,"UTF-8"); edit = getContentservice().editResource(selResourceIdFromList); ResourcePropertiesEdit rp = edit.getPropertiesEdit(); rp.clear(); rp.addProperty(ResourceProperties.PROP_DISPLAY_NAME,secResourceName); rp.addProperty(ResourceProperties.PROP_DESCRIPTION,secResourceDescription); rp.addProperty(getContentservice().PROP_ALTERNATE_REFERENCE, REFERENCE_ROOT); getContentservice().commitResource(edit); edit = null; } catch(Exception e) { logger.error(e.toString()); } finally { if(edit != null) getContentservice().cancelResource(edit); // clear the security advisor meleteSecurityService.popAdvisor(); } return; } public String addResourceItem(String name, String res_mime_type,String addCollId, byte[] secContentData, ResourcePropertiesEdit res ) throws Exception { ContentResource resource = null; name = URLDecoder.decode(name,"UTF-8"); if (logger.isDebugEnabled()) logger.debug("IN addResourceItem "+name+" addCollId "+addCollId); // need to add notify logic here and set the arg6 accordingly. try { if (!isUserAuthor()) { logger.info("User is not authorized to add resource"); } // setup a security advisor meleteSecurityService.pushAdvisor(); try { String finalName = addCollId + name; if (finalName.length() > getContentservice().MAXIMUM_RESOURCE_ID_LENGTH) { // leaving room for CHS inserted duplicate filenames -1 -2 etc int extraChars = finalName.length() - getContentservice().MAXIMUM_RESOURCE_ID_LENGTH + 3; name = name.substring(0, name.length() - extraChars); } resource = getContentservice().addResource(name, addCollId, MAXIMUM_ATTEMPTS_FOR_UNIQUENESS, res_mime_type, secContentData, res, 0); // check if its duplicate file and edit the resource name if it is String checkDup = resource.getUrl().substring(resource.getUrl().lastIndexOf("/") + 1); ContentResourceEdit edit = null; try { if (!checkDup.equals(name)) { edit = getContentservice().editResource(resource.getId()); ResourcePropertiesEdit rp = edit.getPropertiesEdit(); String desc = rp.getProperty(ResourceProperties.PROP_DESCRIPTION); rp.clear(); rp.addProperty(ResourceProperties.PROP_DISPLAY_NAME, checkDup); rp.addProperty(ResourceProperties.PROP_DESCRIPTION, desc); rp.addProperty(getContentservice().PROP_ALTERNATE_REFERENCE, REFERENCE_ROOT); getContentservice().commitResource(edit); edit = null; } } catch (Exception ex) { throw ex; } finally { if (edit != null) getContentservice().cancelResource(edit); } } catch(PermissionException e) { logger.error("permission is denied"); } catch(IdInvalidException e) { logger.error("title" + " " + e.getMessage ()); throw new MeleteException("failed"); } catch(IdLengthException e) { logger.error("The name is too long" + " " +e.getMessage()); throw new MeleteException("failed"); } catch(IdUniquenessException e) { logger.error("Could not add this resource item to melete collection"); throw new MeleteException("failed"); } catch(InconsistentException e) { logger.error("Invalid characters in collection title"); throw new MeleteException("failed"); } catch(OverQuotaException e) { logger.error("Adding this resource would place this account over quota.To add this resource, some resources may need to be deleted."); throw new MeleteException("failed"); } catch(ServerOverloadException e) { logger.error("failed - internal error"); throw new MeleteException("failed"); } catch(RuntimeException e) { logger.error("SectionPage.addResourcetoMeleteCollection ***** Unknown Exception ***** " + e.getMessage()); e.printStackTrace(); throw new MeleteException("failed"); } } catch (Exception e) { logger.error(e.toString()); } finally{ meleteSecurityService.popAdvisor(); } return resource.getId(); } /* * */ public List getAllResources(String uploadCollId) { try { if (!isUserAuthor()) { logger.info("User is not authorized to access meleteDocs collection"); } // setup a security advisor meleteSecurityService.pushAdvisor(); return (getContentservice().getAllResources(uploadCollId)); } catch(Exception e) { logger.error(e.toString()); } finally { // clear the security advisor meleteSecurityService.popAdvisor(); } return null; } /* * */ public ContentResource getResource(String resourceId) throws Exception { try { if (!isUserAuthor() && !isUserStudent()) { logger.info("User is not authorized to access meleteDocs collection"); } // setup a security advisor meleteSecurityService.pushAdvisor(); resourceId = URLDecoder.decode(resourceId,"UTF-8"); return (getContentservice().getResource(resourceId)); } catch(Exception e) { logger.error(e.toString()); throw e; } finally { // clear the security advisor meleteSecurityService.popAdvisor(); } } public void checkResource(String resourceId) throws Exception { try { if (!isUserAuthor()) { logger.info("User is not authorized to access meleteDocs collection"); } // setup a security advisor meleteSecurityService.pushAdvisor(); resourceId = URLDecoder.decode(resourceId,"UTF-8"); getContentservice().checkResource(resourceId); return; } catch (IdUnusedException ex) { logger.debug("resource is not available so create one" + resourceId); throw ex; } catch(Exception e) { logger.error(e.toString()); } finally { // clear the security advisor meleteSecurityService.popAdvisor(); } return ; } /* * */ public void editResource(String resourceId, String contentEditor) throws Exception { ContentResourceEdit edit = null; try { if (!isUserAuthor()) { logger.info("User is not authorized to access meleteDocs collection"); } // setup a security advisor meleteSecurityService.pushAdvisor(); if (resourceId != null) { resourceId = URLDecoder.decode(resourceId,"UTF-8"); edit = getContentservice().editResource(resourceId); edit.setContent(contentEditor.getBytes()); edit.setContentLength(contentEditor.length()); getContentservice().commitResource(edit); edit = null; } return; } catch(Exception e) { logger.error("error saving editor content "+e.toString()); throw e; } finally { if(edit != null) getContentservice().cancelResource(edit); // clear the security advisor meleteSecurityService.popAdvisor(); } } /* * before saving editor content, look for embedded images from local system * and add them to collection * if filename has # sign then throw error * Do see diego's fix to paste from word works */ public String findLocalImagesEmbeddedInEditor(String uploadHomeDir, String contentEditor) throws MeleteException { String checkforimgs = contentEditor; // get collection id where the embedded files will go String UploadCollId = getUploadCollectionId(); String fileName; int startSrc =0; int endSrc = 0; String foundLink = null; // look for local embedded images try { if (!isUserAuthor()) { logger.info("User is not authorized to access meleteDocs"); return null; } // remove MSword comments int wordcommentIdx = -1; while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if gte vml 1]>")) != -1) { String pre = checkforimgs.substring(0,wordcommentIdx); checkforimgs = checkforimgs.substring(wordcommentIdx+19); int endcommentIdx = checkforimgs.indexOf("<![endif]-->"); checkforimgs = checkforimgs.substring(endcommentIdx+12); checkforimgs= pre + checkforimgs; wordcommentIdx = -1; } //for FCK editor inserted comments wordcommentIdx = -1; while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if !vml]-->")) != -1) { String pre = checkforimgs.substring(0,wordcommentIdx); checkforimgs = checkforimgs.substring(wordcommentIdx); int endcommentIdx = checkforimgs.indexOf("<!--[endif]-->"); checkforimgs = checkforimgs.substring(endcommentIdx+14); checkforimgs= pre + checkforimgs; wordcommentIdx = -1; } contentEditor = checkforimgs; // remove word comments code end //check for form tag and remove it checkforimgs = meleteUtil.findFormPattern(checkforimgs); contentEditor = checkforimgs; while(checkforimgs !=null) { // look for a href and img tag ArrayList embedData = meleteUtil.findEmbedItemPattern(checkforimgs); checkforimgs = (String)embedData.get(0); if (embedData.size() > 1) { startSrc = ((Integer)embedData.get(1)).intValue(); endSrc = ((Integer)embedData.get(2)).intValue(); foundLink = (String) embedData.get(3); } if (endSrc <= 0) break; // find filename fileName = checkforimgs.substring(startSrc, endSrc); String patternStr = fileName; logger.debug("processing embed src" + fileName); //process for local uploaded files if(fileName != null && fileName.trim().length() > 0&& (!(fileName.equals(File.separator))) && fileName.startsWith("file:/") ) { // word paste fix patternStr= meleteUtil.replace(patternStr,"\\","/"); contentEditor = meleteUtil.replace(contentEditor,fileName,patternStr); checkforimgs = meleteUtil.replace(checkforimgs,fileName,patternStr); fileName = patternStr; fileName = fileName.substring(fileName.lastIndexOf("/")+1); // if filename contains pound char then throw error if(fileName.indexOf("#") != -1) { logger.error("embedded FILE contains hash or other characters " + fileName); throw new MeleteException("embed_img_bad_filename"); } // add the file to collection and move from uploads directory // read data try{ File re = new File(uploadHomeDir+File.separator+fileName); byte[] data = new byte[(int)re.length()]; FileInputStream fis = new FileInputStream(re); fis.read(data); fis.close(); re.delete(); // add as a resource to uploads collection String file_mime_type = fileName.substring(fileName.lastIndexOf(".")+1); file_mime_type = ContentTypeImageService.getContentType(file_mime_type); String newEmbedResourceId = null; //If the resource already exists, use it try { String checkResourceId = UploadCollId + "/" + fileName; checkResource(checkResourceId); newEmbedResourceId = checkResourceId; } catch (IdUnusedException ex2) { ResourcePropertiesEdit res =fillEmbeddedImagesResourceProperties(fileName); newEmbedResourceId = addResourceItem(fileName,file_mime_type,UploadCollId,data,res ); } //add in melete resource database table also MeleteResource meleteResource = new MeleteResource(); meleteResource.setResourceId(newEmbedResourceId); //set default license info to "I have not determined copyright yet" option meleteResource.setLicenseCode(0); sectiondb.insertResource(meleteResource); // in content editor replace the file found with resource reference url String replaceStr = getResourceUrl(newEmbedResourceId); replaceStr = meleteUtil.replace(replaceStr,ServerConfigurationService.getServerUrl(),""); logger.debug("repl;acestr in embedimage processing is " + replaceStr); // Replace all occurrences of pattern in input Pattern pattern = Pattern.compile(patternStr); //Rashmi's change to fix infinite loop on uploading images contentEditor = meleteUtil.replace(contentEditor,patternStr,replaceStr); checkforimgs = meleteUtil.replace(checkforimgs,patternStr,replaceStr); } catch(FileNotFoundException ff) { logger.error(ff.toString()); throw new MeleteException("embed_image_size_exceed"); } } // for internal links to make it relative else { if (fileName.startsWith(ServerConfigurationService.getServerUrl())) { if (fileName.indexOf("/meleteDocs") != -1) { String findEntity = fileName.substring(fileName.indexOf("/access") + 7); Reference ref = EntityManager.newReference(findEntity); logger.debug("ref properties" + ref.getType() + "," + ref.getId()); String newEmbedResourceId = ref.getId(); newEmbedResourceId = newEmbedResourceId.replaceFirst("/content", ""); if (sectiondb.getMeleteResource(newEmbedResourceId) == null) { // add in melete resource database table also MeleteResource meleteResource = new MeleteResource(); meleteResource.setResourceId(newEmbedResourceId); // set default license info to "I have not determined copyright yet" option meleteResource.setLicenseCode(0); sectiondb.insertResource(meleteResource); } } String replaceStr = meleteUtil.replace(fileName, ServerConfigurationService.getServerUrl(), ""); contentEditor = meleteUtil.replace(contentEditor, patternStr, replaceStr); checkforimgs = meleteUtil.replace(checkforimgs, patternStr, replaceStr); } // process links and append http:// protocol if not provided - else if (!fileName.startsWith("/access") - && foundLink != null - && foundLink.equals("link") - && !(fileName.startsWith("http://") || fileName.startsWith("https://") || fileName.startsWith("mailto:") || fileName - .startsWith("#"))) + else if (!(fileName.startsWith("/") || fileName.startsWith("./") || fileName.startsWith("../") || fileName.startsWith("#")) + && foundLink != null && foundLink.equals("link") + && !(fileName.startsWith("http://") || fileName.startsWith("https://") || fileName.startsWith("mailto:"))) { logger.debug("processing embed link src for appending protocol"); String replaceLinkStr = "http://" + fileName; contentEditor = meleteUtil.replace(contentEditor, fileName, replaceLinkStr); checkforimgs = meleteUtil.replace(checkforimgs, fileName, replaceLinkStr); } } // add target if not provided if(foundLink != null && foundLink.equals("link")) { String soFar = checkforimgs.substring(0,endSrc); String checkTarget = checkforimgs.substring(endSrc , checkforimgs.indexOf(">")+1); String laterPart = checkforimgs.substring(checkforimgs.indexOf(">")+2); Pattern pa = Pattern.compile("\\s[tT][aA][rR][gG][eE][tT]\\s*="); Matcher m = pa.matcher(checkTarget); if(!m.find()) { String newTarget = meleteUtil.replace(checkTarget, ">", " target=_blank >"); checkforimgs = soFar + newTarget + laterPart; contentEditor = meleteUtil.replace(contentEditor, soFar + checkTarget, soFar+newTarget); } } // iterate next if(endSrc > 0 && endSrc <= checkforimgs.length()) checkforimgs =checkforimgs.substring(endSrc); else checkforimgs = null; startSrc=0; endSrc = 0; foundLink = null; } } catch(MeleteException me) {throw me;} catch(Exception e){logger.error(e.toString());e.printStackTrace();} return contentEditor; } public List findAllEmbeddedImages(String sec_resId) throws Exception { try{ ContentResource cr = getResource(sec_resId); String checkforImgs = new String(cr.getContent()); List secEmbedData = new ArrayList<String> (0); int startSrc=0, endSrc=0; if (checkforImgs == null || checkforImgs.length() == 0) return null; while(checkforImgs != null) { // look for a href and img tag ArrayList embedData = meleteUtil.findEmbedItemPattern(checkforImgs); checkforImgs = (String)embedData.get(0); if (embedData.size() > 1) { startSrc = ((Integer)embedData.get(1)).intValue(); endSrc = ((Integer)embedData.get(2)).intValue(); } if (endSrc <= 0) break; // find filename and add just the ones which belongs to meleteDocs String fileName = checkforImgs.substring(startSrc, endSrc); if(fileName.startsWith("/access/meleteDocs/content")) { fileName = fileName.replace("/access/meleteDocs/content", ""); fileName = URLDecoder.decode(fileName,"UTF-8"); secEmbedData.add(fileName); } // iterate next checkforImgs =checkforImgs.substring(endSrc); startSrc=0; endSrc = 0; } return secEmbedData; } catch(Exception e) { logger.debug("can't read section file" + sec_resId); } return null; } /* * get the URL for replaceStr of embedded images */ public String getResourceUrl(String newResourceId) { try { meleteSecurityService.pushAdvisor(); newResourceId = URLDecoder.decode(newResourceId,"UTF-8"); return getContentservice().getUrl(newResourceId); } catch (Exception e) { e.printStackTrace(); return ""; } finally { meleteSecurityService.popAdvisor(); } } public void copyIntoFolder(String fromColl,String toColl) { try { if (!isUserAuthor()) { logger.info("User is not authorized to perform the copyIntoFolder function"); } // setup a security advisor meleteSecurityService.pushAdvisor(); try { getContentservice().copyIntoFolder(fromColl, toColl); } catch(InconsistentException e) { logger.error("Inconsistent exception thrown"); } catch(IdLengthException e) { logger.error("IdLength exception thrown"); } catch(IdUniquenessException e) { logger.error("IdUniqueness exception thrown"); } catch(PermissionException e) { logger.error("Permission to copy uploads collection is denied"); } catch(IdUnusedException e) { logger.error("Failed to create uploads collection in second site"); } catch(TypeException e) { logger.error("TypeException thrown: "+e.getMessage()); } catch(InUseException e) { logger.error("InUseException thrown: "+e.getMessage()); } catch(IdUsedException e) { logger.error("IdUsedException thrown"); } catch(OverQuotaException e) { logger.error("Copying this collection would place this account over quota."); } catch(ServerOverloadException e) { logger.error("Server overload exception"); } } catch (Exception e) { e.printStackTrace(); } finally { meleteSecurityService.popAdvisor(); } } public ContentCollection getCollection(String toColl) { ContentCollection toCollection = null; try { if (!isUserAuthor()) { logger.info("User is not authorized to perform the copyIntoFolder function"); } // setup a security advisor meleteSecurityService.pushAdvisor(); try { toCollection = getContentservice().getCollection(toColl); } catch(IdUnusedException e1) { logger.error("IdUnusedException thrown: "+e1.getMessage()); } catch(TypeException e1) { logger.error("TypeException thrown: "+e1.getMessage()); } catch(PermissionException e1) { logger.error("Permission to get uploads collection is denied"); } } catch (Exception e) { e.printStackTrace(); } finally { meleteSecurityService.popAdvisor(); } return toCollection; } public void removeResource(String delRes_id) throws Exception { if (!isUserAuthor()) { logger.info("User is not authorized to perform del resource function"); } // setup a security advisor meleteSecurityService.pushAdvisor(); ContentResourceEdit edit = null; try { edit = getContentservice().editResource(delRes_id); getContentservice().removeResource(edit); edit = null; } catch(IdUnusedException e1) { logger.error("IdUnusedException thrown: "+e1.getMessage() + delRes_id ); } catch(TypeException e1) { logger.error("TypeException thrown: "+e1.getMessage()); } catch(PermissionException e1) { logger.error("Permission to get uploads collection is denied"); } catch (Exception e) { e.printStackTrace(); throw new MeleteException("delete_resource_fail"); } finally { if(edit != null)getContentservice().cancelResource(edit); meleteSecurityService.popAdvisor(); } } public void removeCollection(String delColl_id, String delSubColl_id) throws Exception { if (!isUserAuthor()) { logger.info("User is not authorized to perform del resource function"); } // setup a security advisor meleteSecurityService.pushAdvisor(); delColl_id= Entity.SEPARATOR+"private"+ REFERENCE_ROOT+ Entity.SEPARATOR+delColl_id+ Entity.SEPARATOR; if(delSubColl_id != null) delColl_id = delColl_id.concat(delSubColl_id + Entity.SEPARATOR); logger.debug("checking coll before delte" + delColl_id); try { getContentservice().checkCollection(delColl_id); getContentservice().removeCollection(delColl_id); } catch (IdUnusedException e1) { logger.error("IdUnusedException thrown: "+e1.getMessage()); } catch(TypeException e1) { logger.error("TypeException thrown: "+e1.getMessage()); } catch(PermissionException e1) { logger.error("Permission to get uploads collection is denied"); } catch (Exception e) { logger.error("error deleting melete collection:" + e.getMessage()); throw new MeleteException("delete_resource_fail"); } finally { meleteSecurityService.popAdvisor(); } } public void removeCourseCollection(String delColl_id) throws Exception { if (!isUserAuthor()) { logger.info("User is not authorized to perform del resource function"); } // setup a security advisor meleteSecurityService.pushAdvisor(); try { delColl_id= Entity.SEPARATOR+"private"+ REFERENCE_ROOT+ Entity.SEPARATOR+delColl_id+ Entity.SEPARATOR; logger.debug("checking course coll before delete: " + delColl_id); getContentservice().checkCollection(delColl_id); // if uploads directory remains and all modules are deleted logger.debug("collection sz"+ getContentservice().getCollectionSize(delColl_id)); if(getContentservice().getCollectionSize(delColl_id) == 1) { List allEnt = getContentservice().getAllEntities(delColl_id); for(Iterator i = allEnt.iterator(); i.hasNext();) { ContentEntity ce = (ContentEntity)i.next(); if(ce.isCollection() && (ce.getId().indexOf("module_") == -1)) getContentservice().removeCollection(delColl_id); } } } catch(IdUnusedException e1) { logger.error("IdUnusedException thrown from remove Course Collection: "+e1.getMessage()); } catch(TypeException e1) { logger.error("TypeException thrown: "+e1.getMessage()); } catch(PermissionException e1) { logger.error("Permission to get uploads collection is denied"); } catch (Exception e) { throw new MeleteException("delete_resource_fail"); } finally { meleteSecurityService.popAdvisor(); } } public String moveResource(String resourceId, String destinationColl) throws Exception { if (!isUserAuthor()) { logger.info("User is not authorized to perform del resource function"); } // setup a security advisor meleteSecurityService.pushAdvisor(); try { getContentservice().checkResource(resourceId); String newResId = getContentservice().moveIntoFolder(resourceId,destinationColl); return newResId; } catch(IdUnusedException e1) { logger.error("IdUnusedException thrown from moveResource: "+e1.getMessage()); } catch (Exception e) { throw new MeleteException("move_resource_fail"); } finally { meleteSecurityService.popAdvisor(); } return null; } /** * @return Returns the logger. */ public void setLogger(Log logger) { this.logger = logger; } /** * @return Returns the contentservice. */ public ContentHostingService getContentservice() { return contentservice; } /** * @param contentservice The contentservice to set. */ public void setContentservice(ContentHostingService contentservice) { this.contentservice = contentservice; } /** * @return meleteSecurityService */ public MeleteSecurityService getMeleteSecurityService() { return meleteSecurityService; } /** * @param meleteSecurityService The meleteSecurityService to set. */ public void setMeleteSecurityService(MeleteSecurityService meleteSecurityService) { this.meleteSecurityService = meleteSecurityService; } /** * @return Returns the sectiondb. */ public SectionDB getSectiondb() { return sectiondb; } /** * @param sectiondb The sectiondb to set. */ public void setSectiondb(SectionDB sectiondb) { this.sectiondb = sectiondb; } }
true
true
public String findLocalImagesEmbeddedInEditor(String uploadHomeDir, String contentEditor) throws MeleteException { String checkforimgs = contentEditor; // get collection id where the embedded files will go String UploadCollId = getUploadCollectionId(); String fileName; int startSrc =0; int endSrc = 0; String foundLink = null; // look for local embedded images try { if (!isUserAuthor()) { logger.info("User is not authorized to access meleteDocs"); return null; } // remove MSword comments int wordcommentIdx = -1; while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if gte vml 1]>")) != -1) { String pre = checkforimgs.substring(0,wordcommentIdx); checkforimgs = checkforimgs.substring(wordcommentIdx+19); int endcommentIdx = checkforimgs.indexOf("<![endif]-->"); checkforimgs = checkforimgs.substring(endcommentIdx+12); checkforimgs= pre + checkforimgs; wordcommentIdx = -1; } //for FCK editor inserted comments wordcommentIdx = -1; while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if !vml]-->")) != -1) { String pre = checkforimgs.substring(0,wordcommentIdx); checkforimgs = checkforimgs.substring(wordcommentIdx); int endcommentIdx = checkforimgs.indexOf("<!--[endif]-->"); checkforimgs = checkforimgs.substring(endcommentIdx+14); checkforimgs= pre + checkforimgs; wordcommentIdx = -1; } contentEditor = checkforimgs; // remove word comments code end //check for form tag and remove it checkforimgs = meleteUtil.findFormPattern(checkforimgs); contentEditor = checkforimgs; while(checkforimgs !=null) { // look for a href and img tag ArrayList embedData = meleteUtil.findEmbedItemPattern(checkforimgs); checkforimgs = (String)embedData.get(0); if (embedData.size() > 1) { startSrc = ((Integer)embedData.get(1)).intValue(); endSrc = ((Integer)embedData.get(2)).intValue(); foundLink = (String) embedData.get(3); } if (endSrc <= 0) break; // find filename fileName = checkforimgs.substring(startSrc, endSrc); String patternStr = fileName; logger.debug("processing embed src" + fileName); //process for local uploaded files if(fileName != null && fileName.trim().length() > 0&& (!(fileName.equals(File.separator))) && fileName.startsWith("file:/") ) { // word paste fix patternStr= meleteUtil.replace(patternStr,"\\","/"); contentEditor = meleteUtil.replace(contentEditor,fileName,patternStr); checkforimgs = meleteUtil.replace(checkforimgs,fileName,patternStr); fileName = patternStr; fileName = fileName.substring(fileName.lastIndexOf("/")+1); // if filename contains pound char then throw error if(fileName.indexOf("#") != -1) { logger.error("embedded FILE contains hash or other characters " + fileName); throw new MeleteException("embed_img_bad_filename"); } // add the file to collection and move from uploads directory // read data try{ File re = new File(uploadHomeDir+File.separator+fileName); byte[] data = new byte[(int)re.length()]; FileInputStream fis = new FileInputStream(re); fis.read(data); fis.close(); re.delete(); // add as a resource to uploads collection String file_mime_type = fileName.substring(fileName.lastIndexOf(".")+1); file_mime_type = ContentTypeImageService.getContentType(file_mime_type); String newEmbedResourceId = null; //If the resource already exists, use it try { String checkResourceId = UploadCollId + "/" + fileName; checkResource(checkResourceId); newEmbedResourceId = checkResourceId; } catch (IdUnusedException ex2) { ResourcePropertiesEdit res =fillEmbeddedImagesResourceProperties(fileName); newEmbedResourceId = addResourceItem(fileName,file_mime_type,UploadCollId,data,res ); } //add in melete resource database table also MeleteResource meleteResource = new MeleteResource(); meleteResource.setResourceId(newEmbedResourceId); //set default license info to "I have not determined copyright yet" option meleteResource.setLicenseCode(0); sectiondb.insertResource(meleteResource); // in content editor replace the file found with resource reference url String replaceStr = getResourceUrl(newEmbedResourceId); replaceStr = meleteUtil.replace(replaceStr,ServerConfigurationService.getServerUrl(),""); logger.debug("repl;acestr in embedimage processing is " + replaceStr); // Replace all occurrences of pattern in input Pattern pattern = Pattern.compile(patternStr); //Rashmi's change to fix infinite loop on uploading images contentEditor = meleteUtil.replace(contentEditor,patternStr,replaceStr); checkforimgs = meleteUtil.replace(checkforimgs,patternStr,replaceStr); } catch(FileNotFoundException ff) { logger.error(ff.toString()); throw new MeleteException("embed_image_size_exceed"); } } // for internal links to make it relative else { if (fileName.startsWith(ServerConfigurationService.getServerUrl())) { if (fileName.indexOf("/meleteDocs") != -1) { String findEntity = fileName.substring(fileName.indexOf("/access") + 7); Reference ref = EntityManager.newReference(findEntity); logger.debug("ref properties" + ref.getType() + "," + ref.getId()); String newEmbedResourceId = ref.getId(); newEmbedResourceId = newEmbedResourceId.replaceFirst("/content", ""); if (sectiondb.getMeleteResource(newEmbedResourceId) == null) { // add in melete resource database table also MeleteResource meleteResource = new MeleteResource(); meleteResource.setResourceId(newEmbedResourceId); // set default license info to "I have not determined copyright yet" option meleteResource.setLicenseCode(0); sectiondb.insertResource(meleteResource); } } String replaceStr = meleteUtil.replace(fileName, ServerConfigurationService.getServerUrl(), ""); contentEditor = meleteUtil.replace(contentEditor, patternStr, replaceStr); checkforimgs = meleteUtil.replace(checkforimgs, patternStr, replaceStr); } // process links and append http:// protocol if not provided else if (!fileName.startsWith("/access") && foundLink != null && foundLink.equals("link") && !(fileName.startsWith("http://") || fileName.startsWith("https://") || fileName.startsWith("mailto:") || fileName .startsWith("#"))) { logger.debug("processing embed link src for appending protocol"); String replaceLinkStr = "http://" + fileName; contentEditor = meleteUtil.replace(contentEditor, fileName, replaceLinkStr); checkforimgs = meleteUtil.replace(checkforimgs, fileName, replaceLinkStr); } } // add target if not provided if(foundLink != null && foundLink.equals("link")) { String soFar = checkforimgs.substring(0,endSrc); String checkTarget = checkforimgs.substring(endSrc , checkforimgs.indexOf(">")+1); String laterPart = checkforimgs.substring(checkforimgs.indexOf(">")+2); Pattern pa = Pattern.compile("\\s[tT][aA][rR][gG][eE][tT]\\s*="); Matcher m = pa.matcher(checkTarget); if(!m.find()) { String newTarget = meleteUtil.replace(checkTarget, ">", " target=_blank >"); checkforimgs = soFar + newTarget + laterPart; contentEditor = meleteUtil.replace(contentEditor, soFar + checkTarget, soFar+newTarget); } } // iterate next if(endSrc > 0 && endSrc <= checkforimgs.length()) checkforimgs =checkforimgs.substring(endSrc); else checkforimgs = null; startSrc=0; endSrc = 0; foundLink = null; } } catch(MeleteException me) {throw me;} catch(Exception e){logger.error(e.toString());e.printStackTrace();} return contentEditor; }
public String findLocalImagesEmbeddedInEditor(String uploadHomeDir, String contentEditor) throws MeleteException { String checkforimgs = contentEditor; // get collection id where the embedded files will go String UploadCollId = getUploadCollectionId(); String fileName; int startSrc =0; int endSrc = 0; String foundLink = null; // look for local embedded images try { if (!isUserAuthor()) { logger.info("User is not authorized to access meleteDocs"); return null; } // remove MSword comments int wordcommentIdx = -1; while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if gte vml 1]>")) != -1) { String pre = checkforimgs.substring(0,wordcommentIdx); checkforimgs = checkforimgs.substring(wordcommentIdx+19); int endcommentIdx = checkforimgs.indexOf("<![endif]-->"); checkforimgs = checkforimgs.substring(endcommentIdx+12); checkforimgs= pre + checkforimgs; wordcommentIdx = -1; } //for FCK editor inserted comments wordcommentIdx = -1; while (checkforimgs != null && (wordcommentIdx = checkforimgs.indexOf("<!--[if !vml]-->")) != -1) { String pre = checkforimgs.substring(0,wordcommentIdx); checkforimgs = checkforimgs.substring(wordcommentIdx); int endcommentIdx = checkforimgs.indexOf("<!--[endif]-->"); checkforimgs = checkforimgs.substring(endcommentIdx+14); checkforimgs= pre + checkforimgs; wordcommentIdx = -1; } contentEditor = checkforimgs; // remove word comments code end //check for form tag and remove it checkforimgs = meleteUtil.findFormPattern(checkforimgs); contentEditor = checkforimgs; while(checkforimgs !=null) { // look for a href and img tag ArrayList embedData = meleteUtil.findEmbedItemPattern(checkforimgs); checkforimgs = (String)embedData.get(0); if (embedData.size() > 1) { startSrc = ((Integer)embedData.get(1)).intValue(); endSrc = ((Integer)embedData.get(2)).intValue(); foundLink = (String) embedData.get(3); } if (endSrc <= 0) break; // find filename fileName = checkforimgs.substring(startSrc, endSrc); String patternStr = fileName; logger.debug("processing embed src" + fileName); //process for local uploaded files if(fileName != null && fileName.trim().length() > 0&& (!(fileName.equals(File.separator))) && fileName.startsWith("file:/") ) { // word paste fix patternStr= meleteUtil.replace(patternStr,"\\","/"); contentEditor = meleteUtil.replace(contentEditor,fileName,patternStr); checkforimgs = meleteUtil.replace(checkforimgs,fileName,patternStr); fileName = patternStr; fileName = fileName.substring(fileName.lastIndexOf("/")+1); // if filename contains pound char then throw error if(fileName.indexOf("#") != -1) { logger.error("embedded FILE contains hash or other characters " + fileName); throw new MeleteException("embed_img_bad_filename"); } // add the file to collection and move from uploads directory // read data try{ File re = new File(uploadHomeDir+File.separator+fileName); byte[] data = new byte[(int)re.length()]; FileInputStream fis = new FileInputStream(re); fis.read(data); fis.close(); re.delete(); // add as a resource to uploads collection String file_mime_type = fileName.substring(fileName.lastIndexOf(".")+1); file_mime_type = ContentTypeImageService.getContentType(file_mime_type); String newEmbedResourceId = null; //If the resource already exists, use it try { String checkResourceId = UploadCollId + "/" + fileName; checkResource(checkResourceId); newEmbedResourceId = checkResourceId; } catch (IdUnusedException ex2) { ResourcePropertiesEdit res =fillEmbeddedImagesResourceProperties(fileName); newEmbedResourceId = addResourceItem(fileName,file_mime_type,UploadCollId,data,res ); } //add in melete resource database table also MeleteResource meleteResource = new MeleteResource(); meleteResource.setResourceId(newEmbedResourceId); //set default license info to "I have not determined copyright yet" option meleteResource.setLicenseCode(0); sectiondb.insertResource(meleteResource); // in content editor replace the file found with resource reference url String replaceStr = getResourceUrl(newEmbedResourceId); replaceStr = meleteUtil.replace(replaceStr,ServerConfigurationService.getServerUrl(),""); logger.debug("repl;acestr in embedimage processing is " + replaceStr); // Replace all occurrences of pattern in input Pattern pattern = Pattern.compile(patternStr); //Rashmi's change to fix infinite loop on uploading images contentEditor = meleteUtil.replace(contentEditor,patternStr,replaceStr); checkforimgs = meleteUtil.replace(checkforimgs,patternStr,replaceStr); } catch(FileNotFoundException ff) { logger.error(ff.toString()); throw new MeleteException("embed_image_size_exceed"); } } // for internal links to make it relative else { if (fileName.startsWith(ServerConfigurationService.getServerUrl())) { if (fileName.indexOf("/meleteDocs") != -1) { String findEntity = fileName.substring(fileName.indexOf("/access") + 7); Reference ref = EntityManager.newReference(findEntity); logger.debug("ref properties" + ref.getType() + "," + ref.getId()); String newEmbedResourceId = ref.getId(); newEmbedResourceId = newEmbedResourceId.replaceFirst("/content", ""); if (sectiondb.getMeleteResource(newEmbedResourceId) == null) { // add in melete resource database table also MeleteResource meleteResource = new MeleteResource(); meleteResource.setResourceId(newEmbedResourceId); // set default license info to "I have not determined copyright yet" option meleteResource.setLicenseCode(0); sectiondb.insertResource(meleteResource); } } String replaceStr = meleteUtil.replace(fileName, ServerConfigurationService.getServerUrl(), ""); contentEditor = meleteUtil.replace(contentEditor, patternStr, replaceStr); checkforimgs = meleteUtil.replace(checkforimgs, patternStr, replaceStr); } // process links and append http:// protocol if not provided else if (!(fileName.startsWith("/") || fileName.startsWith("./") || fileName.startsWith("../") || fileName.startsWith("#")) && foundLink != null && foundLink.equals("link") && !(fileName.startsWith("http://") || fileName.startsWith("https://") || fileName.startsWith("mailto:"))) { logger.debug("processing embed link src for appending protocol"); String replaceLinkStr = "http://" + fileName; contentEditor = meleteUtil.replace(contentEditor, fileName, replaceLinkStr); checkforimgs = meleteUtil.replace(checkforimgs, fileName, replaceLinkStr); } } // add target if not provided if(foundLink != null && foundLink.equals("link")) { String soFar = checkforimgs.substring(0,endSrc); String checkTarget = checkforimgs.substring(endSrc , checkforimgs.indexOf(">")+1); String laterPart = checkforimgs.substring(checkforimgs.indexOf(">")+2); Pattern pa = Pattern.compile("\\s[tT][aA][rR][gG][eE][tT]\\s*="); Matcher m = pa.matcher(checkTarget); if(!m.find()) { String newTarget = meleteUtil.replace(checkTarget, ">", " target=_blank >"); checkforimgs = soFar + newTarget + laterPart; contentEditor = meleteUtil.replace(contentEditor, soFar + checkTarget, soFar+newTarget); } } // iterate next if(endSrc > 0 && endSrc <= checkforimgs.length()) checkforimgs =checkforimgs.substring(endSrc); else checkforimgs = null; startSrc=0; endSrc = 0; foundLink = null; } } catch(MeleteException me) {throw me;} catch(Exception e){logger.error(e.toString());e.printStackTrace();} return contentEditor; }
diff --git a/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java b/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java index b7e470087..401bdc42d 100755 --- a/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java +++ b/src/com/redhat/ceylon/compiler/java/codegen/AbstractTransformer.java @@ -1,1763 +1,1764 @@ /* * Copyright Red Hat Inc. and/or its affiliates and other contributors * as indicated by the authors tag. All rights reserved. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU General Public License version 2. * * This particular file is subject to the "Classpath" exception as provided in the * LICENSE file that accompanied this code. * * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License, * along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package com.redhat.ceylon.compiler.java.codegen; import static com.sun.tools.javac.code.Flags.FINAL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.antlr.runtime.Token; import com.redhat.ceylon.compiler.java.loader.CeylonModelLoader; import com.redhat.ceylon.compiler.java.loader.TypeFactory; import com.redhat.ceylon.compiler.java.tools.CeylonLog; import com.redhat.ceylon.compiler.java.util.Decl; import com.redhat.ceylon.compiler.java.util.Util; import com.redhat.ceylon.compiler.loader.ModelLoader.DeclarationType; import com.redhat.ceylon.compiler.typechecker.model.Annotation; import com.redhat.ceylon.compiler.typechecker.model.BottomType; import com.redhat.ceylon.compiler.typechecker.model.Class; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Interface; import com.redhat.ceylon.compiler.typechecker.model.FunctionalParameter; import com.redhat.ceylon.compiler.typechecker.model.IntersectionType; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.ModuleImport; import com.redhat.ceylon.compiler.typechecker.model.Package; import com.redhat.ceylon.compiler.typechecker.model.Parameter; import com.redhat.ceylon.compiler.typechecker.model.ProducedType; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; import com.redhat.ceylon.compiler.typechecker.model.TypeParameter; import com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration; import com.redhat.ceylon.compiler.typechecker.model.UnionType; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Tree.Expression; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.TypeTags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.Factory; import com.sun.tools.javac.tree.JCTree.JCAnnotation; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCLiteral; import com.sun.tools.javac.tree.JCTree.JCStatement; import com.sun.tools.javac.tree.JCTree.JCTypeParameter; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.JCTree.LetExpr; import com.sun.tools.javac.tree.TreeMaker; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.List; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Names; import com.sun.tools.javac.util.Position; import com.sun.tools.javac.util.Position.LineMap; /** * Base class for all delegating transformers */ public abstract class AbstractTransformer implements Transformation { private Context context; private TreeMaker make; private Names names; private Symtab syms; private CeylonModelLoader loader; private TypeFactory typeFact; protected Log log; public AbstractTransformer(Context context) { this.context = context; make = TreeMaker.instance(context); names = Names.instance(context); syms = Symtab.instance(context); loader = CeylonModelLoader.instance(context); typeFact = TypeFactory.instance(context); log = CeylonLog.instance(context); } public Context getContext() { return context; } @Override public TreeMaker make() { return make; } private static JavaPositionsRetriever javaPositionsRetriever = null; public static void trackNodePositions(JavaPositionsRetriever positionsRetriever) { javaPositionsRetriever = positionsRetriever; } @Override public Factory at(Node node) { if (node == null) { make.at(Position.NOPOS); } else { Token token = node.getToken(); if (token != null) { int tokenStartPosition = getMap().getStartPosition(token.getLine()) + token.getCharPositionInLine(); make().at(tokenStartPosition); if (javaPositionsRetriever != null) { javaPositionsRetriever.addCeylonNode(tokenStartPosition, node); } } } return make(); } @Override public Symtab syms() { return syms; } @Override public Names names() { return names; } @Override public CeylonModelLoader loader() { return loader; } @Override public TypeFactory typeFact() { return typeFact; } public void setMap(LineMap map) { gen().setMap(map); } protected LineMap getMap() { return gen().getMap(); } @Override public CeylonTransformer gen() { return CeylonTransformer.getInstance(context); } @Override public ExpressionTransformer expressionGen() { return ExpressionTransformer.getInstance(context); } @Override public StatementTransformer statementGen() { return StatementTransformer.getInstance(context); } @Override public ClassTransformer classGen() { return ClassTransformer.getInstance(context); } /** * Makes an <strong>unquoted</strong> simple identifier * @param ident The identifier * @return The ident */ protected JCExpression makeUnquotedIdent(String ident) { return make().Ident(names().fromString(ident)); } /** * Makes an <strong>quoted</strong> simple identifier * @param ident The identifier * @return The ident */ protected JCIdent makeQuotedIdent(String ident) { return make().Ident(names().fromString(Util.quoteIfJavaKeyword(ident))); } /** * Makes an <strong>unquoted</strong> qualified (compound) identifier from * the given qualified name. * @param qualifiedName The qualified name * @see #makeQuotedQualIdentFromString(String) */ protected JCExpression makeQualIdentFromString(String qualifiedName) { return makeQualIdent(null, qualifiedName.split("\\.")); } /** * Makes a <strong>quoted</strong> qualified (compound) identifier from * the given qualified name. Each part of the name will be * quoted if it is a Java keyword. * @param qualifiedName The qualified name */ protected JCExpression makeQuotedQualIdentFromString(String qualifiedName) { return makeQualIdent(null, Util.quoteJavaKeywords(qualifiedName.split("\\."))); } /** * Makes an <strong>unquoted</strong> qualified (compound) identifier * from the given qualified name components * @param components The components of the name. * @see #makeQuotedQualIdentFromString(String) */ protected JCExpression makeQualIdent(Iterable<String> components) { JCExpression type = null; for (String component : components) { if (type == null) type = makeUnquotedIdent(component); else type = makeSelect(type, component); } return type; } protected JCExpression makeQuotedQualIdent(Iterable<String> components) { JCExpression type = null; for (String component : components) { if (type == null) type = makeQuotedIdent(component); else type = makeSelect(type, Util.quoteIfJavaKeyword(component)); } return type; } /** * Makes an <strong>unquoted</strong> qualified (compound) identifier * from the given qualified name components * @param expr A starting expression (may be null) * @param names The components of the name (may be null) * @see #makeQuotedQualIdentFromString(String) */ protected JCExpression makeQualIdent(JCExpression expr, String... names) { if (names != null) { for (String component : names) { if (component != null) { if (expr == null) { expr = makeUnquotedIdent(component); } else { expr = makeSelect(expr, component); } } } } return expr; } protected JCExpression makeQuotedQualIdent(JCExpression expr, String... names) { if (names != null) { for (String component : names) { if (component != null) { if (expr == null) { expr = makeQuotedIdent(component); } else { expr = makeSelect(expr, Util.quoteIfJavaKeyword(component)); } } } } return expr; } protected JCExpression makeFQIdent(String... components) { return makeQualIdent(makeUnquotedIdent(""), components); } protected JCExpression makeQuotedFQIdent(String... components) { return makeQuotedQualIdent(makeUnquotedIdent(""), components); } protected JCExpression makeQuotedFQIdent(String qualifiedName) { return makeQuotedFQIdent(Util.quoteJavaKeywords(qualifiedName.split("\\."))); } protected JCExpression makeIdent(Type type) { return make().QualIdent(type.tsym); } /** * Makes a <strong>unquoted</strong> field access * @param s1 The base expression * @param s2 The field to access * @return The field access */ protected JCFieldAccess makeSelect(JCExpression s1, String s2) { return make().Select(s1, names().fromString(s2)); } /** * Makes a <strong>unquoted</strong> field access * @param s1 The base expression * @param s2 The field to access * @return The field access */ protected JCFieldAccess makeSelect(String s1, String s2) { return makeSelect(makeUnquotedIdent(s1), s2); } /** * Makes a sequence of <strong>unquoted</strong> field accesses * @param s1 The base expression * @param s2 The first field to access * @param rest The remaining fields to access * @return The field access */ protected JCFieldAccess makeSelect(String s1, String s2, String... rest) { return makeSelect(makeSelect(s1, s2), rest); } private JCFieldAccess makeSelect(JCFieldAccess s1, String[] rest) { JCFieldAccess acc = s1; for (String s : rest) { acc = makeSelect(acc, s); } return acc; } protected JCLiteral makeNull() { return make().Literal(TypeTags.BOT, null); } protected JCExpression makeInteger(int i) { return make().Literal(Integer.valueOf(i)); } protected JCExpression makeLong(long i) { return make().Literal(Long.valueOf(i)); } protected JCExpression makeBoolean(boolean b) { JCExpression expr; if (b) { expr = make().Literal(TypeTags.BOOLEAN, Integer.valueOf(1)); } else { expr = make().Literal(TypeTags.BOOLEAN, Integer.valueOf(0)); } return expr; } // Creates a "foo foo = new foo();" protected JCTree.JCVariableDecl makeLocalIdentityInstance(String varName, boolean isShared) { JCExpression name = makeQuotedIdent(varName); JCExpression initValue = makeNewClass(varName, false); List<JCAnnotation> annots = List.<JCAnnotation>nil(); int modifiers = isShared ? 0 : FINAL; JCTree.JCVariableDecl var = make().VarDef( make().Modifiers(modifiers, annots), names().fromString(varName), name, initValue); return var; } // Creates a "new foo();" protected JCTree.JCNewClass makeNewClass(String className, boolean fullyQualified) { return makeNewClass(className, List.<JCTree.JCExpression>nil(), fullyQualified); } // Creates a "new foo(arg1, arg2, ...);" protected JCTree.JCNewClass makeNewClass(String className, List<JCTree.JCExpression> args, boolean fullyQualified) { JCExpression name = fullyQualified ? makeQuotedFQIdent(className) : makeQuotedQualIdentFromString(className); return makeNewClass(name, args); } // Creates a "new foo(arg1, arg2, ...);" protected JCTree.JCNewClass makeNewClass(JCExpression clazz, List<JCTree.JCExpression> args) { return make().NewClass(null, null, clazz, args, null); } protected JCVariableDecl makeVar(String varName, JCExpression typeExpr, JCExpression valueExpr) { return make().VarDef(make().Modifiers(0), names().fromString(varName), typeExpr, valueExpr); } // Creates a "( let var1=expr1,var2=expr2,...,varN=exprN in varN; )" // or a "( let var1=expr1,var2=expr2,...,varN=exprN,exprO in exprO; )" protected JCExpression makeLetExpr(JCExpression... args) { return makeLetExpr(tempName(), null, args); } // Creates a "( let var1=expr1,var2=expr2,...,varN=exprN in statements; varN; )" // or a "( let var1=expr1,var2=expr2,...,varN=exprN in statements; exprO; )" protected JCExpression makeLetExpr(String varBaseName, List<JCStatement> statements, JCExpression... args) { String varName = null; List<JCVariableDecl> decls = List.nil(); int i; for (i = 0; (i + 1) < args.length; i += 2) { JCExpression typeExpr = args[i]; JCExpression valueExpr = args[i+1]; varName = varBaseName + ((args.length > 3) ? "$" + i : ""); JCVariableDecl varDecl = makeVar(varName, typeExpr, valueExpr); decls = decls.append(varDecl); } JCExpression result; if (i == args.length) { result = makeUnquotedIdent(varName); } else { result = args[i]; } if (statements != null) { return make().LetExpr(decls, statements, result); } else { return make().LetExpr(decls, result); } } /* * Methods for making unique temporary and alias names */ static class UniqueId { private long id = 0; private long nextId() { return id++; } } private long nextUniqueId() { UniqueId id = context.get(UniqueId.class); if (id == null) { id = new UniqueId(); context.put(UniqueId.class, id); } return id.nextId(); } protected String tempName() { String result = "$ceylontmp" + nextUniqueId(); return result; } protected String tempName(String prefix) { String result = "$ceylontmp" + prefix + nextUniqueId(); return result; } protected String aliasName(String name) { String result = "$" + name + "$" + nextUniqueId(); return result; } /* * Type handling */ boolean isBooleanTrue(Declaration decl) { return decl == loader().getDeclaration("ceylon.language.$true", DeclarationType.VALUE); } boolean isBooleanFalse(Declaration decl) { return decl == loader().getDeclaration("ceylon.language.$false", DeclarationType.VALUE); } // A type is optional when it is a union of Nothing|Type... public boolean isOptional(ProducedType type) { return typeFact().isOptionalType(type); } public boolean isNothing(ProducedType type) { return type.getSupertype(typeFact.getNothingDeclaration()) != null; } public boolean isVoid(ProducedType type) { return typeFact.getVoidDeclaration().getType().isExactly(type); } public boolean isObject(ProducedType type) { return typeFact.getObjectDeclaration().getType().isExactly(type); } protected ProducedType simplifyType(ProducedType type) { if (isOptional(type)) { // For an optional type T?: // - The Ceylon type T? results in the Java type T // Nasty cast because we just so happen to know that nothingType is a Class type = typeFact().getDefiniteType(type); } TypeDeclaration tdecl = type.getDeclaration(); if (tdecl instanceof UnionType && tdecl.getCaseTypes().size() == 1) { // Special case when the Union contains only a single CaseType // FIXME This is not correct! We might lose information about type arguments! type = tdecl.getCaseTypes().get(0); } else if (tdecl instanceof IntersectionType){ java.util.List<ProducedType> satisfiedTypes = tdecl.getSatisfiedTypes(); if(satisfiedTypes.size() == 1) { // Special case when the Intersection contains only a single SatisfiedType // FIXME This is not correct! We might lose information about type arguments! type = satisfiedTypes.get(0); }else if(satisfiedTypes.size() == 2){ // special case for T? simplified as T&Object if(isTypeParameter(satisfiedTypes.get(0)) && isObject(satisfiedTypes.get(1))) type = satisfiedTypes.get(0); } } return type; } protected ProducedType actualType(Tree.TypedDeclaration decl) { return decl.getType().getTypeModel(); } protected TypedDeclaration nonWideningTypeDecl(TypedDeclaration decl) { TypedDeclaration refinedDeclaration = (TypedDeclaration) decl.getRefinedDeclaration(); if(decl != refinedDeclaration){ /* * We are widening if the type: * - is not object * - is erased to object * - refines a declaration that is not erased to object */ boolean isWidening = !sameType(syms().ceylonObjectType, decl.getType()) && willEraseToObject(decl.getType()) && !willEraseToObject(refinedDeclaration.getType()); if(isWidening) return refinedDeclaration; } return decl; } protected ProducedType toPType(com.sun.tools.javac.code.Type t) { return loader().getType(t.tsym.getQualifiedName().toString(), null); } protected boolean sameType(Type t1, ProducedType t2) { return toPType(t1).isExactly(t2); } // Determines if a type will be erased to java.lang.Object once converted to Java protected boolean willEraseToObject(ProducedType type) { type = simplifyType(type); return (sameType(syms().ceylonVoidType, type) || sameType(syms().ceylonObjectType, type) || sameType(syms().ceylonNothingType, type) || sameType(syms().ceylonIdentifiableObjectType, type) || type.getDeclaration() instanceof BottomType || typeFact().isUnion(type)|| typeFact().isIntersection(type)); } protected boolean willEraseToException(ProducedType type) { type = simplifyType(type); return (sameType(syms().ceylonExceptionType, type)); } protected boolean isCeylonString(ProducedType type) { return (sameType(syms().ceylonStringType, type)); } protected boolean isCeylonBoolean(ProducedType type) { return type.isSubtypeOf(typeFact.getBooleanDeclaration().getType()) && !(type.getDeclaration() instanceof BottomType); } protected boolean isCeylonInteger(ProducedType type) { return (sameType(syms().ceylonIntegerType, type)); } protected boolean isCeylonFloat(ProducedType type) { return (sameType(syms().ceylonFloatType, type)); } protected boolean isCeylonCharacter(ProducedType type) { return (sameType(syms().ceylonCharacterType, type)); } protected boolean isCeylonArray(ProducedType type) { return (sameType(syms().ceylonArrayType, type.getDeclaration().getType())); } protected boolean isCeylonBasicType(ProducedType type) { return (isCeylonString(type) || isCeylonBoolean(type) || isCeylonInteger(type) || isCeylonFloat(type) || isCeylonCharacter(type)); } protected boolean isCeylonCallable(ProducedType type) { // FIXME This is ugly, we should find a proper way to do this! return type.getDeclaration().getType().getProducedTypeQualifiedName().startsWith("ceylon.language.Callable<"); } /* * Java Type creation */ static final int SATISFIES = 1 << 0; static final int EXTENDS = 1 << 1; static final int TYPE_ARGUMENT = 1 << 2; static final int NO_PRIMITIVES = 1 << 2; // Yes, same as TYPE_ARGUMENT static final int WANT_RAW_TYPE = 1 << 3; static final int CATCH = 1 << 4; static final int SMALL_TYPE = 1 << 5; static final int CLASS_NEW = 1 << 6; /** * This function is used solely for method return types and parameters */ protected JCExpression makeJavaType(TypedDeclaration typeDecl) { if (typeDecl instanceof FunctionalParameter) { FunctionalParameter p = (FunctionalParameter)typeDecl; return makeJavaType(typeFact().getCallableType(p.getType()), 0); } else { boolean usePrimitives = Util.isUnBoxed(typeDecl); return makeJavaType(typeDecl.getType(), usePrimitives ? 0 : AbstractTransformer.NO_PRIMITIVES); } } protected JCExpression makeJavaType(ProducedType producedType) { return makeJavaType(producedType, 0); } protected JCExpression makeJavaType(ProducedType type, int flags) { if(type == null) return make().Erroneous(); // ERASURE if (willEraseToObject(type)) { // For an erased type: // - Any of the Ceylon types Void, Object, Nothing, // IdentifiableObject, and Bottom result in the Java type Object // For any other union type U|V (U nor V is Optional): // - The Ceylon type U|V results in the Java type Object ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(type)); if (iterType != null) { // We special case the erasure of X[] and X[]? type = iterType; } else { if ((flags & SATISFIES) != 0) { return null; } else { return make().Type(syms().objectType); } } } else if (willEraseToException(type)) { if ((flags & CLASS_NEW) != 0 || (flags & EXTENDS) != 0) { return make().Type(syms().ceylonExceptionType); } else if ((flags & CATCH) != 0) { return make().Type(syms().exceptionType); } else { return make().Type(syms().throwableType); } } else if ((flags & (SATISFIES | EXTENDS | TYPE_ARGUMENT | CLASS_NEW)) == 0 && (!isOptional(type) || isJavaString(type))) { if (isCeylonString(type) || isJavaString(type)) { return make().Type(syms().stringType); } else if (isCeylonBoolean(type)) { return make().TypeIdent(TypeTags.BOOLEAN); } else if (isCeylonInteger(type)) { if ("byte".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.BYTE); } else if ("short".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.SHORT); } else if ((flags & SMALL_TYPE) != 0 || "int".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.INT); } else { return make().TypeIdent(TypeTags.LONG); } } else if (isCeylonFloat(type)) { if ((flags & SMALL_TYPE) != 0 || "float".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.FLOAT); } else { return make().TypeIdent(TypeTags.DOUBLE); } } else if (isCeylonCharacter(type)) { if ("char".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.CHAR); } else { return make().TypeIdent(TypeTags.INT); } } - }else if(isCeylonBoolean(type)){ + }else if(isCeylonBoolean(type) + && (flags & TYPE_ARGUMENT) == 0){ // special case to get rid of $true and $false types type = typeFact.getBooleanDeclaration().getType(); } JCExpression jt = makeErroneous(); ProducedType simpleType = simplifyType(type); java.util.List<ProducedType> qualifyingTypes = new java.util.ArrayList<ProducedType>(); java.util.List<TypeParameter> qualifyingTypeParameters = new java.util.ArrayList<TypeParameter>(); java.util.Map<TypeParameter, ProducedType> qualifyingTypeArguments = new java.util.HashMap<TypeParameter, ProducedType>(); ProducedType qType = simpleType; while (qType != null) { qualifyingTypes.add(qType); Map<TypeParameter, ProducedType> tas = qType.getTypeArguments(); java.util.List<TypeParameter> tps = qType.getDeclaration().getTypeParameters(); if (tps != null) { qualifyingTypeParameters.addAll(tps); qualifyingTypeArguments.putAll(tas); } qType = qType.getQualifyingType(); } if (simpleType.getDeclaration() instanceof Interface && ((flags & WANT_RAW_TYPE) == 0) && !qualifyingTypeParameters.isEmpty()) { Collections.reverse(qualifyingTypes); JCExpression baseType = makeErroneous(); TypeDeclaration tdecl = simpleType.getDeclaration(); ListBuffer<JCExpression> typeArgs = makeTypeArgs(isCeylonCallable(simpleType), flags, qualifyingTypeArguments, qualifyingTypeParameters); if (isCeylonCallable(type) && (flags & CLASS_NEW) != 0) { baseType = makeIdent(syms().ceylonAbstractCallableType); } else { baseType = getDeclarationName(tdecl); } if (typeArgs != null && typeArgs.size() > 0) { jt = make().TypeApply(baseType, typeArgs.toList()); } else { jt = baseType; } } else if (((flags & WANT_RAW_TYPE) == 0) && !qualifyingTypeParameters.isEmpty()) { // GENERIC TYPES Collections.reverse(qualifyingTypes); JCExpression baseType = makeErroneous(); boolean first = true; for (ProducedType qualifyingType : qualifyingTypes) { TypeDeclaration tdecl = qualifyingType.getDeclaration(); ListBuffer<JCExpression> typeArgs = makeTypeArgs( qualifyingType, //tdecl, flags); if (isCeylonCallable(type) && (flags & CLASS_NEW) != 0) { baseType = makeIdent(syms().ceylonAbstractCallableType); } else if (first) { String name = getFQDeclarationName(tdecl); if (tdecl instanceof Interface) { name = Util.getCompanionClassName(name); } baseType = makeQuotedQualIdentFromString(name); } else { baseType = makeSelect(jt, tdecl.getName()); } if (typeArgs != null && typeArgs.size() > 0) { jt = make().TypeApply(baseType, typeArgs.toList()); } else { jt = baseType; } if (first) { first = false; } } } else { TypeDeclaration tdecl = simpleType.getDeclaration(); // For an ordinary class or interface type T: // - The Ceylon type T results in the Java type T if(tdecl instanceof TypeParameter) jt = makeQuotedIdent(tdecl.getName()); // don't use underlying type if we want no primitives else if((flags & (SATISFIES | NO_PRIMITIVES)) != 0 || simpleType.getUnderlyingType() == null) jt = getDeclarationName(tdecl); else jt = makeQuotedFQIdent(simpleType.getUnderlyingType()); } return jt; } private ListBuffer<JCExpression> makeTypeArgs( ProducedType simpleType, int flags) { Map<TypeParameter, ProducedType> tas = simpleType.getTypeArguments(); java.util.List<TypeParameter> tps = simpleType.getDeclaration().getTypeParameters(); return makeTypeArgs(isCeylonCallable(simpleType), flags, tas, tps); } private ListBuffer<JCExpression> makeTypeArgs(boolean isCeylonCallable, int flags, Map<TypeParameter, ProducedType> tas, java.util.List<TypeParameter> tps) { ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>(); int idx = 0; for (TypeParameter tp : tps) { ProducedType ta = tas.get(tp); if (idx > 0 && isCeylonCallable) { // In the runtime Callable only has a single type param break; } if (isOptional(ta)) { // For an optional type T?: // - The Ceylon type Foo<T?> results in the Java type Foo<T>. ta = typeFact().getDefiniteType(ta); } if (typeFact().isUnion(ta) || typeFact().isIntersection(ta)) { // For any other union type U|V (U nor V is Optional): // - The Ceylon type Foo<U|V> results in the raw Java type Foo. // For any other intersection type U|V: // - The Ceylon type Foo<U&V> results in the raw Java type Foo. // A bit ugly, but we need to escape from the loop and create a raw type, no generics ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(ta)); // don't break if the union type is erased to something better than Object if(iterType == null){ typeArgs = null; break; }else ta = iterType; } JCExpression jta; if (sameType(syms().ceylonVoidType, ta)) { // For the root type Void: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<Void> appearing in an extends or satisfies // clause results in the Java raw type Foo<Object> jta = make().Type(syms().objectType); } else { // - The Ceylon type Foo<Void> appearing anywhere else results in the Java type // - Foo<Object> if Foo<T> is invariant in T // - Foo<?> if Foo<T> is covariant in T, or // - Foo<Object> if Foo<T> is contravariant in T if (tp.isContravariant()) { jta = make().Type(syms().objectType); } else if (tp.isCovariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta, flags)); } else { jta = make().Type(syms().objectType); } } } else if (ta.getDeclaration() instanceof BottomType) { // For the bottom type Bottom: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<Bottom> appearing in an extends or satisfies // clause results in the Java raw type Foo // A bit ugly, but we need to escape from the loop and create a raw type, no generics typeArgs = null; break; } else { // - The Ceylon type Foo<Bottom> appearing anywhere else results in the Java type // - raw Foo if Foo<T> is invariant in T, // - raw Foo if Foo<T> is covariant in T, or // - Foo<?> if Foo<T> is contravariant in T if (tp.isContravariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.UNBOUND), makeJavaType(ta)); } else { // A bit ugly, but we need to escape from the loop and create a raw type, no generics typeArgs = null; break; } } } else { // For an ordinary class or interface type T: if ((flags & (SATISFIES | EXTENDS)) != 0) { // - The Ceylon type Foo<T> appearing in an extends or satisfies clause // results in the Java type Foo<T> jta = makeJavaType(ta, TYPE_ARGUMENT); } else { // - The Ceylon type Foo<T> appearing anywhere else results in the Java type // - Foo<T> if Foo is invariant in T, // - Foo<? extends T> if Foo is covariant in T, or // - Foo<? super T> if Foo is contravariant in T if (((flags & CLASS_NEW) == 0) && tp.isContravariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.SUPER), makeJavaType(ta, TYPE_ARGUMENT)); } else if (((flags & CLASS_NEW) == 0) && tp.isCovariant()) { jta = make().Wildcard(make().TypeBoundKind(BoundKind.EXTENDS), makeJavaType(ta, TYPE_ARGUMENT)); } else { jta = makeJavaType(ta, TYPE_ARGUMENT); } } } typeArgs.add(jta); idx++; } return typeArgs; } private boolean isJavaString(ProducedType type) { return "java.lang.String".equals(type.getUnderlyingType()); } protected String getFQDeclarationName(Declaration decl) { /*while (decl instanceof TypeDeclaration && ((TypeDeclaration) decl).getType().getQualifyingType() != null) { decl = ((TypeDeclaration) decl).getType().getQualifyingType().getDeclaration(); String parentName = getFQDeclarationName(decl); if (decl instanceof Interface) { return parentName + "$" + decl.getName(); } else { return parentName + "." + decl.getName(); } } */ if (!decl.isToplevel()) { StringBuilder sb = new StringBuilder(); Scope container; if (decl instanceof Class && decl.getContainer() instanceof Interface) { Interface parent = (Interface)decl.getContainer(); sb.append(Util.getCompanionClassName(parent.getName())+"." + decl.getName()); container = decl.getContainer().getContainer(); } else { sb.append(decl.getName()); container = decl.getContainer(); } while (container != null) { if (container instanceof Package) { sb.insert(0, '.'); sb.insert(0, container.getQualifiedNameString()); sb.insert(0, '.'); break; } else if (container instanceof TypeDeclaration){ sb.insert(0, decl instanceof Interface ? '$' : "."); sb.insert(0, ((TypeDeclaration)container).getName()); } else { // TODO Handle local interfaces throw new RuntimeException(); } container = container.getContainer(); } return sb.toString(); } else if (Decl.isAncestorLocal(decl)) { return decl.getName(); } else { return "."+decl.getQualifiedNameString(); } } protected JCExpression getDeclarationName(Declaration decl) { return makeQuotedQualIdentFromString(getFQDeclarationName(decl)); } protected ProducedType getThisType(Tree.Declaration decl) { if (decl instanceof Tree.TypeDeclaration) { return getThisType(((Tree.TypeDeclaration)decl).getDeclarationModel()); } else { return getThisType(((Tree.TypedDeclaration)decl).getDeclarationModel()); } } protected ProducedType getThisType(Declaration decl) { ProducedType thisType; if (decl instanceof ClassOrInterface) { thisType = ((ClassOrInterface)decl).getType(); } else if (decl.isToplevel()) { thisType = ((TypedDeclaration)decl).getType(); } else { thisType = getThisType((Declaration)decl.getContainer()); } return thisType; } /** * Gets the first type parameter from the type model representing a * ceylon.language.Callable<Result, ParameterTypes...>. * @param typeModel * @return The result type of the Callable. */ protected ProducedType getCallableReturnType(ProducedType typeModel) { assert isCeylonCallable(typeModel); return typeModel.getTypeArgumentList().get(0); } /** * Gets the first type parameter from the type model representing a * ceylon.language.Array<Element>. * @param typeModel * @return The component type of the Array. */ protected ProducedType getArrayComponentType(ProducedType typeModel) { assert isCeylonArray(typeModel); return typeModel.getTypeArgumentList().get(0); } protected ProducedType getTypeForParameter(Parameter parameter, boolean isRaw, java.util.List<ProducedType> typeArgumentModels) { if (parameter instanceof FunctionalParameter) { FunctionalParameter fp = (FunctionalParameter)parameter; java.util.List<ProducedType> typeArgs = new ArrayList<ProducedType>(fp.getTypeParameters().size()); typeArgs.add(fp.getType()); for (TypeParameter typeParameter : fp.getTypeParameters()) { typeArgs.add(typeParameter.getType()); } return typeFact().getCallableType(typeArgs); } ProducedType type = parameter.getType(); if(isTypeParameter(type)){ // TODO This ^^ and this vv is ugly because it doesn't handle unions or intersections properly TypeParameter tp = getTypeParameter(type); if(!isRaw && typeArgumentModels != null){ // try to use the inferred type if we're not going raw Scope scope = parameter.getContainer(); int typeParamIndex = getTypeParameterIndex(scope, tp); if(typeParamIndex != -1) return typeArgumentModels.get(typeParamIndex); } if(tp.getSatisfiedTypes().size() >= 1){ // try the first satisfied type type = tp.getSatisfiedTypes().get(0).getType(); // unless it's erased, in which case try for more specific if(!willEraseToObject(type)) return type; } } return type; } private int getTypeParameterIndex(Scope scope, TypeParameter tp) { if(scope instanceof Method) return ((Method)scope).getTypeParameters().indexOf(tp); return ((ClassOrInterface)scope).getTypeParameters().indexOf(tp); } /* * Annotation generation */ List<JCAnnotation> makeAtOverride() { return List.<JCAnnotation> of(make().Annotation(makeIdent(syms().overrideType), List.<JCExpression> nil())); } // FIXME public static boolean disableModelAnnotations = false; public boolean checkCompilerAnnotations(Tree.Declaration decl){ boolean old = disableModelAnnotations; if(Util.hasCompilerAnnotation(decl, "nomodel")) disableModelAnnotations = true; return old; } public void resetCompilerAnnotations(boolean value){ disableModelAnnotations = value; } private List<JCAnnotation> makeModelAnnotation(Type annotationType, List<JCExpression> annotationArgs) { if (disableModelAnnotations) return List.nil(); return List.of(make().Annotation(makeIdent(annotationType), annotationArgs)); } private List<JCAnnotation> makeModelAnnotation(Type annotationType) { return makeModelAnnotation(annotationType, List.<JCExpression>nil()); } protected List<JCAnnotation> makeAtCeylon() { return makeModelAnnotation(syms().ceylonAtCeylonType); } protected List<JCAnnotation> makeAtModule(Module module) { String name = module.getNameAsString(); String version = module.getVersion(); java.util.List<ModuleImport> dependencies = module.getImports(); ListBuffer<JCExpression> imports = new ListBuffer<JCTree.JCExpression>(); for(ModuleImport dependency : dependencies){ Module dependencyModule = dependency.getModule(); // do not include the implicit java module as a dependency if(dependencyModule.getNameAsString().equals("java") // nor ceylon.language || dependencyModule.getNameAsString().equals("ceylon.language")) continue; JCExpression dependencyName = make().Assign(makeUnquotedIdent("name"), make().Literal(dependencyModule.getNameAsString())); JCExpression dependencyVersion = null; if(dependencyModule.getVersion() != null) dependencyVersion = make().Assign(makeUnquotedIdent("version"), make().Literal(dependencyModule.getVersion())); List<JCExpression> spec; if(dependencyVersion != null) spec = List.<JCExpression>of(dependencyName, dependencyVersion); else spec = List.<JCExpression>of(dependencyName); JCAnnotation atImport = make().Annotation(makeIdent(syms().ceylonAtImportType), spec); // TODO : add the export & optional annotations also ? imports.add(atImport); } JCExpression nameAttribute = make().Assign(makeUnquotedIdent("name"), make().Literal(name)); JCExpression versionAttribute = make().Assign(makeUnquotedIdent("version"), make().Literal(version)); JCExpression importAttribute = make().Assign(makeUnquotedIdent("dependencies"), make().NewArray(null, null, imports.toList())); return makeModelAnnotation(syms().ceylonAtModuleType, List.<JCExpression>of(nameAttribute, versionAttribute, importAttribute)); } protected List<JCAnnotation> makeAtPackage(Package pkg) { String name = pkg.getNameAsString(); boolean shared = pkg.isShared(); JCExpression nameAttribute = make().Assign(makeUnquotedIdent("name"), make().Literal(name)); JCExpression sharedAttribute = make().Assign(makeUnquotedIdent("shared"), makeBoolean(shared)); return makeModelAnnotation(syms().ceylonAtPackageType, List.<JCExpression>of(nameAttribute, sharedAttribute)); } protected List<JCAnnotation> makeAtName(String name) { return makeModelAnnotation(syms().ceylonAtNameType, List.<JCExpression>of(make().Literal(name))); } protected List<JCAnnotation> makeAtType(String name) { return makeModelAnnotation(syms().ceylonAtTypeInfoType, List.<JCExpression>of(make().Literal(name))); } public final JCAnnotation makeAtTypeParameter(String name, java.util.List<ProducedType> satisfiedTypes, boolean covariant, boolean contravariant) { JCExpression nameAttribute = make().Assign(makeUnquotedIdent("value"), make().Literal(name)); // variance String variance = "NONE"; if(covariant) variance = "OUT"; else if(contravariant) variance = "IN"; JCExpression varianceAttribute = make().Assign(makeUnquotedIdent("variance"), make().Select(makeIdent(syms().ceylonVarianceType), names().fromString(variance))); // upper bounds ListBuffer<JCExpression> upperBounds = new ListBuffer<JCTree.JCExpression>(); for(ProducedType satisfiedType : satisfiedTypes){ String type = serialiseTypeSignature(satisfiedType); upperBounds.append(make().Literal(type)); } JCExpression satisfiesAttribute = make().Assign(makeUnquotedIdent("satisfies"), make().NewArray(null, null, upperBounds.toList())); // all done return make().Annotation(makeIdent(syms().ceylonAtTypeParameter), List.<JCExpression>of(nameAttribute, varianceAttribute, satisfiesAttribute)); } public List<JCAnnotation> makeAtTypeParameters(List<JCExpression> typeParameters) { JCExpression value = make().NewArray(null, null, typeParameters); return makeModelAnnotation(syms().ceylonAtTypeParameters, List.of(value)); } protected List<JCAnnotation> makeAtSequenced() { return makeModelAnnotation(syms().ceylonAtSequencedType); } protected List<JCAnnotation> makeAtDefaulted() { return makeModelAnnotation(syms().ceylonAtDefaultedType); } protected List<JCAnnotation> makeAtAttribute() { return makeModelAnnotation(syms().ceylonAtAttributeType); } protected List<JCAnnotation> makeAtMethod() { return makeModelAnnotation(syms().ceylonAtMethodType); } protected List<JCAnnotation> makeAtObject() { return makeModelAnnotation(syms().ceylonAtObjectType); } protected List<JCAnnotation> makeAtClass(ProducedType extendedType) { List<JCExpression> attributes = List.nil(); if(!extendedType.isExactly(typeFact.getIdentifiableObjectDeclaration().getType())){ JCExpression extendsAttribute = make().Assign(makeUnquotedIdent("extendsType"), make().Literal(serialiseTypeSignature(extendedType))); attributes = attributes.prepend(extendsAttribute); } return makeModelAnnotation(syms().ceylonAtClassType, attributes); } protected List<JCAnnotation> makeAtSatisfiedTypes(java.util.List<ProducedType> satisfiedTypes) { return makeTypesListAnnotation(syms().ceylonAtSatisfiedTypes, satisfiedTypes); } protected List<JCAnnotation> makeAtCaseTypes(java.util.List<ProducedType> caseTypes) { return makeTypesListAnnotation(syms().ceylonAtCaseTypes, caseTypes); } private List<JCAnnotation> makeTypesListAnnotation(Type annotationType, java.util.List<ProducedType> types) { if(types.isEmpty()) return List.nil(); ListBuffer<JCExpression> upperBounds = new ListBuffer<JCTree.JCExpression>(); for(ProducedType type : types){ String typeSig = serialiseTypeSignature(type); upperBounds.append(make().Literal(typeSig)); } JCExpression caseAttribute = make().Assign(makeUnquotedIdent("value"), make().NewArray(null, null, upperBounds.toList())); return makeModelAnnotation(annotationType, List.of(caseAttribute)); } protected List<JCAnnotation> makeAtIgnore() { return makeModelAnnotation(syms().ceylonAtIgnore); } protected List<JCAnnotation> makeAtAnnotations(java.util.List<Annotation> annotations) { if(annotations == null || annotations.isEmpty()) return List.nil(); ListBuffer<JCExpression> array = new ListBuffer<JCTree.JCExpression>(); for(Annotation annotation : annotations){ array.append(makeAtAnnotation(annotation)); } JCExpression annotationsAttribute = make().Assign(makeUnquotedIdent("value"), make().NewArray(null, null, array.toList())); return makeModelAnnotation(syms().ceylonAtAnnotationsType, List.of(annotationsAttribute)); } private JCExpression makeAtAnnotation(Annotation annotation) { JCExpression valueAttribute = make().Assign(makeUnquotedIdent("value"), make().Literal(annotation.getName())); List<JCExpression> attributes; if(!annotation.getPositionalArguments().isEmpty()){ java.util.List<String> positionalArguments = annotation.getPositionalArguments(); ListBuffer<JCExpression> array = new ListBuffer<JCTree.JCExpression>(); for(String val : positionalArguments) array.add(make().Literal(val)); JCExpression argumentsAttribute = make().Assign(makeUnquotedIdent("arguments"), make().NewArray(null, null, array.toList())); attributes = List.of(valueAttribute, argumentsAttribute); }else if(!annotation.getNamedArguments().isEmpty()){ Map<String, String> namedArguments = annotation.getNamedArguments(); ListBuffer<JCExpression> array = new ListBuffer<JCTree.JCExpression>(); for(Entry<String, String> entry : namedArguments.entrySet()){ JCExpression argNameAttribute = make().Assign(makeUnquotedIdent("name"), make().Literal(entry.getKey())); JCExpression argValueAttribute = make().Assign(makeUnquotedIdent("value"), make().Literal(entry.getValue())); JCAnnotation namedArg = make().Annotation(makeIdent(syms().ceylonAtNamedArgumentType), List.of(argNameAttribute, argValueAttribute)); array.add(namedArg); } JCExpression argumentsAttribute = make().Assign(makeUnquotedIdent("namedArguments"), make().NewArray(null, null, array.toList())); attributes = List.of(valueAttribute, argumentsAttribute); }else attributes = List.of(valueAttribute); return make().Annotation(makeIdent(syms().ceylonAtAnnotationType), attributes); } protected boolean needsAnnotations(Declaration decl) { Declaration reqdecl = decl; if (reqdecl instanceof Parameter) { Parameter p = (Parameter)reqdecl; reqdecl = p.getDeclaration(); } return reqdecl.isToplevel() || (reqdecl.isClassOrInterfaceMember() && reqdecl.isShared() && !Decl.isAncestorLocal(reqdecl)); } protected List<JCTree.JCAnnotation> makeJavaTypeAnnotations(TypedDeclaration decl) { if(decl == null || decl.getType() == null) return List.nil(); ProducedType type; if (decl instanceof FunctionalParameter) { type = getTypeForParameter((Parameter)decl, false, Collections.<ProducedType>emptyList()); } else { type = decl.getType(); } return makeJavaTypeAnnotations(type, needsAnnotations(decl)); } protected List<JCTree.JCAnnotation> makeJavaTypeAnnotations(ProducedType type, boolean required) { if (!required) return List.nil(); // Add the original type to the annotations return makeAtType(serialiseTypeSignature(type)); } protected String serialiseTypeSignature(ProducedType type){ if(isTypeParameter(type)) return type.getProducedTypeName(); return type.getProducedTypeQualifiedName(); } /* * Boxing */ public enum BoxingStrategy { UNBOXED, BOXED, INDIFFERENT; } protected JCExpression boxUnboxIfNecessary(JCExpression javaExpr, Tree.Term expr, ProducedType exprType, BoxingStrategy boxingStrategy) { boolean exprBoxed = !Util.isUnBoxed(expr); return boxUnboxIfNecessary(javaExpr, exprBoxed, exprType, boxingStrategy); } protected JCExpression boxUnboxIfNecessary(JCExpression javaExpr, boolean exprBoxed, ProducedType exprType, BoxingStrategy boxingStrategy) { if(boxingStrategy == BoxingStrategy.INDIFFERENT) return javaExpr; boolean targetBoxed = boxingStrategy == BoxingStrategy.BOXED; // only box if the two differ if(targetBoxed == exprBoxed) return javaExpr; if (targetBoxed) { // box javaExpr = boxType(javaExpr, exprType); } else { // unbox javaExpr = unboxType(javaExpr, exprType); } return javaExpr; } protected TypeParameter getTypeParameter(ProducedType type) { if (typeFact().isOptionalType(type)) { type = type.minus(typeFact().getNothingDeclaration()); } return (TypeParameter)type.getDeclaration(); } protected boolean isTypeParameter(ProducedType type) { if (typeFact().isOptionalType(type)) { type = type.minus(typeFact().getNothingDeclaration()); } return type.getDeclaration() instanceof TypeParameter; } protected JCExpression unboxType(JCExpression expr, ProducedType targetType) { if (isCeylonInteger(targetType)) { expr = unboxInteger(expr); } else if (isCeylonFloat(targetType)) { expr = unboxFloat(expr); } else if (isCeylonString(targetType)) { expr = unboxString(expr); } else if (isCeylonCharacter(targetType)) { boolean isJavaCharacter = targetType.getUnderlyingType() != null; expr = unboxCharacter(expr, isJavaCharacter); } else if (isCeylonBoolean(targetType)) { expr = unboxBoolean(expr); } else if (isCeylonArray(targetType)) { expr = unboxArray(expr); } return expr; } protected JCExpression boxType(JCExpression expr, ProducedType exprType) { if (isCeylonInteger(exprType)) { expr = boxInteger(expr); } else if (isCeylonFloat(exprType)) { expr = boxFloat(expr); } else if (isCeylonString(exprType)) { expr = boxString(expr); } else if (isCeylonCharacter(exprType)) { expr = boxCharacter(expr); } else if (isCeylonBoolean(exprType)) { expr = boxBoolean(expr); } else if (isCeylonArray(exprType)) { expr = boxArray(expr); } return expr; } private JCTree.JCMethodInvocation boxInteger(JCExpression value) { return makeBoxType(value, syms().ceylonIntegerType); } private JCTree.JCMethodInvocation boxFloat(JCExpression value) { return makeBoxType(value, syms().ceylonFloatType); } private JCTree.JCMethodInvocation boxString(JCExpression value) { return makeBoxType(value, syms().ceylonStringType); } private JCTree.JCMethodInvocation boxCharacter(JCExpression value) { return makeBoxType(value, syms().ceylonCharacterType); } private JCTree.JCMethodInvocation boxBoolean(JCExpression value) { return makeBoxType(value, syms().ceylonBooleanType); } private JCTree.JCMethodInvocation boxArray(JCExpression value) { return makeBoxType(value, syms().ceylonArrayType); } private JCTree.JCMethodInvocation makeBoxType(JCExpression value, Type type) { return make().Apply(null, makeSelect(makeIdent(type), "instance"), List.<JCExpression>of(value)); } private JCTree.JCMethodInvocation unboxInteger(JCExpression value) { return makeUnboxType(value, "longValue"); } private JCTree.JCMethodInvocation unboxFloat(JCExpression value) { return makeUnboxType(value, "doubleValue"); } private JCTree.JCMethodInvocation unboxString(JCExpression value) { return makeUnboxType(value, "toString"); } private JCTree.JCMethodInvocation unboxCharacter(JCExpression value, boolean isJava) { return makeUnboxType(value, isJava ? "charValue" : "intValue"); } private JCTree.JCMethodInvocation unboxBoolean(JCExpression value) { return makeUnboxType(value, "booleanValue"); } private JCTree.JCMethodInvocation unboxArray(JCExpression value) { return makeUnboxType(value, "toArray"); } private JCTree.JCMethodInvocation makeUnboxType(JCExpression value, String unboxMethodName) { return make().Apply(null, makeSelect(value, unboxMethodName), List.<JCExpression>nil()); } protected ProducedType determineExpressionType(Tree.Expression expr) { return determineExpressionType(expr.getTerm()); } protected ProducedType determineExpressionType(Tree.Term term) { ProducedType exprType = term.getTypeModel(); if (term instanceof Tree.InvocationExpression) { Tree.InvocationExpression invocation = (Tree.InvocationExpression)term; Tree.MemberOrTypeExpression primary = (Tree.MemberOrTypeExpression)invocation.getPrimary(); Declaration decl = primary.getDeclaration().getRefinedDeclaration(); if (decl instanceof Method) { exprType = ((Method)decl).getType(); } } return exprType; } /* * Sequences */ /** * Returns a JCExpression along the lines of * {@code new ArraySequence<seqElemType>(list...)} * @param elems The elements in the sequence * @param seqElemType The sequence type parameter * @param makeJavaTypeOpts The option flags to pass to makeJavaType(). * @return a JCExpression * @see #makeSequenceRaw(java.util.List) */ protected JCExpression makeSequence(List<JCExpression> elems, ProducedType seqElemType, int makeJavaTypeOpts) { ProducedType seqType = typeFact().getDefaultSequenceType(seqElemType); JCExpression typeExpr = makeJavaType(seqType, makeJavaTypeOpts); return makeNewClass(typeExpr, elems); } /** * Returns a JCExpression along the lines of * {@code new ArraySequence<seqElemType>(list...)} * @param list The elements in the sequence * @param seqElemType The sequence type parameter * @return a JCExpression * @see #makeSequenceRaw(java.util.List) */ protected JCExpression makeSequence(java.util.List<Expression> list, ProducedType seqElemType) { ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>(); for (Expression expr : list) { // no need for erasure casts here elems.append(expressionGen().transformExpression(expr)); } return makeSequence(elems.toList(), seqElemType,CeylonTransformer.TYPE_ARGUMENT); } /** * Returns a JCExpression along the lines of * {@code new ArraySequence(list...)} * @param list The elements in the sequence * @return a JCExpression * @see #makeSequence(java.util.List, ProducedType) */ protected JCExpression makeSequenceRaw(java.util.List<Expression> list) { ListBuffer<JCExpression> elems = new ListBuffer<JCExpression>(); for (Expression expr : list) { // no need for erasure casts here elems.append(expressionGen().transformExpression(expr)); } return makeSequence(elems.toList(), typeFact().getObjectDeclaration().getType(), CeylonTransformer.WANT_RAW_TYPE); } protected JCExpression makeSequenceRaw(List<JCExpression> elems) { return makeSequence(elems, typeFact().getObjectDeclaration().getType(), CeylonTransformer.WANT_RAW_TYPE); } protected JCExpression makeEmpty() { return make().Apply( List.<JCTree.JCExpression>nil(), makeFQIdent("ceylon", "language", "$empty", Util.getGetterName("$empty")), List.<JCTree.JCExpression>nil()); } protected JCExpression makeFinished() { return make().Apply( List.<JCTree.JCExpression>nil(), makeFQIdent("ceylon", "language", "$finished", Util.getGetterName("$finished")), List.<JCTree.JCExpression>nil()); } /* * Variable name substitution */ @SuppressWarnings("serial") protected static class VarMapper extends HashMap<String, String> { } private Map<String, String> getVarMapper() { VarMapper map = context.get(VarMapper.class); if (map == null) { map = new VarMapper(); context.put(VarMapper.class, map); } return map; } String addVariableSubst(String origVarName, String substVarName) { return getVarMapper().put(origVarName, substVarName); } void removeVariableSubst(String origVarName, String prevSubst) { if (prevSubst != null) { getVarMapper().put(origVarName, prevSubst); } else { getVarMapper().remove(origVarName); } } /* * Checks a global map of variable name substitutions and returns * either the original name if none was found or the substitute. */ String substitute(String varName) { if (getVarMapper().containsKey(varName)) { return getVarMapper().get(varName); } else { return varName; } } // Creates comparisons of expressions against types protected JCExpression makeTypeTest(JCExpression firstTimeExpr, String varName, ProducedType type) { JCExpression result = null; if (typeFact().isUnion(type)) { UnionType union = (UnionType)type.getDeclaration(); for (ProducedType pt : union.getCaseTypes()) { JCExpression partExpr = makeTypeTest(firstTimeExpr, varName, pt); firstTimeExpr = null; if (result == null) { result = partExpr; } else { result = make().Binary(JCTree.OR, result, partExpr); } } } else if (typeFact().isIntersection(type)) { IntersectionType union = (IntersectionType)type.getDeclaration(); for (ProducedType pt : union.getSatisfiedTypes()) { JCExpression partExpr = makeTypeTest(firstTimeExpr, varName, pt); firstTimeExpr = null; if (result == null) { result = partExpr; } else { result = make().Binary(JCTree.AND, result, partExpr); } } } else { JCExpression varExpr = firstTimeExpr != null ? firstTimeExpr : makeUnquotedIdent(varName); if (type.isExactly(typeFact().getNothingDeclaration().getType())){ // is Nothing => is null return make().Binary(JCTree.EQ, varExpr, makeNull()); } else if (type.isExactly(typeFact().getObjectDeclaration().getType())){ // is Object => is not null return make().Binary(JCTree.NE, varExpr, makeNull()); } else if (isVoid(type)){ // everything is Void, it's the root of the hierarchy return makeIgnoredEvalAndReturn(varExpr, makeBoolean(true)); } else if (type.isExactly(typeFact().getObjectDeclaration().getType())){ // it's erased return makeUtilInvocation("isEquality", List.of(varExpr)); } else if (type.isExactly(typeFact().getIdentifiableObjectDeclaration().getType())){ // it's erased return makeUtilInvocation("isIdentifiableObject", List.of(varExpr)); } else if (type.getDeclaration() instanceof BottomType){ // nothing is Bottom return makeIgnoredEvalAndReturn(varExpr, makeBoolean(false)); } else { JCExpression rawTypeExpr = makeJavaType(type, NO_PRIMITIVES | WANT_RAW_TYPE); result = make().TypeTest(varExpr, rawTypeExpr); } } return result; } protected JCExpression makeNonEmptyTest(JCExpression firstTimeExpr, String varName) { Interface fixedSize = typeFact().getFixedSizedDeclaration(); JCExpression test = makeTypeTest(firstTimeExpr, varName, fixedSize.getType()); JCExpression fixedSizeType = makeJavaType(fixedSize.getType(), NO_PRIMITIVES | WANT_RAW_TYPE); JCExpression nonEmpty = makeNonEmptyTest(make().TypeCast(fixedSizeType, makeUnquotedIdent(varName))); return make().Binary(JCTree.AND, test, nonEmpty); } protected JCExpression makeNonEmptyTest(JCExpression expr){ JCExpression getEmptyCall = make().Select(expr, names().fromString("getEmpty")); JCExpression empty = make().Apply(List.<JCExpression>nil(), getEmptyCall, List.<JCExpression>nil()); return make().Unary(JCTree.NOT, empty); } /** * Invokes a static method of the Util helper class * @param methodName name of the method * @param params parameters * @return the invocation AST */ protected JCExpression makeUtilInvocation(String methodName, List<JCExpression> params) { return make().Apply(null, make().Select(make().QualIdent(syms().ceylonUtilType.tsym), names().fromString(methodName)), params); } protected LetExpr makeIgnoredEvalAndReturn(JCExpression toEval, JCExpression toReturn){ // define a variable of type j.l.Object to hold the result of the evaluation JCVariableDecl def = makeVar(tempName(), make().Type(syms().objectType), toEval); // then ignore this result and return something else return make().LetExpr(def, toReturn); } protected JCExpression makeErroneous() { return makeErroneous(null); } /** * Makes an 'erroneous' AST node with no message */ protected JCExpression makeErroneous(Node node) { return makeErroneous(node, null, List.<JCTree>nil()); } /** * Makes an 'erroneous' AST node with a message to be logged as an error */ protected JCExpression makeErroneous(Node node, String message) { return makeErroneous(node, message, List.<JCTree>nil()); } /** * Makes an 'erroneous' AST node with a message to be logged as an error */ protected JCExpression makeErroneous(Node node, String message, List<? extends JCTree> errs) { if (node != null) { at(node); } if (message != null) { if (node != null) { log.error(getPosition(node), "ceylon", message); } else { log.error("ceylon", message); } } return make().Erroneous(errs); } public JCTypeParameter makeTypeParameter(String name, java.util.List<ProducedType> satisfiedTypes, boolean covariant, boolean contravariant) { ListBuffer<JCExpression> bounds = new ListBuffer<JCExpression>(); for (ProducedType t : satisfiedTypes) { if (!willEraseToObject(t)) { bounds.append(makeJavaType(t, AbstractTransformer.NO_PRIMITIVES)); } } return make().TypeParameter(names().fromString(name), bounds.toList()); } public JCTypeParameter makeTypeParameter(TypeParameter declarationModel) { return makeTypeParameter(declarationModel.getName(), declarationModel.getSatisfiedTypes(), declarationModel.isCovariant(), declarationModel.isContravariant()); } public JCTypeParameter makeTypeParameter(Tree.TypeParameterDeclaration param) { at(param); return makeTypeParameter(param.getDeclarationModel()); } public JCAnnotation makeAtTypeParameter(TypeParameter declarationModel) { return makeAtTypeParameter(declarationModel.getName(), declarationModel.getSatisfiedTypes(), declarationModel.isCovariant(), declarationModel.isContravariant()); } public JCAnnotation makeAtTypeParameter(Tree.TypeParameterDeclaration param) { at(param); return makeAtTypeParameter(param.getDeclarationModel()); } public final List<JCExpression> typeParams(Method method) { return typeParams(method.getTypeParameters()); } public final List<JCExpression> typeParams(ClassOrInterface type) { return typeParams(type.getTypeParameters()); } public final List<JCExpression> typeParams(Iterable<TypeParameter> typeParams) { ListBuffer<JCExpression> typeArgs = ListBuffer.<JCExpression>lb(); for (TypeParameter tp : typeParams) { typeArgs.append(makeQuotedIdent(tp.getName())); } return typeArgs.toList(); } public final String getCompanionFieldName(Interface def) { return "$" + Util.getCompanionClassName(def.getName()); } public final JCExpression makeDefaultedParamMethodIdent(Method method, Parameter param) { Interface iface = (Interface)method.getRefinedDeclaration().getContainer(); return makeQuotedQualIdent(makeQuotedIdent(getCompanionFieldName(iface)), Util.getDefaultedParamMethodName(method, param)); } public final JCExpression makeCompanionType(final ClassOrInterface decl) { return makeCompanionType(decl, decl.getTypeParameters()); } public final JCExpression makeCompanionType(final ClassOrInterface decl, Iterable<TypeParameter> typeParameters) { List<JCExpression> typeArgs = typeParams(typeParameters); return makeCompanionType(decl, typeArgs); } public final JCExpression makeCompanionType(final ClassOrInterface decl, List<JCExpression> typeArgs) { String companionClassName = Util.getCompanionClassName(decl.getQualifiedNameString()); JCExpression baseName = makeQuotedFQIdent(companionClassName); if (!typeArgs.isEmpty()) { return make().TypeApply(baseName, typeArgs); } return baseName; } private int getPosition(Node node) { int pos = getMap().getStartPosition(node.getToken().getLine()) + node.getToken().getCharPositionInLine(); log.useSource(gen().getFileObject()); return pos; } }
true
true
protected JCExpression makeJavaType(ProducedType type, int flags) { if(type == null) return make().Erroneous(); // ERASURE if (willEraseToObject(type)) { // For an erased type: // - Any of the Ceylon types Void, Object, Nothing, // IdentifiableObject, and Bottom result in the Java type Object // For any other union type U|V (U nor V is Optional): // - The Ceylon type U|V results in the Java type Object ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(type)); if (iterType != null) { // We special case the erasure of X[] and X[]? type = iterType; } else { if ((flags & SATISFIES) != 0) { return null; } else { return make().Type(syms().objectType); } } } else if (willEraseToException(type)) { if ((flags & CLASS_NEW) != 0 || (flags & EXTENDS) != 0) { return make().Type(syms().ceylonExceptionType); } else if ((flags & CATCH) != 0) { return make().Type(syms().exceptionType); } else { return make().Type(syms().throwableType); } } else if ((flags & (SATISFIES | EXTENDS | TYPE_ARGUMENT | CLASS_NEW)) == 0 && (!isOptional(type) || isJavaString(type))) { if (isCeylonString(type) || isJavaString(type)) { return make().Type(syms().stringType); } else if (isCeylonBoolean(type)) { return make().TypeIdent(TypeTags.BOOLEAN); } else if (isCeylonInteger(type)) { if ("byte".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.BYTE); } else if ("short".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.SHORT); } else if ((flags & SMALL_TYPE) != 0 || "int".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.INT); } else { return make().TypeIdent(TypeTags.LONG); } } else if (isCeylonFloat(type)) { if ((flags & SMALL_TYPE) != 0 || "float".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.FLOAT); } else { return make().TypeIdent(TypeTags.DOUBLE); } } else if (isCeylonCharacter(type)) { if ("char".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.CHAR); } else { return make().TypeIdent(TypeTags.INT); } } }else if(isCeylonBoolean(type)){ // special case to get rid of $true and $false types type = typeFact.getBooleanDeclaration().getType(); } JCExpression jt = makeErroneous(); ProducedType simpleType = simplifyType(type); java.util.List<ProducedType> qualifyingTypes = new java.util.ArrayList<ProducedType>(); java.util.List<TypeParameter> qualifyingTypeParameters = new java.util.ArrayList<TypeParameter>(); java.util.Map<TypeParameter, ProducedType> qualifyingTypeArguments = new java.util.HashMap<TypeParameter, ProducedType>(); ProducedType qType = simpleType; while (qType != null) { qualifyingTypes.add(qType); Map<TypeParameter, ProducedType> tas = qType.getTypeArguments(); java.util.List<TypeParameter> tps = qType.getDeclaration().getTypeParameters(); if (tps != null) { qualifyingTypeParameters.addAll(tps); qualifyingTypeArguments.putAll(tas); } qType = qType.getQualifyingType(); } if (simpleType.getDeclaration() instanceof Interface && ((flags & WANT_RAW_TYPE) == 0) && !qualifyingTypeParameters.isEmpty()) { Collections.reverse(qualifyingTypes); JCExpression baseType = makeErroneous(); TypeDeclaration tdecl = simpleType.getDeclaration(); ListBuffer<JCExpression> typeArgs = makeTypeArgs(isCeylonCallable(simpleType), flags, qualifyingTypeArguments, qualifyingTypeParameters); if (isCeylonCallable(type) && (flags & CLASS_NEW) != 0) { baseType = makeIdent(syms().ceylonAbstractCallableType); } else { baseType = getDeclarationName(tdecl); } if (typeArgs != null && typeArgs.size() > 0) { jt = make().TypeApply(baseType, typeArgs.toList()); } else { jt = baseType; } } else if (((flags & WANT_RAW_TYPE) == 0) && !qualifyingTypeParameters.isEmpty()) { // GENERIC TYPES Collections.reverse(qualifyingTypes); JCExpression baseType = makeErroneous(); boolean first = true; for (ProducedType qualifyingType : qualifyingTypes) { TypeDeclaration tdecl = qualifyingType.getDeclaration(); ListBuffer<JCExpression> typeArgs = makeTypeArgs( qualifyingType, //tdecl, flags); if (isCeylonCallable(type) && (flags & CLASS_NEW) != 0) { baseType = makeIdent(syms().ceylonAbstractCallableType); } else if (first) { String name = getFQDeclarationName(tdecl); if (tdecl instanceof Interface) { name = Util.getCompanionClassName(name); } baseType = makeQuotedQualIdentFromString(name); } else { baseType = makeSelect(jt, tdecl.getName()); } if (typeArgs != null && typeArgs.size() > 0) { jt = make().TypeApply(baseType, typeArgs.toList()); } else { jt = baseType; } if (first) { first = false; } } } else { TypeDeclaration tdecl = simpleType.getDeclaration(); // For an ordinary class or interface type T: // - The Ceylon type T results in the Java type T if(tdecl instanceof TypeParameter) jt = makeQuotedIdent(tdecl.getName()); // don't use underlying type if we want no primitives else if((flags & (SATISFIES | NO_PRIMITIVES)) != 0 || simpleType.getUnderlyingType() == null) jt = getDeclarationName(tdecl); else jt = makeQuotedFQIdent(simpleType.getUnderlyingType()); } return jt; }
protected JCExpression makeJavaType(ProducedType type, int flags) { if(type == null) return make().Erroneous(); // ERASURE if (willEraseToObject(type)) { // For an erased type: // - Any of the Ceylon types Void, Object, Nothing, // IdentifiableObject, and Bottom result in the Java type Object // For any other union type U|V (U nor V is Optional): // - The Ceylon type U|V results in the Java type Object ProducedType iterType = typeFact().getNonemptyIterableType(typeFact().getDefiniteType(type)); if (iterType != null) { // We special case the erasure of X[] and X[]? type = iterType; } else { if ((flags & SATISFIES) != 0) { return null; } else { return make().Type(syms().objectType); } } } else if (willEraseToException(type)) { if ((flags & CLASS_NEW) != 0 || (flags & EXTENDS) != 0) { return make().Type(syms().ceylonExceptionType); } else if ((flags & CATCH) != 0) { return make().Type(syms().exceptionType); } else { return make().Type(syms().throwableType); } } else if ((flags & (SATISFIES | EXTENDS | TYPE_ARGUMENT | CLASS_NEW)) == 0 && (!isOptional(type) || isJavaString(type))) { if (isCeylonString(type) || isJavaString(type)) { return make().Type(syms().stringType); } else if (isCeylonBoolean(type)) { return make().TypeIdent(TypeTags.BOOLEAN); } else if (isCeylonInteger(type)) { if ("byte".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.BYTE); } else if ("short".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.SHORT); } else if ((flags & SMALL_TYPE) != 0 || "int".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.INT); } else { return make().TypeIdent(TypeTags.LONG); } } else if (isCeylonFloat(type)) { if ((flags & SMALL_TYPE) != 0 || "float".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.FLOAT); } else { return make().TypeIdent(TypeTags.DOUBLE); } } else if (isCeylonCharacter(type)) { if ("char".equals(type.getUnderlyingType())) { return make().TypeIdent(TypeTags.CHAR); } else { return make().TypeIdent(TypeTags.INT); } } }else if(isCeylonBoolean(type) && (flags & TYPE_ARGUMENT) == 0){ // special case to get rid of $true and $false types type = typeFact.getBooleanDeclaration().getType(); } JCExpression jt = makeErroneous(); ProducedType simpleType = simplifyType(type); java.util.List<ProducedType> qualifyingTypes = new java.util.ArrayList<ProducedType>(); java.util.List<TypeParameter> qualifyingTypeParameters = new java.util.ArrayList<TypeParameter>(); java.util.Map<TypeParameter, ProducedType> qualifyingTypeArguments = new java.util.HashMap<TypeParameter, ProducedType>(); ProducedType qType = simpleType; while (qType != null) { qualifyingTypes.add(qType); Map<TypeParameter, ProducedType> tas = qType.getTypeArguments(); java.util.List<TypeParameter> tps = qType.getDeclaration().getTypeParameters(); if (tps != null) { qualifyingTypeParameters.addAll(tps); qualifyingTypeArguments.putAll(tas); } qType = qType.getQualifyingType(); } if (simpleType.getDeclaration() instanceof Interface && ((flags & WANT_RAW_TYPE) == 0) && !qualifyingTypeParameters.isEmpty()) { Collections.reverse(qualifyingTypes); JCExpression baseType = makeErroneous(); TypeDeclaration tdecl = simpleType.getDeclaration(); ListBuffer<JCExpression> typeArgs = makeTypeArgs(isCeylonCallable(simpleType), flags, qualifyingTypeArguments, qualifyingTypeParameters); if (isCeylonCallable(type) && (flags & CLASS_NEW) != 0) { baseType = makeIdent(syms().ceylonAbstractCallableType); } else { baseType = getDeclarationName(tdecl); } if (typeArgs != null && typeArgs.size() > 0) { jt = make().TypeApply(baseType, typeArgs.toList()); } else { jt = baseType; } } else if (((flags & WANT_RAW_TYPE) == 0) && !qualifyingTypeParameters.isEmpty()) { // GENERIC TYPES Collections.reverse(qualifyingTypes); JCExpression baseType = makeErroneous(); boolean first = true; for (ProducedType qualifyingType : qualifyingTypes) { TypeDeclaration tdecl = qualifyingType.getDeclaration(); ListBuffer<JCExpression> typeArgs = makeTypeArgs( qualifyingType, //tdecl, flags); if (isCeylonCallable(type) && (flags & CLASS_NEW) != 0) { baseType = makeIdent(syms().ceylonAbstractCallableType); } else if (first) { String name = getFQDeclarationName(tdecl); if (tdecl instanceof Interface) { name = Util.getCompanionClassName(name); } baseType = makeQuotedQualIdentFromString(name); } else { baseType = makeSelect(jt, tdecl.getName()); } if (typeArgs != null && typeArgs.size() > 0) { jt = make().TypeApply(baseType, typeArgs.toList()); } else { jt = baseType; } if (first) { first = false; } } } else { TypeDeclaration tdecl = simpleType.getDeclaration(); // For an ordinary class or interface type T: // - The Ceylon type T results in the Java type T if(tdecl instanceof TypeParameter) jt = makeQuotedIdent(tdecl.getName()); // don't use underlying type if we want no primitives else if((flags & (SATISFIES | NO_PRIMITIVES)) != 0 || simpleType.getUnderlyingType() == null) jt = getDeclarationName(tdecl); else jt = makeQuotedFQIdent(simpleType.getUnderlyingType()); } return jt; }
diff --git a/src/com/android/settings/paranoid/Toolbar.java b/src/com/android/settings/paranoid/Toolbar.java index 7f42b364b..d0b653298 100644 --- a/src/com/android/settings/paranoid/Toolbar.java +++ b/src/com/android/settings/paranoid/Toolbar.java @@ -1,317 +1,317 @@ /* * Copyright (C) 2012 ParanoidAndroid Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.settings.paranoid; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnMultiChoiceClickListener; import android.os.Bundle; import android.os.RemoteException; import android.os.ServiceManager; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.preference.Preference.OnPreferenceClickListener; import android.provider.Settings; import android.provider.Settings.SettingNotFoundException; import android.view.IWindowManager; import com.android.settings.R; import com.android.settings.SettingsPreferenceFragment; import com.android.settings.Utils; public class Toolbar extends SettingsPreferenceFragment implements Preference.OnPreferenceChangeListener { private static final String KEY_QUICK_PULL_DOWN = "quick_pulldown"; private static final String KEY_AM_PM_STYLE = "am_pm_style"; private static final String KEY_SHOW_CLOCK = "show_clock"; private static final String KEY_CIRCLE_BATTERY = "circle_battery"; private static final String KEY_STATUS_BAR_NOTIF_COUNT = "status_bar_notif_count"; private static final String STATUS_BAR_MAX_NOTIF = "status_bar_max_notifications"; private static final String NAV_BAR_TABUI_MENU = "nav_bar_tabui_menu"; private static final String STATUS_BAR_DONOTDISTURB = "status_bar_donotdisturb"; private static final String NAV_BAR_CATEGORY = "toolbar_navigation"; private static final String NAV_BAR_CONTROLS = "navigation_bar_controls"; private static final String PIE_GRAVITY = "pie_gravity"; private static final String PIE_MODE = "pie_mode"; private static final String PIE_SIZE = "pie_size"; private static final String PIE_TRIGGER = "pie_trigger"; private static final String PIE_ANGLE = "pie_angle"; private static final String PIE_GAP = "pie_gap"; private static final String PIE_MENU = "pie_menu"; private static final String PIE_SEARCH = "pie_search"; private static final String PIE_CENTER = "pie_center"; private static final String PIE_STICK = "pie_stick"; private static final String KEY_HARDWARE_KEYS = "hardware_keys"; private ListPreference mAmPmStyle; private ListPreference mStatusBarMaxNotif; private ListPreference mPieMode; private ListPreference mPieSize; private ListPreference mPieGravity; private ListPreference mPieTrigger; private ListPreference mPieAngle; private ListPreference mPieGap; private CheckBoxPreference mQuickPullDown; private CheckBoxPreference mShowClock; private CheckBoxPreference mCircleBattery; private CheckBoxPreference mStatusBarNotifCount; private CheckBoxPreference mMenuButtonShow; private CheckBoxPreference mStatusBarDoNotDisturb; private CheckBoxPreference mPieMenu; private CheckBoxPreference mPieSearch; private CheckBoxPreference mPieCenter; private CheckBoxPreference mPieStick; private PreferenceScreen mNavigationBarControls; private PreferenceCategory mNavigationCategory; private Context mContext; private int mAllowedLocations; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.tool_bar_settings); PreferenceScreen prefSet = getPreferenceScreen(); mContext = getActivity(); mQuickPullDown = (CheckBoxPreference) prefSet.findPreference(KEY_QUICK_PULL_DOWN); mQuickPullDown.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0) == 1); mShowClock = (CheckBoxPreference) prefSet.findPreference(KEY_SHOW_CLOCK); mShowClock.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_SHOW_CLOCK, 1) == 1); mCircleBattery = (CheckBoxPreference) prefSet.findPreference(KEY_CIRCLE_BATTERY); mCircleBattery.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_CIRCLE_BATTERY, 0) == 1); mPieMenu = (CheckBoxPreference) prefSet.findPreference(PIE_MENU); mPieMenu.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MENU, 1) == 1); mPieSearch = (CheckBoxPreference) prefSet.findPreference(PIE_SEARCH); mPieSearch.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_SEARCH, 1) == 1); mPieCenter = (CheckBoxPreference) prefSet.findPreference(PIE_CENTER); mPieCenter.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_CENTER, 1) == 1); mPieStick = (CheckBoxPreference) prefSet.findPreference(PIE_STICK); mPieStick.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_STICK, 1) == 1); mAmPmStyle = (ListPreference) prefSet.findPreference(KEY_AM_PM_STYLE); int amPmStyle = Settings.System.getInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_AM_PM_STYLE, 2); mAmPmStyle.setValue(String.valueOf(amPmStyle)); mAmPmStyle.setSummary(mAmPmStyle.getEntry()); mAmPmStyle.setOnPreferenceChangeListener(this); mStatusBarMaxNotif = (ListPreference) prefSet.findPreference(STATUS_BAR_MAX_NOTIF); int maxNotIcons = Settings.System.getInt(mContext.getContentResolver(), Settings.System.MAX_NOTIFICATION_ICONS, 2); mStatusBarMaxNotif.setValue(String.valueOf(maxNotIcons)); mStatusBarMaxNotif.setOnPreferenceChangeListener(this); mNavigationCategory = (PreferenceCategory) prefSet.findPreference(NAV_BAR_CATEGORY); mMenuButtonShow = (CheckBoxPreference) prefSet.findPreference(NAV_BAR_TABUI_MENU); mMenuButtonShow.setChecked((Settings.System.getInt(mContext.getContentResolver(), Settings.System.NAV_BAR_TABUI_MENU, 0) == 1)); mNavigationBarControls = (PreferenceScreen) prefSet.findPreference(NAV_BAR_CONTROLS); mPieGravity = (ListPreference) prefSet.findPreference(PIE_GRAVITY); int pieGravity = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GRAVITY, 3); mPieGravity.setValue(String.valueOf(pieGravity)); mPieGravity.setOnPreferenceChangeListener(this); mPieMode = (ListPreference) prefSet.findPreference(PIE_MODE); int pieMode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MODE, 2); mPieMode.setValue(String.valueOf(pieMode)); mPieMode.setOnPreferenceChangeListener(this); mPieSize = (ListPreference) prefSet.findPreference(PIE_SIZE); mPieTrigger = (ListPreference) prefSet.findPreference(PIE_TRIGGER); try { float pieSize = Settings.System.getFloat(mContext.getContentResolver(), - Settings.System.PIE_SIZE, 0.9f); + Settings.System.PIE_SIZE, 1.0f); mPieSize.setValue(String.valueOf(pieSize)); float pieTrigger = Settings.System.getFloat(mContext.getContentResolver(), Settings.System.PIE_TRIGGER); mPieTrigger.setValue(String.valueOf(pieTrigger)); } catch(SettingNotFoundException ex) { // So what } mPieSize.setOnPreferenceChangeListener(this); mPieTrigger.setOnPreferenceChangeListener(this); mPieGap = (ListPreference) prefSet.findPreference(PIE_GAP); int pieGap = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GAP, 3); mPieGap.setValue(String.valueOf(pieGap)); mPieGap.setOnPreferenceChangeListener(this); mPieAngle = (ListPreference) prefSet.findPreference(PIE_ANGLE); int pieAngle = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_ANGLE, 12); mPieAngle.setValue(String.valueOf(pieAngle)); mPieAngle.setOnPreferenceChangeListener(this); try { if (Settings.System.getInt(getActivity().getContentResolver(), Settings.System.TIME_12_24) != 12) { mAmPmStyle.setEnabled(false); mAmPmStyle.setSummary(R.string.status_bar_am_pm_info); } } catch (SettingNotFoundException e) { // This will hurt you, run away } mStatusBarNotifCount = (CheckBoxPreference) prefSet.findPreference(KEY_STATUS_BAR_NOTIF_COUNT); mStatusBarNotifCount.setChecked(Settings.System.getInt(getActivity().getContentResolver(), Settings.System.STATUS_BAR_NOTIF_COUNT, 0) == 1); mStatusBarDoNotDisturb = (CheckBoxPreference) prefSet.findPreference(STATUS_BAR_DONOTDISTURB); mStatusBarDoNotDisturb.setChecked((Settings.System.getInt(getActivity().getContentResolver(), Settings.System.STATUS_BAR_DONOTDISTURB, 0) == 1)); if (!Utils.isTablet()) { prefSet.removePreference(mStatusBarMaxNotif); prefSet.removePreference(mMenuButtonShow); prefSet.removePreference(mStatusBarDoNotDisturb); if(!Utils.hasNavigationBar()) { prefSet.removePreference(mNavigationCategory); } } else { mNavigationCategory.removePreference(mNavigationBarControls); prefSet.removePreference(mQuickPullDown); } // Only show the hardware keys config on a device that does not have a navbar final int deviceKeys = getResources().getInteger( com.android.internal.R.integer.config_deviceHardwareKeys); if(deviceKeys==15) { PreferenceScreen HARDWARE =(PreferenceScreen) prefSet.findPreference(KEY_HARDWARE_KEYS); prefSet.removePreference(HARDWARE); } } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { if (preference == mShowClock) { Settings.System.putInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_SHOW_CLOCK, mShowClock.isChecked() ? 1 : 0); } else if (preference == mCircleBattery) { Settings.System.putInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_CIRCLE_BATTERY, mCircleBattery.isChecked() ? 1 : 0); } else if (preference == mQuickPullDown) { Settings.System.putInt(mContext.getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, mQuickPullDown.isChecked() ? 1 : 0); } else if (preference == mStatusBarNotifCount) { Settings.System.putInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_NOTIF_COUNT, mStatusBarNotifCount.isChecked() ? 1 : 0); } else if (preference == mMenuButtonShow) { Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(), Settings.System.NAV_BAR_TABUI_MENU, mMenuButtonShow.isChecked() ? 1 : 0); return true; } else if (preference == mStatusBarDoNotDisturb) { Settings.System.putInt(getActivity().getContentResolver(), Settings.System.STATUS_BAR_DONOTDISTURB, mStatusBarDoNotDisturb.isChecked() ? 1 : 0); return true; } else if (preference == mPieMenu) { Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(), Settings.System.PIE_MENU, mPieMenu.isChecked() ? 1 : 0); } else if (preference == mPieSearch) { Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(), Settings.System.PIE_SEARCH, mPieSearch.isChecked() ? 1 : 0); } else if (preference == mPieCenter) { Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(), Settings.System.PIE_CENTER, mPieCenter.isChecked() ? 1 : 0); } else if (preference == mPieStick) { Settings.System.putInt(getActivity().getApplicationContext().getContentResolver(), Settings.System.PIE_STICK, mPieStick.isChecked() ? 1 : 0); } return super.onPreferenceTreeClick(preferenceScreen, preference); } public boolean onPreferenceChange(Preference preference, Object newValue) { if (preference == mAmPmStyle) { int statusBarAmPmSize = Integer.valueOf((String) newValue); int index = mAmPmStyle.findIndexOfValue((String) newValue); Settings.System.putInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_AM_PM_STYLE, statusBarAmPmSize); mAmPmStyle.setSummary(mAmPmStyle.getEntries()[index]); return true; } else if (preference == mStatusBarMaxNotif) { int maxNotIcons = Integer.valueOf((String) newValue); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.MAX_NOTIFICATION_ICONS, maxNotIcons); return true; } else if (preference == mPieMode) { int pieMode = Integer.valueOf((String) newValue); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.PIE_MODE, pieMode); return true; } else if (preference == mPieSize) { float pieSize = Float.valueOf((String) newValue); Settings.System.putFloat(getActivity().getContentResolver(), Settings.System.PIE_SIZE, pieSize); return true; } else if (preference == mPieGravity) { int pieGravity = Integer.valueOf((String) newValue); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.PIE_GRAVITY, pieGravity); return true; } else if (preference == mPieAngle) { int pieAngle = Integer.valueOf((String) newValue); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.PIE_ANGLE, pieAngle); return true; } else if (preference == mPieGap) { int pieGap = Integer.valueOf((String) newValue); Settings.System.putInt(getActivity().getContentResolver(), Settings.System.PIE_GAP, pieGap); return true; } else if (preference == mPieTrigger) { float pieTrigger = Float.valueOf((String) newValue); Settings.System.putFloat(getActivity().getContentResolver(), Settings.System.PIE_TRIGGER, pieTrigger); return true; } return false; } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.tool_bar_settings); PreferenceScreen prefSet = getPreferenceScreen(); mContext = getActivity(); mQuickPullDown = (CheckBoxPreference) prefSet.findPreference(KEY_QUICK_PULL_DOWN); mQuickPullDown.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0) == 1); mShowClock = (CheckBoxPreference) prefSet.findPreference(KEY_SHOW_CLOCK); mShowClock.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_SHOW_CLOCK, 1) == 1); mCircleBattery = (CheckBoxPreference) prefSet.findPreference(KEY_CIRCLE_BATTERY); mCircleBattery.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_CIRCLE_BATTERY, 0) == 1); mPieMenu = (CheckBoxPreference) prefSet.findPreference(PIE_MENU); mPieMenu.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MENU, 1) == 1); mPieSearch = (CheckBoxPreference) prefSet.findPreference(PIE_SEARCH); mPieSearch.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_SEARCH, 1) == 1); mPieCenter = (CheckBoxPreference) prefSet.findPreference(PIE_CENTER); mPieCenter.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_CENTER, 1) == 1); mPieStick = (CheckBoxPreference) prefSet.findPreference(PIE_STICK); mPieStick.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_STICK, 1) == 1); mAmPmStyle = (ListPreference) prefSet.findPreference(KEY_AM_PM_STYLE); int amPmStyle = Settings.System.getInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_AM_PM_STYLE, 2); mAmPmStyle.setValue(String.valueOf(amPmStyle)); mAmPmStyle.setSummary(mAmPmStyle.getEntry()); mAmPmStyle.setOnPreferenceChangeListener(this); mStatusBarMaxNotif = (ListPreference) prefSet.findPreference(STATUS_BAR_MAX_NOTIF); int maxNotIcons = Settings.System.getInt(mContext.getContentResolver(), Settings.System.MAX_NOTIFICATION_ICONS, 2); mStatusBarMaxNotif.setValue(String.valueOf(maxNotIcons)); mStatusBarMaxNotif.setOnPreferenceChangeListener(this); mNavigationCategory = (PreferenceCategory) prefSet.findPreference(NAV_BAR_CATEGORY); mMenuButtonShow = (CheckBoxPreference) prefSet.findPreference(NAV_BAR_TABUI_MENU); mMenuButtonShow.setChecked((Settings.System.getInt(mContext.getContentResolver(), Settings.System.NAV_BAR_TABUI_MENU, 0) == 1)); mNavigationBarControls = (PreferenceScreen) prefSet.findPreference(NAV_BAR_CONTROLS); mPieGravity = (ListPreference) prefSet.findPreference(PIE_GRAVITY); int pieGravity = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GRAVITY, 3); mPieGravity.setValue(String.valueOf(pieGravity)); mPieGravity.setOnPreferenceChangeListener(this); mPieMode = (ListPreference) prefSet.findPreference(PIE_MODE); int pieMode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MODE, 2); mPieMode.setValue(String.valueOf(pieMode)); mPieMode.setOnPreferenceChangeListener(this); mPieSize = (ListPreference) prefSet.findPreference(PIE_SIZE); mPieTrigger = (ListPreference) prefSet.findPreference(PIE_TRIGGER); try { float pieSize = Settings.System.getFloat(mContext.getContentResolver(), Settings.System.PIE_SIZE, 0.9f); mPieSize.setValue(String.valueOf(pieSize)); float pieTrigger = Settings.System.getFloat(mContext.getContentResolver(), Settings.System.PIE_TRIGGER); mPieTrigger.setValue(String.valueOf(pieTrigger)); } catch(SettingNotFoundException ex) { // So what } mPieSize.setOnPreferenceChangeListener(this); mPieTrigger.setOnPreferenceChangeListener(this); mPieGap = (ListPreference) prefSet.findPreference(PIE_GAP); int pieGap = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GAP, 3); mPieGap.setValue(String.valueOf(pieGap)); mPieGap.setOnPreferenceChangeListener(this); mPieAngle = (ListPreference) prefSet.findPreference(PIE_ANGLE); int pieAngle = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_ANGLE, 12); mPieAngle.setValue(String.valueOf(pieAngle)); mPieAngle.setOnPreferenceChangeListener(this); try { if (Settings.System.getInt(getActivity().getContentResolver(), Settings.System.TIME_12_24) != 12) { mAmPmStyle.setEnabled(false); mAmPmStyle.setSummary(R.string.status_bar_am_pm_info); } } catch (SettingNotFoundException e) { // This will hurt you, run away } mStatusBarNotifCount = (CheckBoxPreference) prefSet.findPreference(KEY_STATUS_BAR_NOTIF_COUNT); mStatusBarNotifCount.setChecked(Settings.System.getInt(getActivity().getContentResolver(), Settings.System.STATUS_BAR_NOTIF_COUNT, 0) == 1); mStatusBarDoNotDisturb = (CheckBoxPreference) prefSet.findPreference(STATUS_BAR_DONOTDISTURB); mStatusBarDoNotDisturb.setChecked((Settings.System.getInt(getActivity().getContentResolver(), Settings.System.STATUS_BAR_DONOTDISTURB, 0) == 1)); if (!Utils.isTablet()) { prefSet.removePreference(mStatusBarMaxNotif); prefSet.removePreference(mMenuButtonShow); prefSet.removePreference(mStatusBarDoNotDisturb); if(!Utils.hasNavigationBar()) { prefSet.removePreference(mNavigationCategory); } } else { mNavigationCategory.removePreference(mNavigationBarControls); prefSet.removePreference(mQuickPullDown); } // Only show the hardware keys config on a device that does not have a navbar final int deviceKeys = getResources().getInteger( com.android.internal.R.integer.config_deviceHardwareKeys); if(deviceKeys==15) { PreferenceScreen HARDWARE =(PreferenceScreen) prefSet.findPreference(KEY_HARDWARE_KEYS); prefSet.removePreference(HARDWARE); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.tool_bar_settings); PreferenceScreen prefSet = getPreferenceScreen(); mContext = getActivity(); mQuickPullDown = (CheckBoxPreference) prefSet.findPreference(KEY_QUICK_PULL_DOWN); mQuickPullDown.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.QS_QUICK_PULLDOWN, 0) == 1); mShowClock = (CheckBoxPreference) prefSet.findPreference(KEY_SHOW_CLOCK); mShowClock.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_SHOW_CLOCK, 1) == 1); mCircleBattery = (CheckBoxPreference) prefSet.findPreference(KEY_CIRCLE_BATTERY); mCircleBattery.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_CIRCLE_BATTERY, 0) == 1); mPieMenu = (CheckBoxPreference) prefSet.findPreference(PIE_MENU); mPieMenu.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MENU, 1) == 1); mPieSearch = (CheckBoxPreference) prefSet.findPreference(PIE_SEARCH); mPieSearch.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_SEARCH, 1) == 1); mPieCenter = (CheckBoxPreference) prefSet.findPreference(PIE_CENTER); mPieCenter.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_CENTER, 1) == 1); mPieStick = (CheckBoxPreference) prefSet.findPreference(PIE_STICK); mPieStick.setChecked(Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_STICK, 1) == 1); mAmPmStyle = (ListPreference) prefSet.findPreference(KEY_AM_PM_STYLE); int amPmStyle = Settings.System.getInt(mContext.getContentResolver(), Settings.System.STATUS_BAR_AM_PM_STYLE, 2); mAmPmStyle.setValue(String.valueOf(amPmStyle)); mAmPmStyle.setSummary(mAmPmStyle.getEntry()); mAmPmStyle.setOnPreferenceChangeListener(this); mStatusBarMaxNotif = (ListPreference) prefSet.findPreference(STATUS_BAR_MAX_NOTIF); int maxNotIcons = Settings.System.getInt(mContext.getContentResolver(), Settings.System.MAX_NOTIFICATION_ICONS, 2); mStatusBarMaxNotif.setValue(String.valueOf(maxNotIcons)); mStatusBarMaxNotif.setOnPreferenceChangeListener(this); mNavigationCategory = (PreferenceCategory) prefSet.findPreference(NAV_BAR_CATEGORY); mMenuButtonShow = (CheckBoxPreference) prefSet.findPreference(NAV_BAR_TABUI_MENU); mMenuButtonShow.setChecked((Settings.System.getInt(mContext.getContentResolver(), Settings.System.NAV_BAR_TABUI_MENU, 0) == 1)); mNavigationBarControls = (PreferenceScreen) prefSet.findPreference(NAV_BAR_CONTROLS); mPieGravity = (ListPreference) prefSet.findPreference(PIE_GRAVITY); int pieGravity = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GRAVITY, 3); mPieGravity.setValue(String.valueOf(pieGravity)); mPieGravity.setOnPreferenceChangeListener(this); mPieMode = (ListPreference) prefSet.findPreference(PIE_MODE); int pieMode = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_MODE, 2); mPieMode.setValue(String.valueOf(pieMode)); mPieMode.setOnPreferenceChangeListener(this); mPieSize = (ListPreference) prefSet.findPreference(PIE_SIZE); mPieTrigger = (ListPreference) prefSet.findPreference(PIE_TRIGGER); try { float pieSize = Settings.System.getFloat(mContext.getContentResolver(), Settings.System.PIE_SIZE, 1.0f); mPieSize.setValue(String.valueOf(pieSize)); float pieTrigger = Settings.System.getFloat(mContext.getContentResolver(), Settings.System.PIE_TRIGGER); mPieTrigger.setValue(String.valueOf(pieTrigger)); } catch(SettingNotFoundException ex) { // So what } mPieSize.setOnPreferenceChangeListener(this); mPieTrigger.setOnPreferenceChangeListener(this); mPieGap = (ListPreference) prefSet.findPreference(PIE_GAP); int pieGap = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_GAP, 3); mPieGap.setValue(String.valueOf(pieGap)); mPieGap.setOnPreferenceChangeListener(this); mPieAngle = (ListPreference) prefSet.findPreference(PIE_ANGLE); int pieAngle = Settings.System.getInt(mContext.getContentResolver(), Settings.System.PIE_ANGLE, 12); mPieAngle.setValue(String.valueOf(pieAngle)); mPieAngle.setOnPreferenceChangeListener(this); try { if (Settings.System.getInt(getActivity().getContentResolver(), Settings.System.TIME_12_24) != 12) { mAmPmStyle.setEnabled(false); mAmPmStyle.setSummary(R.string.status_bar_am_pm_info); } } catch (SettingNotFoundException e) { // This will hurt you, run away } mStatusBarNotifCount = (CheckBoxPreference) prefSet.findPreference(KEY_STATUS_BAR_NOTIF_COUNT); mStatusBarNotifCount.setChecked(Settings.System.getInt(getActivity().getContentResolver(), Settings.System.STATUS_BAR_NOTIF_COUNT, 0) == 1); mStatusBarDoNotDisturb = (CheckBoxPreference) prefSet.findPreference(STATUS_BAR_DONOTDISTURB); mStatusBarDoNotDisturb.setChecked((Settings.System.getInt(getActivity().getContentResolver(), Settings.System.STATUS_BAR_DONOTDISTURB, 0) == 1)); if (!Utils.isTablet()) { prefSet.removePreference(mStatusBarMaxNotif); prefSet.removePreference(mMenuButtonShow); prefSet.removePreference(mStatusBarDoNotDisturb); if(!Utils.hasNavigationBar()) { prefSet.removePreference(mNavigationCategory); } } else { mNavigationCategory.removePreference(mNavigationBarControls); prefSet.removePreference(mQuickPullDown); } // Only show the hardware keys config on a device that does not have a navbar final int deviceKeys = getResources().getInteger( com.android.internal.R.integer.config_deviceHardwareKeys); if(deviceKeys==15) { PreferenceScreen HARDWARE =(PreferenceScreen) prefSet.findPreference(KEY_HARDWARE_KEYS); prefSet.removePreference(HARDWARE); } }
diff --git a/src/me/chaseoes/tf2/listeners/PlayerInteractListener.java b/src/me/chaseoes/tf2/listeners/PlayerInteractListener.java index 0ab8f8b..4fffbab 100644 --- a/src/me/chaseoes/tf2/listeners/PlayerInteractListener.java +++ b/src/me/chaseoes/tf2/listeners/PlayerInteractListener.java @@ -1,145 +1,147 @@ package me.chaseoes.tf2.listeners; import me.chaseoes.tf2.*; import me.chaseoes.tf2.classes.ClassUtilities; import me.chaseoes.tf2.classes.TF2Class; import me.chaseoes.tf2.utilities.DataChecker; import me.chaseoes.tf2.utilities.GeneralUtilities; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.InventoryHolder; public class PlayerInteractListener implements Listener { @SuppressWarnings("deprecation") @EventHandler(priority = EventPriority.HIGHEST) public void onPlayerInteract(PlayerInteractEvent event) { try { Player player = event.getPlayer(); GamePlayer gp = GameUtilities.getUtilities().getGamePlayer(player); if (GameUtilities.getUtilities().isIngame(player)) { if ((player.getItemInHand().getType() == Material.getMaterial(373) || player.getItemInHand().getType() == Material.BOW) && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { if (gp.justSpawned()) { event.setCancelled(true); player.updateInventory(); } if (gp.isInLobby()) { event.setCancelled(true); player.updateInventory(); } } } if (event.getPlayer().isSneaking()) { return; } if (event.hasBlock() && (event.getClickedBlock().getType() == Material.WALL_SIGN || event.getClickedBlock().getType() == Material.SIGN_POST)) { Sign s = (Sign) event.getClickedBlock().getState(); if (s.getLine(0).equalsIgnoreCase("Team Fortress 2") && s.getLine(2).equalsIgnoreCase("to join:")) { String map = ChatColor.stripColor(s.getLine(3)); Game game = GameUtilities.getUtilities().getGame(TF2.getInstance().getMap(map)); Team team = game.decideTeam(); DataChecker dc = new DataChecker(map); if (!dc.allGood()) { player.sendMessage(ChatColor.YELLOW + "[TF2] This map has not yet been setup."); if (player.hasPermission("tf2.create")) { player.sendMessage(ChatColor.YELLOW + "[TF2] Type " + ChatColor.GOLD + "/tf2 checkdata " + map + " " + ChatColor.YELLOW + "to see what else needs to be done."); } return; } if (!player.hasPermission("tf2.play")) { event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] You do not have permission."); return; } if (GameUtilities.getUtilities().isIngame(player)) { event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] You are already playing on a map!"); return; } if (DataConfiguration.getData().getDataFile().getStringList("disabled-maps").contains(map)) { player.sendMessage(ChatColor.YELLOW + "[TF2] That map is disabled."); return; } Queue q = GameUtilities.getUtilities().plugin.getQueue(map); if (!player.hasPermission("tf2.create")) { if (q.contains(player)) { player.sendMessage(ChatColor.YELLOW + "[TF2] You are #" + q.getPosition(player.getName()) + " in line for this map."); return; } q.add(player); Integer position = q.getPosition(player.getName()); if (game.getPlayersIngame().size() + 1 <= TF2.getInstance().getMap(map).getPlayerlimit()) { q.remove(position); game.joinGame(GameUtilities.getUtilities().getGamePlayer(player), team); } else { player.sendMessage(ChatColor.YELLOW + "[TF2] You are #" + position + " in line for this map."); } } else { game.joinGame(GameUtilities.getUtilities().getGamePlayer(player), team); } event.setCancelled(true); } } if (event.hasBlock() && (event.getClickedBlock().getType() == Material.STONE_BUTTON || event.getClickedBlock().getType() == Material.WOOD_BUTTON)) { if (GameUtilities.getUtilities().isIngame(player)) { for (String s : DataConfiguration.getData().getDataFile().getStringList("classbuttons")) { if (ClassUtilities.getUtilities().loadClassButtonLocation(s).toString().equalsIgnoreCase(event.getClickedBlock().getLocation().toString())) { if (player.hasPermission("tf2.button." + ClassUtilities.getUtilities().loadClassButtonTypeFromLocation(s))) { TF2Class c = new TF2Class(ClassUtilities.getUtilities().loadClassFromLocation(s)); if (c.apply(player)) { if (gp.isUsingChangeClassButton()) { player.teleport(MapUtilities.getUtilities().loadTeamSpawn(gp.getGame().getMapName(), gp.getTeam())); gp.setInLobby(false); gp.setUsingChangeClassButton(false); + TF2Class classChosen = gp.getCurrentClass(); + classChosen.apply(player); } } return; } event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] " + GeneralUtilities.colorize(GameUtilities.getUtilities().plugin.getConfig().getString("donor-button-noperm"))); } } for (String s : DataConfiguration.getData().getDataFile().getStringList("changeclassbuttons")) { if (ClassUtilities.getUtilities().loadClassButtonLocation(s).toString().equalsIgnoreCase(event.getClickedBlock().getLocation().toString())) { gp.setInLobby(true); gp.setUsingChangeClassButton(true); event.getPlayer().teleport(MapUtilities.getUtilities().loadTeamLobby(GameUtilities.getUtilities().getGamePlayer(player).getCurrentMap(), gp.getTeam())); } } } } if (event.hasBlock() && event.getClickedBlock().getState() instanceof InventoryHolder && gp.isCreatingContainer()) { if (TF2.getInstance().getMap(gp.getMapCreatingItemFor()).isContainerRegistered(event.getClickedBlock().getLocation())) { player.sendMessage(ChatColor.YELLOW + "[TF2] This container is already registered."); gp.setCreatingContainer(false); gp.setMapCreatingItemFor(null); event.setCancelled(true); } else { Map map = TF2.getInstance().getMap(gp.getMapCreatingItemFor()); map.addContainer(event.getClickedBlock().getLocation(), ((InventoryHolder) event.getClickedBlock().getState()).getInventory()); player.sendMessage(ChatColor.YELLOW + "[TF2] Successfully registered container."); gp.setCreatingContainer(false); gp.setMapCreatingItemFor(null); event.setCancelled(true); } } } catch (Exception e) { e.printStackTrace(); } } }
true
true
public void onPlayerInteract(PlayerInteractEvent event) { try { Player player = event.getPlayer(); GamePlayer gp = GameUtilities.getUtilities().getGamePlayer(player); if (GameUtilities.getUtilities().isIngame(player)) { if ((player.getItemInHand().getType() == Material.getMaterial(373) || player.getItemInHand().getType() == Material.BOW) && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { if (gp.justSpawned()) { event.setCancelled(true); player.updateInventory(); } if (gp.isInLobby()) { event.setCancelled(true); player.updateInventory(); } } } if (event.getPlayer().isSneaking()) { return; } if (event.hasBlock() && (event.getClickedBlock().getType() == Material.WALL_SIGN || event.getClickedBlock().getType() == Material.SIGN_POST)) { Sign s = (Sign) event.getClickedBlock().getState(); if (s.getLine(0).equalsIgnoreCase("Team Fortress 2") && s.getLine(2).equalsIgnoreCase("to join:")) { String map = ChatColor.stripColor(s.getLine(3)); Game game = GameUtilities.getUtilities().getGame(TF2.getInstance().getMap(map)); Team team = game.decideTeam(); DataChecker dc = new DataChecker(map); if (!dc.allGood()) { player.sendMessage(ChatColor.YELLOW + "[TF2] This map has not yet been setup."); if (player.hasPermission("tf2.create")) { player.sendMessage(ChatColor.YELLOW + "[TF2] Type " + ChatColor.GOLD + "/tf2 checkdata " + map + " " + ChatColor.YELLOW + "to see what else needs to be done."); } return; } if (!player.hasPermission("tf2.play")) { event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] You do not have permission."); return; } if (GameUtilities.getUtilities().isIngame(player)) { event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] You are already playing on a map!"); return; } if (DataConfiguration.getData().getDataFile().getStringList("disabled-maps").contains(map)) { player.sendMessage(ChatColor.YELLOW + "[TF2] That map is disabled."); return; } Queue q = GameUtilities.getUtilities().plugin.getQueue(map); if (!player.hasPermission("tf2.create")) { if (q.contains(player)) { player.sendMessage(ChatColor.YELLOW + "[TF2] You are #" + q.getPosition(player.getName()) + " in line for this map."); return; } q.add(player); Integer position = q.getPosition(player.getName()); if (game.getPlayersIngame().size() + 1 <= TF2.getInstance().getMap(map).getPlayerlimit()) { q.remove(position); game.joinGame(GameUtilities.getUtilities().getGamePlayer(player), team); } else { player.sendMessage(ChatColor.YELLOW + "[TF2] You are #" + position + " in line for this map."); } } else { game.joinGame(GameUtilities.getUtilities().getGamePlayer(player), team); } event.setCancelled(true); } } if (event.hasBlock() && (event.getClickedBlock().getType() == Material.STONE_BUTTON || event.getClickedBlock().getType() == Material.WOOD_BUTTON)) { if (GameUtilities.getUtilities().isIngame(player)) { for (String s : DataConfiguration.getData().getDataFile().getStringList("classbuttons")) { if (ClassUtilities.getUtilities().loadClassButtonLocation(s).toString().equalsIgnoreCase(event.getClickedBlock().getLocation().toString())) { if (player.hasPermission("tf2.button." + ClassUtilities.getUtilities().loadClassButtonTypeFromLocation(s))) { TF2Class c = new TF2Class(ClassUtilities.getUtilities().loadClassFromLocation(s)); if (c.apply(player)) { if (gp.isUsingChangeClassButton()) { player.teleport(MapUtilities.getUtilities().loadTeamSpawn(gp.getGame().getMapName(), gp.getTeam())); gp.setInLobby(false); gp.setUsingChangeClassButton(false); } } return; } event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] " + GeneralUtilities.colorize(GameUtilities.getUtilities().plugin.getConfig().getString("donor-button-noperm"))); } } for (String s : DataConfiguration.getData().getDataFile().getStringList("changeclassbuttons")) { if (ClassUtilities.getUtilities().loadClassButtonLocation(s).toString().equalsIgnoreCase(event.getClickedBlock().getLocation().toString())) { gp.setInLobby(true); gp.setUsingChangeClassButton(true); event.getPlayer().teleport(MapUtilities.getUtilities().loadTeamLobby(GameUtilities.getUtilities().getGamePlayer(player).getCurrentMap(), gp.getTeam())); } } } } if (event.hasBlock() && event.getClickedBlock().getState() instanceof InventoryHolder && gp.isCreatingContainer()) { if (TF2.getInstance().getMap(gp.getMapCreatingItemFor()).isContainerRegistered(event.getClickedBlock().getLocation())) { player.sendMessage(ChatColor.YELLOW + "[TF2] This container is already registered."); gp.setCreatingContainer(false); gp.setMapCreatingItemFor(null); event.setCancelled(true); } else { Map map = TF2.getInstance().getMap(gp.getMapCreatingItemFor()); map.addContainer(event.getClickedBlock().getLocation(), ((InventoryHolder) event.getClickedBlock().getState()).getInventory()); player.sendMessage(ChatColor.YELLOW + "[TF2] Successfully registered container."); gp.setCreatingContainer(false); gp.setMapCreatingItemFor(null); event.setCancelled(true); } } } catch (Exception e) { e.printStackTrace(); } }
public void onPlayerInteract(PlayerInteractEvent event) { try { Player player = event.getPlayer(); GamePlayer gp = GameUtilities.getUtilities().getGamePlayer(player); if (GameUtilities.getUtilities().isIngame(player)) { if ((player.getItemInHand().getType() == Material.getMaterial(373) || player.getItemInHand().getType() == Material.BOW) && (event.getAction() == Action.RIGHT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_BLOCK)) { if (gp.justSpawned()) { event.setCancelled(true); player.updateInventory(); } if (gp.isInLobby()) { event.setCancelled(true); player.updateInventory(); } } } if (event.getPlayer().isSneaking()) { return; } if (event.hasBlock() && (event.getClickedBlock().getType() == Material.WALL_SIGN || event.getClickedBlock().getType() == Material.SIGN_POST)) { Sign s = (Sign) event.getClickedBlock().getState(); if (s.getLine(0).equalsIgnoreCase("Team Fortress 2") && s.getLine(2).equalsIgnoreCase("to join:")) { String map = ChatColor.stripColor(s.getLine(3)); Game game = GameUtilities.getUtilities().getGame(TF2.getInstance().getMap(map)); Team team = game.decideTeam(); DataChecker dc = new DataChecker(map); if (!dc.allGood()) { player.sendMessage(ChatColor.YELLOW + "[TF2] This map has not yet been setup."); if (player.hasPermission("tf2.create")) { player.sendMessage(ChatColor.YELLOW + "[TF2] Type " + ChatColor.GOLD + "/tf2 checkdata " + map + " " + ChatColor.YELLOW + "to see what else needs to be done."); } return; } if (!player.hasPermission("tf2.play")) { event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] You do not have permission."); return; } if (GameUtilities.getUtilities().isIngame(player)) { event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] You are already playing on a map!"); return; } if (DataConfiguration.getData().getDataFile().getStringList("disabled-maps").contains(map)) { player.sendMessage(ChatColor.YELLOW + "[TF2] That map is disabled."); return; } Queue q = GameUtilities.getUtilities().plugin.getQueue(map); if (!player.hasPermission("tf2.create")) { if (q.contains(player)) { player.sendMessage(ChatColor.YELLOW + "[TF2] You are #" + q.getPosition(player.getName()) + " in line for this map."); return; } q.add(player); Integer position = q.getPosition(player.getName()); if (game.getPlayersIngame().size() + 1 <= TF2.getInstance().getMap(map).getPlayerlimit()) { q.remove(position); game.joinGame(GameUtilities.getUtilities().getGamePlayer(player), team); } else { player.sendMessage(ChatColor.YELLOW + "[TF2] You are #" + position + " in line for this map."); } } else { game.joinGame(GameUtilities.getUtilities().getGamePlayer(player), team); } event.setCancelled(true); } } if (event.hasBlock() && (event.getClickedBlock().getType() == Material.STONE_BUTTON || event.getClickedBlock().getType() == Material.WOOD_BUTTON)) { if (GameUtilities.getUtilities().isIngame(player)) { for (String s : DataConfiguration.getData().getDataFile().getStringList("classbuttons")) { if (ClassUtilities.getUtilities().loadClassButtonLocation(s).toString().equalsIgnoreCase(event.getClickedBlock().getLocation().toString())) { if (player.hasPermission("tf2.button." + ClassUtilities.getUtilities().loadClassButtonTypeFromLocation(s))) { TF2Class c = new TF2Class(ClassUtilities.getUtilities().loadClassFromLocation(s)); if (c.apply(player)) { if (gp.isUsingChangeClassButton()) { player.teleport(MapUtilities.getUtilities().loadTeamSpawn(gp.getGame().getMapName(), gp.getTeam())); gp.setInLobby(false); gp.setUsingChangeClassButton(false); TF2Class classChosen = gp.getCurrentClass(); classChosen.apply(player); } } return; } event.getPlayer().sendMessage(ChatColor.YELLOW + "[TF2] " + GeneralUtilities.colorize(GameUtilities.getUtilities().plugin.getConfig().getString("donor-button-noperm"))); } } for (String s : DataConfiguration.getData().getDataFile().getStringList("changeclassbuttons")) { if (ClassUtilities.getUtilities().loadClassButtonLocation(s).toString().equalsIgnoreCase(event.getClickedBlock().getLocation().toString())) { gp.setInLobby(true); gp.setUsingChangeClassButton(true); event.getPlayer().teleport(MapUtilities.getUtilities().loadTeamLobby(GameUtilities.getUtilities().getGamePlayer(player).getCurrentMap(), gp.getTeam())); } } } } if (event.hasBlock() && event.getClickedBlock().getState() instanceof InventoryHolder && gp.isCreatingContainer()) { if (TF2.getInstance().getMap(gp.getMapCreatingItemFor()).isContainerRegistered(event.getClickedBlock().getLocation())) { player.sendMessage(ChatColor.YELLOW + "[TF2] This container is already registered."); gp.setCreatingContainer(false); gp.setMapCreatingItemFor(null); event.setCancelled(true); } else { Map map = TF2.getInstance().getMap(gp.getMapCreatingItemFor()); map.addContainer(event.getClickedBlock().getLocation(), ((InventoryHolder) event.getClickedBlock().getState()).getInventory()); player.sendMessage(ChatColor.YELLOW + "[TF2] Successfully registered container."); gp.setCreatingContainer(false); gp.setMapCreatingItemFor(null); event.setCancelled(true); } } } catch (Exception e) { e.printStackTrace(); } }
diff --git a/src/com/axelby/podax/GoogleAccountChooserActivity.java b/src/com/axelby/podax/GoogleAccountChooserActivity.java index e3aa1b4..584e709 100644 --- a/src/com/axelby/podax/GoogleAccountChooserActivity.java +++ b/src/com/axelby/podax/GoogleAccountChooserActivity.java @@ -1,184 +1,185 @@ package com.axelby.podax; import java.io.IOException; import java.io.InputStream; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.sax.Element; import android.sax.ElementListener; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.sax.StartElementListener; import android.util.Log; import android.util.Xml; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.GoogleTransport; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpTransport; public class GoogleAccountChooserActivity extends ListActivity { protected AccountManager _accountManager; protected Account[] _accounts; protected Account _chosenAccount; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); _accountManager = AccountManager.get(getApplicationContext()); _chosenAccount = null; _accountManager.getAccountsByTypeAndFeatures("com.google", new String[] { "service_reader" }, new AccountManagerCallback<Account[]>() { public void run(AccountManagerFuture<Account[]> future) { try { _accounts = future.getResult(); String[] names = new String[_accounts.length]; for (int i = 0; i < _accounts.length; ++i) names[i] = _accounts[i].name; GoogleAccountChooserActivity.this.setListAdapter( new ArrayAdapter<String>(GoogleAccountChooserActivity.this, android.R.layout.simple_list_item_1, names)); } catch (OperationCanceledException e) { Log.e("Podax", "Operation Canceled", e); } catch (IOException e) { Log.e("Podax", "IOException", e); } catch (AuthenticatorException e) { Log.e("Podax", "Authentication Failed", e); } } }, null); } @Override protected void onListItemClick(ListView l, View v, final int position, long itemId) { _chosenAccount = _accounts[position]; getAuthToken(); } private void getAuthToken() { if (_chosenAccount == null) return; _accountManager.getAuthToken(_chosenAccount, "reader", true, new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { Bundle authTokenBundle = null; try { authTokenBundle = future.getResult(); if (authTokenBundle == null) return; if(authTokenBundle.containsKey(AccountManager.KEY_INTENT)) { // User input required Intent intent = (Intent)authTokenBundle.get(AccountManager.KEY_INTENT); // clear the new task flag int flags = intent.getFlags(); flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK; intent.setFlags(flags); startActivityForResult(intent, 1); return; } doImport(authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN)); } catch (OperationCanceledException e) { Log.e("Podax", "Operation Canceled", e); } catch (IOException e) { Log.e("Podax", "IOException", e); } catch (AuthenticatorException e) { Log.e("Podax", "Authentication Failed", e); } } }, null); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (resultCode == RESULT_OK && data == null) getAuthToken(); } } private void doImport(String authToken) { HttpTransport transport = GoogleTransport.create(); GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders; headers.setApplicationName("Podax"); headers.gdataVersion = "2"; headers.setGoogleLogin(authToken); HttpRequest request = transport.buildGetRequest(); request.url = new GenericUrl("http://www.google.com/reader/api/0/subscription/list"); try { InputStream response = request.execute().getContent(); // set up the sax parser RootElement root = new RootElement("object"); Element object = root.getChild("list").getChild("object"); // put these in an array to we can use them in the inner class final String[] id = { "" }; final String[] title = { "" }; final String[] stringType = { "" }; final DBAdapter adapter = DBAdapter.getInstance(GoogleAccountChooserActivity.this); object.setElementListener(new ElementListener() { public void start(Attributes attrs) { id[0] = ""; title[0] = ""; } public void end() { Subscription subscription = adapter.addSubscription(id[0], title[0]); UpdateService.updateSubscription(GoogleAccountChooserActivity.this, subscription); } }); object.getChild("string").setStartElementListener(new StartElementListener() { public void start(Attributes attributes) { stringType[0] = attributes.getValue("name"); } }); object.getChild("string").setEndTextElementListener(new EndTextElementListener() { public void end(String text) { if (stringType[0].equals("id")) { if (text != null && text.startsWith("feed/")) text = text.substring(5); id[0] = text; } else if (stringType[0].equals("title")) title[0] = text; } }); Xml.parse(response, Xml.Encoding.UTF_8, root.getContentHandler()); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } Toast.makeText(this, "Google Reader subscriptions imported", Toast.LENGTH_LONG); + finish(); startActivity(new Intent(this, SubscriptionListActivity.class)); } }
true
true
private void doImport(String authToken) { HttpTransport transport = GoogleTransport.create(); GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders; headers.setApplicationName("Podax"); headers.gdataVersion = "2"; headers.setGoogleLogin(authToken); HttpRequest request = transport.buildGetRequest(); request.url = new GenericUrl("http://www.google.com/reader/api/0/subscription/list"); try { InputStream response = request.execute().getContent(); // set up the sax parser RootElement root = new RootElement("object"); Element object = root.getChild("list").getChild("object"); // put these in an array to we can use them in the inner class final String[] id = { "" }; final String[] title = { "" }; final String[] stringType = { "" }; final DBAdapter adapter = DBAdapter.getInstance(GoogleAccountChooserActivity.this); object.setElementListener(new ElementListener() { public void start(Attributes attrs) { id[0] = ""; title[0] = ""; } public void end() { Subscription subscription = adapter.addSubscription(id[0], title[0]); UpdateService.updateSubscription(GoogleAccountChooserActivity.this, subscription); } }); object.getChild("string").setStartElementListener(new StartElementListener() { public void start(Attributes attributes) { stringType[0] = attributes.getValue("name"); } }); object.getChild("string").setEndTextElementListener(new EndTextElementListener() { public void end(String text) { if (stringType[0].equals("id")) { if (text != null && text.startsWith("feed/")) text = text.substring(5); id[0] = text; } else if (stringType[0].equals("title")) title[0] = text; } }); Xml.parse(response, Xml.Encoding.UTF_8, root.getContentHandler()); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } Toast.makeText(this, "Google Reader subscriptions imported", Toast.LENGTH_LONG); startActivity(new Intent(this, SubscriptionListActivity.class)); }
private void doImport(String authToken) { HttpTransport transport = GoogleTransport.create(); GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders; headers.setApplicationName("Podax"); headers.gdataVersion = "2"; headers.setGoogleLogin(authToken); HttpRequest request = transport.buildGetRequest(); request.url = new GenericUrl("http://www.google.com/reader/api/0/subscription/list"); try { InputStream response = request.execute().getContent(); // set up the sax parser RootElement root = new RootElement("object"); Element object = root.getChild("list").getChild("object"); // put these in an array to we can use them in the inner class final String[] id = { "" }; final String[] title = { "" }; final String[] stringType = { "" }; final DBAdapter adapter = DBAdapter.getInstance(GoogleAccountChooserActivity.this); object.setElementListener(new ElementListener() { public void start(Attributes attrs) { id[0] = ""; title[0] = ""; } public void end() { Subscription subscription = adapter.addSubscription(id[0], title[0]); UpdateService.updateSubscription(GoogleAccountChooserActivity.this, subscription); } }); object.getChild("string").setStartElementListener(new StartElementListener() { public void start(Attributes attributes) { stringType[0] = attributes.getValue("name"); } }); object.getChild("string").setEndTextElementListener(new EndTextElementListener() { public void end(String text) { if (stringType[0].equals("id")) { if (text != null && text.startsWith("feed/")) text = text.substring(5); id[0] = text; } else if (stringType[0].equals("title")) title[0] = text; } }); Xml.parse(response, Xml.Encoding.UTF_8, root.getContentHandler()); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } Toast.makeText(this, "Google Reader subscriptions imported", Toast.LENGTH_LONG); finish(); startActivity(new Intent(this, SubscriptionListActivity.class)); }
diff --git a/src/kundera-cassandra/src/test/java/com/impetus/client/schemamanager/CassanrdaGeneratedIdSchemaTest.java b/src/kundera-cassandra/src/test/java/com/impetus/client/schemamanager/CassanrdaGeneratedIdSchemaTest.java index bb26a23eb..b50569712 100644 --- a/src/kundera-cassandra/src/test/java/com/impetus/client/schemamanager/CassanrdaGeneratedIdSchemaTest.java +++ b/src/kundera-cassandra/src/test/java/com/impetus/client/schemamanager/CassanrdaGeneratedIdSchemaTest.java @@ -1,104 +1,105 @@ package com.impetus.client.schemamanager; import java.util.List; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.apache.cassandra.db.marshal.CounterColumnType; import org.apache.cassandra.thrift.CfDef; import org.apache.cassandra.thrift.ColumnDef; import org.apache.cassandra.thrift.InvalidRequestException; import org.apache.cassandra.thrift.KsDef; import org.apache.cassandra.thrift.NotFoundException; import org.apache.thrift.TException; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.impetus.client.persistence.CassandraCli; public class CassanrdaGeneratedIdSchemaTest { private EntityManagerFactory emf; @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { CassandraCli.cassandraSetUp(); emf = Persistence.createEntityManagerFactory("cassandra_generated_id"); } @After public void tearDown() throws Exception { emf.close(); } @Test public void test() { try { KsDef ksDef = CassandraCli.client.describe_keyspace("kunderaGeneratedId"); Assert.assertNotNull(ksDef); Assert.assertEquals(18, ksDef.getCf_defsSize()); int count = 0; for (CfDef cfDef : ksDef.cf_defs) { if (cfDef.getName().equals("kundera_sequences")) { Assert.assertTrue(cfDef.getColumn_type().equals("Standard")); Assert.assertTrue(cfDef.getDefault_validation_class().equals(CounterColumnType.class.getName())); count++; continue; } if (cfDef.getName().equals("kundera")) { Assert.assertTrue(cfDef.getColumn_type().equals("Standard")); Assert.assertTrue(cfDef.getDefault_validation_class().equals(CounterColumnType.class.getName())); count++; } // Mapped super class test classes are created with 4 columns and without @Table annotation. Hence eligible for this pu as well. - else if(!cfDef.getName().equals("TRNX_CREDIT") && !cfDef.getName().equals("DebitTransaction")) + else if(!cfDef.getName().equals("user_account") && !cfDef.getName().equals("social_profile") && !cfDef.getName().equals("TRNX_CREDIT") && !cfDef.getName().equals("DebitTransaction")) { +// System.out.println(cfDef.getName()); Assert.assertTrue(cfDef.getColumn_type().equals("Standard")); List<ColumnDef> columnDefs = cfDef.getColumn_metadata(); Assert.assertEquals(1, columnDefs.size()); count++; } } Assert.assertEquals(14, count); } catch (NotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidRequestException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
false
true
public void test() { try { KsDef ksDef = CassandraCli.client.describe_keyspace("kunderaGeneratedId"); Assert.assertNotNull(ksDef); Assert.assertEquals(18, ksDef.getCf_defsSize()); int count = 0; for (CfDef cfDef : ksDef.cf_defs) { if (cfDef.getName().equals("kundera_sequences")) { Assert.assertTrue(cfDef.getColumn_type().equals("Standard")); Assert.assertTrue(cfDef.getDefault_validation_class().equals(CounterColumnType.class.getName())); count++; continue; } if (cfDef.getName().equals("kundera")) { Assert.assertTrue(cfDef.getColumn_type().equals("Standard")); Assert.assertTrue(cfDef.getDefault_validation_class().equals(CounterColumnType.class.getName())); count++; } // Mapped super class test classes are created with 4 columns and without @Table annotation. Hence eligible for this pu as well. else if(!cfDef.getName().equals("TRNX_CREDIT") && !cfDef.getName().equals("DebitTransaction")) { Assert.assertTrue(cfDef.getColumn_type().equals("Standard")); List<ColumnDef> columnDefs = cfDef.getColumn_metadata(); Assert.assertEquals(1, columnDefs.size()); count++; } } Assert.assertEquals(14, count); } catch (NotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidRequestException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void test() { try { KsDef ksDef = CassandraCli.client.describe_keyspace("kunderaGeneratedId"); Assert.assertNotNull(ksDef); Assert.assertEquals(18, ksDef.getCf_defsSize()); int count = 0; for (CfDef cfDef : ksDef.cf_defs) { if (cfDef.getName().equals("kundera_sequences")) { Assert.assertTrue(cfDef.getColumn_type().equals("Standard")); Assert.assertTrue(cfDef.getDefault_validation_class().equals(CounterColumnType.class.getName())); count++; continue; } if (cfDef.getName().equals("kundera")) { Assert.assertTrue(cfDef.getColumn_type().equals("Standard")); Assert.assertTrue(cfDef.getDefault_validation_class().equals(CounterColumnType.class.getName())); count++; } // Mapped super class test classes are created with 4 columns and without @Table annotation. Hence eligible for this pu as well. else if(!cfDef.getName().equals("user_account") && !cfDef.getName().equals("social_profile") && !cfDef.getName().equals("TRNX_CREDIT") && !cfDef.getName().equals("DebitTransaction")) { // System.out.println(cfDef.getName()); Assert.assertTrue(cfDef.getColumn_type().equals("Standard")); List<ColumnDef> columnDefs = cfDef.getColumn_metadata(); Assert.assertEquals(1, columnDefs.size()); count++; } } Assert.assertEquals(14, count); } catch (NotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidRequestException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForWorkspaceFiles.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForWorkspaceFiles.java index b29d9990d..f19eea382 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForWorkspaceFiles.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForWorkspaceFiles.java @@ -1,130 +1,131 @@ /******************************************************************************* * Copyright (c) 2000, 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 API and implementation *******************************************************************************/ package org.eclipse.core.filebuffers.tests; import java.io.File; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.core.filebuffers.FileBuffers; /** * FileBuffersForWorkspaceFiles */ public class FileBuffersForWorkspaceFiles extends FileBufferFunctions { private static class ResourceListener implements IResourceChangeListener { public boolean fFired= false; public IPath fPath; public ResourceListener(IPath path) { fPath= path; } public void resourceChanged(IResourceChangeEvent event) { if (!fFired) { IResourceDelta delta= event.getDelta(); if (delta != null) { delta= delta.findMember(fPath); if (delta != null) fFired= IResourceDelta.CHANGED == delta.getKind() && (IResourceDelta.CONTENT & delta.getFlags()) != 0; } } } } protected IPath createPath(IProject project) throws Exception { IFolder folder= ResourceHelper.createFolder("project/folderA/folderB/"); IFile file= ResourceHelper.createFile(folder, "WorkspaceFile", "content"); return file.getFullPath(); } /* * @see org.eclipse.core.filebuffers.tests.FileBufferFunctions#markReadOnly() */ protected void markReadOnly() throws Exception { IFile file= FileBuffers.getWorkspaceFileAtLocation(getPath()); file.setReadOnly(true); } /* * @see org.eclipse.core.filebuffers.tests.FileBufferFunctions#isStateValidationSupported() */ protected boolean isStateValidationSupported() { return true; } /* * @see org.eclipse.core.filebuffers.tests.FileBufferFunctions#deleteUnderlyingFile() */ protected boolean deleteUnderlyingFile() throws Exception { IFile file= FileBuffers.getWorkspaceFileAtLocation(getPath()); file.delete(true, false, null); return file.exists(); } /* * @see org.eclipse.core.filebuffers.tests.FileBufferFunctions#moveUnderlyingFile() */ protected IPath moveUnderlyingFile() throws Exception { IFile file= FileBuffers.getWorkspaceFileAtLocation(getPath()); ResourceHelper.createFolder("project/folderA/folderB/folderC"); IPath path= new Path("/project/folderA/folderB/folderC/MovedWorkspaceFile"); file.move(path, true, false, null); file= FileBuffers.getWorkspaceFileAtLocation(path); if (file != null && file.exists()) return path; return null; } /* * @see org.eclipse.core.filebuffers.tests.FileBufferFunctions#modifyUnderlyingFile() */ protected boolean modifyUnderlyingFile() throws Exception { File file= FileBuffers.getSystemFileAtLocation(getPath()); FileTool.write(file.getAbsolutePath(), new StringBuffer("Changed content of workspace file")); + file.setLastModified(1000); IFile iFile= FileBuffers.getWorkspaceFileAtLocation(getPath()); ResourceListener listener= new ResourceListener(iFile.getFullPath()); ResourcesPlugin.getWorkspace().addResourceChangeListener(listener); try { iFile.refreshLocal(IResource.DEPTH_INFINITE, null); return receivedNotification(listener); } finally { ResourcesPlugin.getWorkspace().removeResourceChangeListener(listener); listener= null; } } private boolean receivedNotification(ResourceListener listener) { for (int i= 0; i < 5; i++) { if (listener.fFired) return true; try { Thread.sleep(1000); // sleep a second } catch (InterruptedException e) { } } return false; } }
true
true
protected boolean modifyUnderlyingFile() throws Exception { File file= FileBuffers.getSystemFileAtLocation(getPath()); FileTool.write(file.getAbsolutePath(), new StringBuffer("Changed content of workspace file")); IFile iFile= FileBuffers.getWorkspaceFileAtLocation(getPath()); ResourceListener listener= new ResourceListener(iFile.getFullPath()); ResourcesPlugin.getWorkspace().addResourceChangeListener(listener); try { iFile.refreshLocal(IResource.DEPTH_INFINITE, null); return receivedNotification(listener); } finally { ResourcesPlugin.getWorkspace().removeResourceChangeListener(listener); listener= null; } }
protected boolean modifyUnderlyingFile() throws Exception { File file= FileBuffers.getSystemFileAtLocation(getPath()); FileTool.write(file.getAbsolutePath(), new StringBuffer("Changed content of workspace file")); file.setLastModified(1000); IFile iFile= FileBuffers.getWorkspaceFileAtLocation(getPath()); ResourceListener listener= new ResourceListener(iFile.getFullPath()); ResourcesPlugin.getWorkspace().addResourceChangeListener(listener); try { iFile.refreshLocal(IResource.DEPTH_INFINITE, null); return receivedNotification(listener); } finally { ResourcesPlugin.getWorkspace().removeResourceChangeListener(listener); listener= null; } }
diff --git a/metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/richFunctions/TestFunctions.java b/metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/richFunctions/TestFunctions.java index 6916558ce..95ce3e27c 100644 --- a/metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/richFunctions/TestFunctions.java +++ b/metamer/ftest/src/test/java/org/richfaces/tests/metamer/ftest/richFunctions/TestFunctions.java @@ -1,192 +1,192 @@ /******************************************************************************* * JBoss, Home of Professional Open Source * Copyright 2010-2013, Red Hat, Inc. and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. *******************************************************************************/ package org.richfaces.tests.metamer.ftest.richFunctions; import static org.jboss.test.selenium.support.url.URLUtils.buildUrl; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotSame; import static org.testng.Assert.assertTrue; import java.net.URL; import org.jboss.arquillian.graphene.Graphene; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import org.richfaces.fragment.common.ClearType; import org.richfaces.fragment.common.TextInputComponentImpl; import org.richfaces.tests.metamer.ftest.AbstractWebDriverTest; import org.richfaces.tests.metamer.ftest.annotations.IssueTracking; import org.richfaces.tests.metamer.ftest.annotations.Templates; import org.richfaces.tests.metamer.ftest.webdriver.MetamerPage; import org.richfaces.tests.metamer.ftest.webdriver.MetamerPage.WaitRequestType; import org.testng.annotations.Test; /** * Test case for page faces/components/richFunctions/all.xhtml. * * @author <a href="mailto:[email protected]">Pavol Pitonak</a> * @author <a href="mailto:[email protected]">Jiri Stefek</a> */ public class TestFunctions extends AbstractWebDriverTest { @FindBy(css = "span[id$=clientIdOutput]") private WebElement clientIdOutput; @FindBy(css = "span[id$=elementOutput]") private WebElement elementOutput; @FindBy(css = "span[id$=componentOutput]") private WebElement componentOutput; @FindBy(css = "span[id$=findComponentOutput]") private WebElement findComponentOutput; @FindBy(css = "span[id$=jQuerySelectorOutput]") private WebElement jQuerySelectorOutput; @FindBy(css = "span[id$=jQueryOutput]") private WebElement jQueryOutput; @FindBy(css = "span[id$=outputUserInRoleAU]") private WebElement userInRoleAUOutput; @FindBy(css = "span[id$=outputUserInRoleA]") private WebElement userInRoleAOutput; @FindBy(css = "span[id$=outputUserInRoleU]") private WebElement userInRoleUOutput; @FindBy(css = "a[id$=applyLink]") private WebElement applyLink; @FindBy(css = "input[id$=jQuerySelectorOutputFadeOut]") private WebElement fadeOut; @FindBy(css = "input[id$=jQuerySelectorOutputFadeIn]") private WebElement fadeIn; @FindBy(css = "input[id$=input]") private TextInputComponentImpl input; @FindBy(css = "input[id$=roleName]") private TextInputComponentImpl roleNameInput; private enum Role { ADMIN, USER, NOBODY } private void assertUserIs(Role role) { switch (role) { case ADMIN: assertTrue(isAdmin(), "Current user should have 'admin' rights"); assertFalse(isUser(), "Current user should not have 'user' rights"); assertTrue(isAdminOrUser(), "Current user should have 'admin' or 'user' rights"); break; case USER: assertFalse(isAdmin(), "Current user should not have 'admin' rights"); assertTrue(isUser(), "Current user should have 'user' rights"); assertTrue(isAdminOrUser(), "Current user should have 'admin' or 'user' rights"); break; case NOBODY: assertFalse(isAdmin(), "Current user should not have 'admin' rights"); assertFalse(isUser(), "Current user should not have 'user' rights"); assertFalse(isAdminOrUser(), "Current user should not have 'admin' nor 'user' rights"); break; } } private void fillInRoleAndApply(String role) { roleNameInput.advanced().clear(ClearType.JS).sendKeys(role); MetamerPage.waitRequest(applyLink, WaitRequestType.HTTP).click(); } @Override public URL getTestUrl() { return buildUrl(contextPath, "faces/components/richFunctions/all.xhtml"); } private boolean isAdmin() { return Boolean.parseBoolean(userInRoleAOutput.getText()); } private boolean isAdminOrUser() { return Boolean.parseBoolean(userInRoleAUOutput.getText()); } private boolean isUser() { return Boolean.parseBoolean(userInRoleUOutput.getText()); } @Test public void testFadeOutFadeIn() { assertVisible(input.advanced().getInputElement(), "Input should be visible"); new Actions(driver).moveToElement(fadeOut).perform(); Graphene.waitGui().until().element(input.advanced().getInputElement()).is().not().visible(); assertNotVisible(input.advanced().getInputElement(), "Input should not be visible."); new Actions(driver).moveToElement(fadeIn).perform(); Graphene.waitGui().until().element(input.advanced().getInputElement()).is().visible(); assertVisible(input.advanced().getInputElement(), "Input should be visible"); } @Test @Templates(exclude = { "a4jRepeat", "richCollapsibleSubTable", "richDataGrid", "richDataTable", "richExtendedDataTable", "richList", "hDataTable", "uiRepeat" }) public void testFunctions() { String id = input.advanced().getInputElement().getAttribute("id"); String clientId = clientIdOutput.getText(); assertNotNull(clientId, "Function clientId() doesn't work."); assertNotSame(clientId, "", "Function clientId() doesn't work."); assertEquals(clientId, id, "Function clientId() doesn't work."); String output = elementOutput.getText(); assertEquals(output, "document.getElementById('" + clientId + "')", "Function element() doesn't work."); output = componentOutput.getText(); - assertEquals(output, "RichFaces.$('" + clientId + "')", "Function component() doesn't work."); + assertEquals(output, "RichFaces.component('" + clientId + "')", "Function component() doesn't work."); output = findComponentOutput.getText(); assertEquals(output, "abc", "Function findComponent() doesn't work."); input.advanced().clear(ClearType.JS).sendKeys("RichFaces"); MetamerPage.waitRequest(applyLink, WaitRequestType.HTTP).click(); output = findComponentOutput.getText(); assertEquals(output, "RichFaces", "Function findComponent() doesn't work."); output = jQuerySelectorOutput.getText(); assertEquals(output, "#form\\\\:subview\\\\:input", "Function jQuerySelector() doesn't work."); output = jQueryOutput.getText(); - assertEquals(output, "jQuery(document.getElementById('" + clientId + "'))", "Function jQuerySelector() doesn't work."); + assertEquals(output, "RichFaces.jQuery(document.getElementById('" + clientId + "'))", "Function jQuerySelector() doesn't work."); } @Test(groups = { "Future" }) @Templates(value = { "a4jRepeat", "hDataTable", "richCollapsibleSubTable", "richDataGrid", "richDataTable", "richExtendedDataTable", "richList", "uiRepeat" }) @IssueTracking("https://issues.jboss.org/browse/RF-10465") public void testFunctionsInIterationComponents() { testFunctions(); } @Test public void testRoles() { assertUserIs(Role.NOBODY); fillInRoleAndApply("user"); assertUserIs(Role.USER); fillInRoleAndApply("admin"); assertUserIs(Role.ADMIN); fillInRoleAndApply("superhero"); assertUserIs(Role.NOBODY); } }
false
true
public void testFunctions() { String id = input.advanced().getInputElement().getAttribute("id"); String clientId = clientIdOutput.getText(); assertNotNull(clientId, "Function clientId() doesn't work."); assertNotSame(clientId, "", "Function clientId() doesn't work."); assertEquals(clientId, id, "Function clientId() doesn't work."); String output = elementOutput.getText(); assertEquals(output, "document.getElementById('" + clientId + "')", "Function element() doesn't work."); output = componentOutput.getText(); assertEquals(output, "RichFaces.$('" + clientId + "')", "Function component() doesn't work."); output = findComponentOutput.getText(); assertEquals(output, "abc", "Function findComponent() doesn't work."); input.advanced().clear(ClearType.JS).sendKeys("RichFaces"); MetamerPage.waitRequest(applyLink, WaitRequestType.HTTP).click(); output = findComponentOutput.getText(); assertEquals(output, "RichFaces", "Function findComponent() doesn't work."); output = jQuerySelectorOutput.getText(); assertEquals(output, "#form\\\\:subview\\\\:input", "Function jQuerySelector() doesn't work."); output = jQueryOutput.getText(); assertEquals(output, "jQuery(document.getElementById('" + clientId + "'))", "Function jQuerySelector() doesn't work."); }
public void testFunctions() { String id = input.advanced().getInputElement().getAttribute("id"); String clientId = clientIdOutput.getText(); assertNotNull(clientId, "Function clientId() doesn't work."); assertNotSame(clientId, "", "Function clientId() doesn't work."); assertEquals(clientId, id, "Function clientId() doesn't work."); String output = elementOutput.getText(); assertEquals(output, "document.getElementById('" + clientId + "')", "Function element() doesn't work."); output = componentOutput.getText(); assertEquals(output, "RichFaces.component('" + clientId + "')", "Function component() doesn't work."); output = findComponentOutput.getText(); assertEquals(output, "abc", "Function findComponent() doesn't work."); input.advanced().clear(ClearType.JS).sendKeys("RichFaces"); MetamerPage.waitRequest(applyLink, WaitRequestType.HTTP).click(); output = findComponentOutput.getText(); assertEquals(output, "RichFaces", "Function findComponent() doesn't work."); output = jQuerySelectorOutput.getText(); assertEquals(output, "#form\\\\:subview\\\\:input", "Function jQuerySelector() doesn't work."); output = jQueryOutput.getText(); assertEquals(output, "RichFaces.jQuery(document.getElementById('" + clientId + "'))", "Function jQuerySelector() doesn't work."); }
diff --git a/reset-pass/src/java/org/sakaiproject/tool/resetpass/ConfirmProducer.java b/reset-pass/src/java/org/sakaiproject/tool/resetpass/ConfirmProducer.java index 614192a..385e488 100644 --- a/reset-pass/src/java/org/sakaiproject/tool/resetpass/ConfirmProducer.java +++ b/reset-pass/src/java/org/sakaiproject/tool/resetpass/ConfirmProducer.java @@ -1,44 +1,44 @@ package org.sakaiproject.tool.resetpass; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UILink; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.ViewParameters; import uk.org.ponder.rsf.components.UIOutput; import org.sakaiproject.component.api.ServerConfigurationService; import org.sakaiproject.tool.resetpass.RetUser; public class ConfirmProducer implements ViewComponentProducer { public static final String VIEW_ID = "confirm"; public String getViewID() { // TODO Auto-generated method stub return VIEW_ID; } private ServerConfigurationService serverConfigurationService; public void setServerConfigurationService(ServerConfigurationService s) { this.serverConfigurationService = s; } private RetUser userBean; public void setUserBean(RetUser u){ this.userBean = u; } public void fillComponents(UIContainer tofill, ViewParameters arg1, ComponentChecker arg2) { String[] parms = new String[] {userBean.getEmail()}; UIMessage.make(tofill,"message","confirm",parms); if (serverConfigurationService.getString("support.email", null) != null) { UIMessage.make(tofill, "supportMessage", "supportMessage"); - UILink.make(tofill, "supportEmail",serverConfigurationService.getString("support.email", "")); + UILink.make(tofill, "supportEmail",serverConfigurationService.getString("support.email", ""),"mailto:" + serverConfigurationService.getString("support.email", "")); } } }
true
true
public void fillComponents(UIContainer tofill, ViewParameters arg1, ComponentChecker arg2) { String[] parms = new String[] {userBean.getEmail()}; UIMessage.make(tofill,"message","confirm",parms); if (serverConfigurationService.getString("support.email", null) != null) { UIMessage.make(tofill, "supportMessage", "supportMessage"); UILink.make(tofill, "supportEmail",serverConfigurationService.getString("support.email", "")); } }
public void fillComponents(UIContainer tofill, ViewParameters arg1, ComponentChecker arg2) { String[] parms = new String[] {userBean.getEmail()}; UIMessage.make(tofill,"message","confirm",parms); if (serverConfigurationService.getString("support.email", null) != null) { UIMessage.make(tofill, "supportMessage", "supportMessage"); UILink.make(tofill, "supportEmail",serverConfigurationService.getString("support.email", ""),"mailto:" + serverConfigurationService.getString("support.email", "")); } }
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/BlockTextArea.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/BlockTextArea.java index ca675e0cf..983be3c00 100644 --- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/BlockTextArea.java +++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/BlockTextArea.java @@ -1,109 +1,109 @@ /*********************************************************************** * Copyright (c) 2009 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.report.engine.nLayout.area.impl; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.content.ITextContent; import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil; import org.eclipse.birt.report.engine.nLayout.LayoutContext; import org.eclipse.birt.report.engine.nLayout.area.ILayout; public class BlockTextArea extends BlockContainerArea implements ILayout { public BlockTextArea( ContainerArea parent, LayoutContext context, IContent content ) { super( parent, context, content ); } public BlockTextArea(BlockTextArea area) { super(area); } public void layout( ) throws BirtException { initialize(); TextLineArea line = new TextLineArea(this, context); line.initialize( ); line.setTextIndent( (ITextContent)content ); TextAreaLayout text = new TextAreaLayout( line, context, content); text.initialize( ); text.layout( ); text.close( ); line.close( ); close(); } public BlockTextArea cloneArea() { return new BlockTextArea(this); } public boolean isPageBreakInsideAvoid( ) { if ( context.isFixedLayout( ) && specifiedHeight > 0 ) { return true; } return super.isPageBreakInsideAvoid( ); } protected void update( ) throws BirtException { if ( parent != null ) { if ( context.isFixedLayout( ) && height > specifiedHeight ) { setHeight( specifiedHeight ); setNeedClip( true ); } if ( !isInInlineStacking && context.isAutoPageBreak( ) ) { int aHeight = getAllocatedHeight( ); int size = children.size( ); if ( ( aHeight + parent.getAbsoluteBP( ) > context.getMaxBP( ) ) && ( size > 1 ) ) { IStyle style = content.getComputedStyle( ); // Minimum number of lines of a paragraph that must appear // at the top of a page. - int widow = PropertyUtil.getIntValue( style - .getProperty( IStyle.STYLE_WIDOWS ) ); + int widow = Math.min( size, PropertyUtil.getIntValue( style + .getProperty( IStyle.STYLE_WIDOWS ) )); // Minimum number of lines of a paragraph that must appear // at the bottom of a page. - int orphan = PropertyUtil.getIntValue( style - .getProperty( IStyle.STYLE_ORPHANS ) ); + int orphan = Math.min( size, PropertyUtil.getIntValue( style + .getProperty( IStyle.STYLE_ORPHANS ) )); for ( int i = 0; i < size; i++ ) { TextLineArea line = (TextLineArea) children.get( i ); if ( i > 0 && i < orphan ) { line.setPageBreakBefore( IStyle.AVOID_VALUE ); } else if ( i > size - widow ) { line.setPageBreakBefore( IStyle.AVOID_VALUE ); } } } while ( aHeight + parent.getAbsoluteBP( ) >= context.getMaxBP( ) ) { parent.autoPageBreak( ); aHeight = getAllocatedHeight( ); } } parent.update( this ); } } }
false
true
protected void update( ) throws BirtException { if ( parent != null ) { if ( context.isFixedLayout( ) && height > specifiedHeight ) { setHeight( specifiedHeight ); setNeedClip( true ); } if ( !isInInlineStacking && context.isAutoPageBreak( ) ) { int aHeight = getAllocatedHeight( ); int size = children.size( ); if ( ( aHeight + parent.getAbsoluteBP( ) > context.getMaxBP( ) ) && ( size > 1 ) ) { IStyle style = content.getComputedStyle( ); // Minimum number of lines of a paragraph that must appear // at the top of a page. int widow = PropertyUtil.getIntValue( style .getProperty( IStyle.STYLE_WIDOWS ) ); // Minimum number of lines of a paragraph that must appear // at the bottom of a page. int orphan = PropertyUtil.getIntValue( style .getProperty( IStyle.STYLE_ORPHANS ) ); for ( int i = 0; i < size; i++ ) { TextLineArea line = (TextLineArea) children.get( i ); if ( i > 0 && i < orphan ) { line.setPageBreakBefore( IStyle.AVOID_VALUE ); } else if ( i > size - widow ) { line.setPageBreakBefore( IStyle.AVOID_VALUE ); } } } while ( aHeight + parent.getAbsoluteBP( ) >= context.getMaxBP( ) ) { parent.autoPageBreak( ); aHeight = getAllocatedHeight( ); } } parent.update( this ); } }
protected void update( ) throws BirtException { if ( parent != null ) { if ( context.isFixedLayout( ) && height > specifiedHeight ) { setHeight( specifiedHeight ); setNeedClip( true ); } if ( !isInInlineStacking && context.isAutoPageBreak( ) ) { int aHeight = getAllocatedHeight( ); int size = children.size( ); if ( ( aHeight + parent.getAbsoluteBP( ) > context.getMaxBP( ) ) && ( size > 1 ) ) { IStyle style = content.getComputedStyle( ); // Minimum number of lines of a paragraph that must appear // at the top of a page. int widow = Math.min( size, PropertyUtil.getIntValue( style .getProperty( IStyle.STYLE_WIDOWS ) )); // Minimum number of lines of a paragraph that must appear // at the bottom of a page. int orphan = Math.min( size, PropertyUtil.getIntValue( style .getProperty( IStyle.STYLE_ORPHANS ) )); for ( int i = 0; i < size; i++ ) { TextLineArea line = (TextLineArea) children.get( i ); if ( i > 0 && i < orphan ) { line.setPageBreakBefore( IStyle.AVOID_VALUE ); } else if ( i > size - widow ) { line.setPageBreakBefore( IStyle.AVOID_VALUE ); } } } while ( aHeight + parent.getAbsoluteBP( ) >= context.getMaxBP( ) ) { parent.autoPageBreak( ); aHeight = getAllocatedHeight( ); } } parent.update( this ); } }
diff --git a/errai-bus/src/main/java/org/jboss/errai/bus/server/io/MessageFactory.java b/errai-bus/src/main/java/org/jboss/errai/bus/server/io/MessageFactory.java index 68ff5f91a..2fc50dd05 100644 --- a/errai-bus/src/main/java/org/jboss/errai/bus/server/io/MessageFactory.java +++ b/errai-bus/src/main/java/org/jboss/errai/bus/server/io/MessageFactory.java @@ -1,161 +1,164 @@ /* * Copyright 2012 JBoss, by Red Hat, 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.jboss.errai.bus.server.io; import org.jboss.errai.bus.client.api.messaging.Message; import org.jboss.errai.bus.client.api.QueueSession; import org.jboss.errai.bus.client.api.RoutingFlag; import org.jboss.errai.common.client.protocols.MessageParts; import org.jboss.errai.marshalling.client.api.json.EJArray; import org.jboss.errai.marshalling.client.api.json.EJValue; import org.jboss.errai.marshalling.client.marshallers.ErraiProtocolEnvelopeMarshaller; import org.jboss.errai.marshalling.server.DecodingSession; import org.jboss.errai.marshalling.server.JSONDecoder; import org.jboss.errai.marshalling.server.JSONStreamDecoder; import org.jboss.errai.marshalling.server.MappingContextSingleton; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import static org.jboss.errai.bus.client.api.base.CommandMessage.createWithParts; import static org.jboss.errai.bus.client.api.base.CommandMessage.createWithPartsFromRawMap; /** * The <tt>MessageFactory</tt> facilitates the building of a command message using a JSON string */ public class MessageFactory { /** * Decodes a JSON string to a map (string name -> object) * * @param in - JSON string * @return map representing the string */ public static Map<String, Object> decodeToMap(String in) { //noinspection unchecked return (Map<String, Object>) JSONDecoder.decode(in); } /** * Creates the command message from the given JSON string and session. The message is constructed in * parts depending on the string * * @param session - the queue session in which the message exists * @param request - * @param json - the string representing the parts of the message * @return the message array constructed using the JSON string */ public static Message createCommandMessage(QueueSession session, HttpServletRequest request, String json) { if (json.length() == 0) return null; Map<String, Object> parts = decodeToMap(json); parts.remove(MessageParts.SessionID.name()); return from(parts, session, request); } @SuppressWarnings("unchecked") public static Message createCommandMessage(QueueSession session, String json) { if (json.length() == 0) return null; Message msg = createWithPartsFromRawMap(ErraiProtocolEnvelopeMarshaller.INSTANCE.demarshall(JSONDecoder.decode(json), new DecodingSession(MappingContextSingleton.get()))) .setResource("Session", session) .setResource("SessionID", session.getSessionId()); msg.setFlag(RoutingFlag.FromRemote); return msg; } public static List<Message> createCommandMessage(QueueSession session, HttpServletRequest request) throws IOException { EJValue value = JSONStreamDecoder.decode(request.getInputStream()); if (value.isObject() != null) { return Collections.singletonList(from(getParts(value), session, request)); } else if (value.isArray() != null) { EJArray arr = value.isArray(); List<Message> messages = new ArrayList<Message>(arr.size()); for (int i = 0; i < arr.size(); i++) { messages.add(from(getParts(arr.get(i)), session, request)); } return messages; } + else if (value.isNull()) { + return Collections.<Message>emptyList(); + } else { throw new RuntimeException("bad payload"); } } public static List<Message> createCommandMessage(QueueSession session, InputStream inputStream) throws IOException { EJValue value = JSONStreamDecoder.decode(inputStream); if (value.isObject() != null) { return Collections.singletonList(from(getParts(value), session, null)); } else if (value.isArray() != null) { EJArray arr = value.isArray(); List<Message> messages = new ArrayList<Message>(arr.size()); for (int i = 0; i < arr.size(); i++) { messages.add(from(getParts(arr.get(i)), session, null)); } return messages; } else { throw new RuntimeException("bad payload"); } } public static List<Message> createCommandMessage(QueueSession session, EJValue value) { if (value.isObject() != null) { return Collections.singletonList(from(getParts(value), session, null)); } else if (value.isArray() != null) { EJArray arr = value.isArray(); List<Message> messages = new ArrayList<Message>(arr.size()); for (int i = 0; i < arr.size(); i++) { messages.add(from(getParts(arr.get(i)), session, null)); } return messages; } else { throw new RuntimeException("bad payload"); } } private static Map getParts(EJValue value) { return ErraiProtocolEnvelopeMarshaller.INSTANCE.demarshall(value, new DecodingSession(MappingContextSingleton.get())); } @SuppressWarnings("unchecked") private static Message from(Map parts, QueueSession session, HttpServletRequest request) { Message msg = createWithParts(parts) .setResource("Session", session) .setResource("SessionID", session.getSessionId()) .setResource(HttpServletRequest.class.getName(), request); msg.setFlag(RoutingFlag.FromRemote); return msg; } }
true
true
public static List<Message> createCommandMessage(QueueSession session, HttpServletRequest request) throws IOException { EJValue value = JSONStreamDecoder.decode(request.getInputStream()); if (value.isObject() != null) { return Collections.singletonList(from(getParts(value), session, request)); } else if (value.isArray() != null) { EJArray arr = value.isArray(); List<Message> messages = new ArrayList<Message>(arr.size()); for (int i = 0; i < arr.size(); i++) { messages.add(from(getParts(arr.get(i)), session, request)); } return messages; } else { throw new RuntimeException("bad payload"); } }
public static List<Message> createCommandMessage(QueueSession session, HttpServletRequest request) throws IOException { EJValue value = JSONStreamDecoder.decode(request.getInputStream()); if (value.isObject() != null) { return Collections.singletonList(from(getParts(value), session, request)); } else if (value.isArray() != null) { EJArray arr = value.isArray(); List<Message> messages = new ArrayList<Message>(arr.size()); for (int i = 0; i < arr.size(); i++) { messages.add(from(getParts(arr.get(i)), session, request)); } return messages; } else if (value.isNull()) { return Collections.<Message>emptyList(); } else { throw new RuntimeException("bad payload"); } }
diff --git a/src/org/opensolaris/opengrok/util/Executor.java b/src/org/opensolaris/opengrok/util/Executor.java index 0175d45d..b047c83a 100644 --- a/src/org/opensolaris/opengrok/util/Executor.java +++ b/src/org/opensolaris/opengrok/util/Executor.java @@ -1,132 +1,132 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ package org.opensolaris.opengrok.util; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.List; import java.util.logging.Level; import org.opensolaris.opengrok.OpenGrokLogger; /** * Wrapper to Java Process API * * @author Emilio Monti - [email protected] */ public class Executor { private List<String> cmdList; private File workingDirectory; private String stdoutString = ""; private String stderrString = ""; public Executor(List<String> cmdList) { this(cmdList, null); } public Executor(List<String> cmdList, File workingDirectory) { this.cmdList = cmdList; this.workingDirectory = workingDirectory; } public void exec() { ProcessBuilder processBuilder = new ProcessBuilder(cmdList); if (workingDirectory != null) { processBuilder.directory(workingDirectory); } StringPipe stdout = new StringPipe(); StringPipe stderr = new StringPipe(); Process process = null; try { process = processBuilder.start(); stdout.startListen(process.getInputStream()); stderr.startListen(process.getErrorStream()); process.waitFor(); stdout.join(); stderr.join(); stdoutString = stdout.getString(); - stderrString = stdout.getString(); + stderrString = stderr.getString(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to read from process: " + cmdList.get(0), e); } catch (InterruptedException e) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Waiting for process interrupted: " + cmdList.get(0), e); } finally { try { if (process != null) { process.exitValue(); } } catch (IllegalThreadStateException e) { process.destroy(); } } } public String get_stdout() { return stdoutString; } public BufferedReader get_stdout_reader() { return new BufferedReader(new StringReader(stdoutString)); } public String get_stderr() { return stderrString; } public BufferedReader get_stderr_reader() { return new BufferedReader(new StringReader(stderrString)); } private static class StringPipe extends Thread { private InputStream input = null; private String output = null; void startListen(InputStream is) { input = is; this.start(); } @Override public void run() { try { int byteIn; StringBuffer sb = new StringBuffer(); while ((byteIn = input.read()) != -1) { sb.append((char) byteIn); } output = sb.toString(); } catch (IOException ioe) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Error during process pipe listening", ioe); } } public String getString() { return output; } } }
true
true
public void exec() { ProcessBuilder processBuilder = new ProcessBuilder(cmdList); if (workingDirectory != null) { processBuilder.directory(workingDirectory); } StringPipe stdout = new StringPipe(); StringPipe stderr = new StringPipe(); Process process = null; try { process = processBuilder.start(); stdout.startListen(process.getInputStream()); stderr.startListen(process.getErrorStream()); process.waitFor(); stdout.join(); stderr.join(); stdoutString = stdout.getString(); stderrString = stdout.getString(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to read from process: " + cmdList.get(0), e); } catch (InterruptedException e) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Waiting for process interrupted: " + cmdList.get(0), e); } finally { try { if (process != null) { process.exitValue(); } } catch (IllegalThreadStateException e) { process.destroy(); } } }
public void exec() { ProcessBuilder processBuilder = new ProcessBuilder(cmdList); if (workingDirectory != null) { processBuilder.directory(workingDirectory); } StringPipe stdout = new StringPipe(); StringPipe stderr = new StringPipe(); Process process = null; try { process = processBuilder.start(); stdout.startListen(process.getInputStream()); stderr.startListen(process.getErrorStream()); process.waitFor(); stdout.join(); stderr.join(); stdoutString = stdout.getString(); stderrString = stderr.getString(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Failed to read from process: " + cmdList.get(0), e); } catch (InterruptedException e) { OpenGrokLogger.getLogger().log(Level.SEVERE, "Waiting for process interrupted: " + cmdList.get(0), e); } finally { try { if (process != null) { process.exitValue(); } } catch (IllegalThreadStateException e) { process.destroy(); } } }
diff --git a/src/com/me/ifly6/Console.java b/src/com/me/ifly6/Console.java index 1e0cd81..aa5d29c 100644 --- a/src/com/me/ifly6/Console.java +++ b/src/com/me/ifly6/Console.java @@ -1,359 +1,359 @@ package com.me.ifly6; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.InetAddress; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.*; import javax.swing.text.DefaultCaret; public class Console extends JFrame implements KeyListener, ActionListener{ /* * THINGS TO DO: * IMPLEMENT A CHANGE DIRECTORY SYSTEM. * FIX THE SWTICH SCREEN MECHANISM */ private static final long serialVersionUID = 1L; // SWING DATA JPanel pane = new JPanel(); static JTextArea output = new JTextArea(); static JTextArea log = new JTextArea(); static JTextField input = new JTextField(); JScrollPane scp = new JScrollPane(output); // INTERNAL DATA static String t1; static String[] t2; static String computername = "Unknown"; static String[] mem = new String[10]; static final String starter = "\n == iUtilities Console " + Info.version + " == " + "\n Hello " + System.getProperty("user.name") + "!" + "\n Type 'help' for help."; static String helpstring = ("\n == Help Menu ==" + "\n * Commands: 'acknowledgements', 'changelog', 'copyright', '/clear'" + "\n * Most (but not all) bash commands are accepted, and will run."); static int status; // MENUBAR DATA JMenuBar menubar = new JMenuBar(); JMenu menufile = new JMenu("File"); JMenu menucomm = new JMenu("Commands"); JMenu menuview = new JMenu("View"); JMenu menuhelp = new JMenu("Help"); JMenuItem export = new JMenuItem("Exportation"); JMenuItem script = new JMenuItem("Script Input"); JMenuItem mindterm = new JMenuItem("Mindterm"); JMenuItem purge = new JMenuItem("Inactive Memory Purge"); JMenuItem debug = new JMenuItem("Log Console"); JMenuItem info = new JMenuItem("System Readout"); JMenuItem ping = new JMenuItem("Ping Utility"); JMenuItem clear = new JMenuItem("Clear Screen"); JMenuItem viewswitch = new JMenuItem("Switch View"); JMenuItem del = new JMenuItem("Delete iUtilities Files"); JMenuItem term = new JMenuItem("Terminate"); JMenuItem about = new JMenuItem("About"); JMenuItem help = new JMenuItem("Help"); JMenuItem updates = new JMenuItem("Updates"); Console() { // Base GUI, in Swing. super("iUtilities " + Info.version); setBounds(50, 50, 670, 735); setDefaultCloseOperation(DISPOSE_ON_CLOSE); Container con = getContentPane(); getContentPane().setLayout(new BorderLayout()); con.add(this.pane); pane.setLayout(new BorderLayout()); pane.add(scp, BorderLayout.CENTER); pane.add(input, BorderLayout.SOUTH); output.setEditable(false); input.addKeyListener(this); Font font = new Font("Monaco", 0, 11); output.setFont(font); output.setBackground(Color.black); output.setForeground(Color.green); input.setFont(font); input.setBackground(Color.black); input.setForeground(Color.green); input.setCaretColor(Color.green); this.pane.setBackground(Color.DARK_GRAY); DefaultCaret caret = (DefaultCaret)output.getCaret(); caret.setUpdatePolicy(2); // MENUBAR CREATION menubar.add(menufile); menubar.add(menucomm); menubar.add(menuview); menubar.add(menuhelp); // File menufile.add(export); menufile.add(script); menufile.add(mindterm); export.addActionListener(this); script.addActionListener(this); mindterm.addActionListener(this); // Commands menucomm.add(purge); menucomm.add(debug); menucomm.add(info); menucomm.add(ping); purge.addActionListener(this); debug.addActionListener(this); info.addActionListener(this); ping.addActionListener(this); // View menuview.add(clear); menuview.add(viewswitch); menuview.add(del); menuview.add(term); clear.addActionListener(this); viewswitch.addActionListener(this); term.addActionListener(this); del.addActionListener(this); // Help menuhelp.add(about); menuhelp.add(help); menuhelp.add(updates); about.addActionListener(this); help.addActionListener(this); updates.addActionListener(this); pane.add(menubar, BorderLayout.NORTH); setVisible(true); log.append("\nJava Swing GUI Initialised and Rendered"); } // MAIN THREAD. public static void main(String[] args) { new Console(); output.append(starter); try { computername = InetAddress.getLocalHost().getHostName(); } catch (Exception localException) { } @SuppressWarnings("unused") DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); log.append("\niUtilities " + Info.version + " Initialised. Date: " + date); status = 0; } // EVENT HANDLER public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == 10) { try { processing(null); } catch (InterruptedException e1) { log.append("\nkeyPressed Error"); } catch (IOException e1) { log.append("\nkeyPressed Error"); } } if (keyCode == 38){ input.setText(t1); } } public void keyReleased(KeyEvent arg0) { } public void keyTyped(KeyEvent arg0) { } // ACTIONPREFORMED LISTENER FOR ALL THE DAMN BUTTONS public void actionPerformed(ActionEvent e) { Object eventSource = e.getSource(); if (eventSource == export) { - output.append("\n" + computername + "~ $ File>Export"); + output.append("\n" + computername + "~ $ File>Export "); try { Addons.save(null); } catch (IOException e1) { log.append("\nExport Failed, IOException"); } } if (eventSource == script) { output.append("\n" + computername + "~ $ File>Script"); Addons.script(); log.append("Script Look Executed. May or may not have run."); } if (eventSource == mindterm) { output.append("\n" + computername + "~ $ File>Mindterm"); try { Addons.mindterm(); } catch (IOException e1) { log.append("\nMindterm Download Failed: IOException"); } log.append("\nMindterm Download Commenced."); } if (eventSource == purge) { output.append("\n" + computername + "~ $ Command>Purge"); try { Addons.purge(null); } catch (IOException e1) { log.append("\nPurge Failed: IOException");} } if (eventSource == debug) { output.append("\n" + computername + "~ $ Command>Debug"); try { Addons.debug(null); } catch (IOException e1) { log.append("\nBug JTextArea Export Failed: IOException"); } } if (eventSource == info){ output.append("\n" + computername + "~ $ Command>System Readout"); try { Addons.info(null); } catch (InterruptedException e1) { log.append("\nInformation Not Exported: InterruptedException"); } catch (IOException e1) { log.append("\nInformation Not Exported: IOException"); } } if (eventSource == ping){ input.setText("ping -c 1 "); log.append("\nPing Shortcut Accessed."); } if (eventSource == clear){ output.setText(starter); log.append("\nConsole Text Cleared"); } // Needs Work if (eventSource == viewswitch){ output.append("\n" + computername + "~ $ View>Switch View"); if (status == 0){ output.setText(null); Console.output.setText(Console.log.getText()); output.append("\nViewSwitched to Debug"); try { Thread.sleep(50); } catch (InterruptedException e1) { } status = 1; } if (status == 1){ output.setText(starter); try { Thread.sleep(50); } catch (InterruptedException e1) { } status = 0; log.append("\nViewSwitched to Output"); } } if (eventSource == del){ output.append("\n" + computername + "~ $ View>Delete iUtilities Files"); try { Addons.delete(null); } catch (IOException e1) { log.append("\nDeletion Failed: IOException"); } output.append("\nAll iUtilities files in ~/Library/Application Support/iUtilities have been deleted."); } if (eventSource == term){ output.append("\n" + computername + "~ $ View>Terminate"); log.append("\nTermination of Programme Switched"); System.exit(0); } if (eventSource == about) { output.append("\n" + computername + "~ $ Help>About"); output.append("\n== About iUtilities " + Info.version ); output.append("\n" + Info.copyright); output.append("\nVersion " + Info.version + " '" + Info.password + "'"); } if (eventSource == help){ output.append("\n" + computername + "~ $ Help>Help"); output.append(helpstring); } if (eventSource == updates){ output.append("\n" + computername + "~ $ Help>Updates"); // Fix THIS } } // PROCESSING STREAM public static void processing(String[] args) throws InterruptedException, IOException { t1 = input.getText(); output.append("\n" + computername + "~ $ " + t1); input.setText(null); t2 = t1.split(" "); // Sub-commands Runtime rt = Runtime.getRuntime(); if (t2[0].equals("changelog")) { try { String userName = System.getProperty("user.name"); File folder = new File("/Users/" + userName + "/Library/Application Support/iUtilities"); folder.mkdirs(); String[] url = { "curl","-o","/Users/" + userName + "/Library/Application Support/iUtilities/changelog.txt", "http://ifly6server.no-ip.org/iUtilities/changelog.txt" }; rt.exec(url); String r = "\n"; FileReader fstream = new FileReader("/Users/" + userName + "/Library/Application Support/iUtilities/changelog.txt"); BufferedReader br = new BufferedReader(fstream); r = br.readLine(); while ((r = br.readLine()) != null) output.append("\n " + r); } catch (IOException localIOException) { log.append("\nChangelog Failed: IOException"); } log.append("\nChangelog Processing Trigger Invoked."); } if (t2[0].equals("copyright")) { output.append("\n" + Info.copyright); log.append("\nCopyright Processing Trigger Invoked"); } if (t2[0].equals("help")) { output.append(helpstring); log.append("\nHelp Processing Trigger Invoked"); } if (t2[0].equals("/clear")) { output.setText(starter); log.append("\nCommand to Clear Screen Invoked"); } if (t2[0].equals("acknowledgements")) { try { String userName = System.getProperty("user.name"); File folder = new File("/Users/" + userName + "/Library/Application Support/iUtilities"); folder.mkdirs(); String[] url = { "curl", "-o", "/Users/" + userName + "/Library/Application Support/iUtilities/acknowledgements.txt", "http://ifly6server.no-ip.org/iUtilities/acknowledgements.txt" }; ProcessBuilder builder = new ProcessBuilder(url); builder.start(); String r = "\n"; FileReader fstream = new FileReader("/Users/" + userName + "/Library/Application Support/iUtilities/acknowledgements.txt"); BufferedReader br = new BufferedReader(fstream); r = br.readLine(); while ((r = br.readLine()) != null) output.append("\n " + r); } catch (IOException localIOException2) { log.append("\nAcknowledgements Failed: IOException"); } log.append("\nAcknowledgements Processing Trigger Invoked"); } if (t2[0].equals("/font")){ int tmp; if (t2[2].equals(null)){ tmp = 11; } tmp = java.lang.Integer.parseInt(t2[2]); Font font = new Font(t2[1], 0, tmp); output.setFont(font); } // ProcessBuilder Calling System else { if ((!t2[0].equals("bash"))) { exec(null); log.append("\nBASH COMMAND INVOKED: " + t1); } } } // EXECUTION STREAM public static void exec(String[] args) throws IOException{ // Output Stream ProcessBuilder builder = new ProcessBuilder(t2); Process process = builder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { output.append("\n" + line); } // Error Stream InputStream stderr1 = process.getErrorStream(); InputStreamReader isr1 = new InputStreamReader(stderr1); BufferedReader br1 = new BufferedReader(isr1); String line1 = null; while ((line1 = br1.readLine()) != null) output.append("\n " + line1); } }
true
true
public void actionPerformed(ActionEvent e) { Object eventSource = e.getSource(); if (eventSource == export) { output.append("\n" + computername + "~ $ File>Export"); try { Addons.save(null); } catch (IOException e1) { log.append("\nExport Failed, IOException"); } } if (eventSource == script) { output.append("\n" + computername + "~ $ File>Script"); Addons.script(); log.append("Script Look Executed. May or may not have run."); } if (eventSource == mindterm) { output.append("\n" + computername + "~ $ File>Mindterm"); try { Addons.mindterm(); } catch (IOException e1) { log.append("\nMindterm Download Failed: IOException"); } log.append("\nMindterm Download Commenced."); } if (eventSource == purge) { output.append("\n" + computername + "~ $ Command>Purge"); try { Addons.purge(null); } catch (IOException e1) { log.append("\nPurge Failed: IOException");} } if (eventSource == debug) { output.append("\n" + computername + "~ $ Command>Debug"); try { Addons.debug(null); } catch (IOException e1) { log.append("\nBug JTextArea Export Failed: IOException"); } } if (eventSource == info){ output.append("\n" + computername + "~ $ Command>System Readout"); try { Addons.info(null); } catch (InterruptedException e1) { log.append("\nInformation Not Exported: InterruptedException"); } catch (IOException e1) { log.append("\nInformation Not Exported: IOException"); } } if (eventSource == ping){ input.setText("ping -c 1 "); log.append("\nPing Shortcut Accessed."); } if (eventSource == clear){ output.setText(starter); log.append("\nConsole Text Cleared"); } // Needs Work if (eventSource == viewswitch){ output.append("\n" + computername + "~ $ View>Switch View"); if (status == 0){ output.setText(null); Console.output.setText(Console.log.getText()); output.append("\nViewSwitched to Debug"); try { Thread.sleep(50); } catch (InterruptedException e1) { } status = 1; } if (status == 1){ output.setText(starter); try { Thread.sleep(50); } catch (InterruptedException e1) { } status = 0; log.append("\nViewSwitched to Output"); } } if (eventSource == del){ output.append("\n" + computername + "~ $ View>Delete iUtilities Files"); try { Addons.delete(null); } catch (IOException e1) { log.append("\nDeletion Failed: IOException"); } output.append("\nAll iUtilities files in ~/Library/Application Support/iUtilities have been deleted."); } if (eventSource == term){ output.append("\n" + computername + "~ $ View>Terminate"); log.append("\nTermination of Programme Switched"); System.exit(0); } if (eventSource == about) { output.append("\n" + computername + "~ $ Help>About"); output.append("\n== About iUtilities " + Info.version ); output.append("\n" + Info.copyright); output.append("\nVersion " + Info.version + " '" + Info.password + "'"); } if (eventSource == help){ output.append("\n" + computername + "~ $ Help>Help"); output.append(helpstring); } if (eventSource == updates){ output.append("\n" + computername + "~ $ Help>Updates"); // Fix THIS } }
public void actionPerformed(ActionEvent e) { Object eventSource = e.getSource(); if (eventSource == export) { output.append("\n" + computername + "~ $ File>Export "); try { Addons.save(null); } catch (IOException e1) { log.append("\nExport Failed, IOException"); } } if (eventSource == script) { output.append("\n" + computername + "~ $ File>Script"); Addons.script(); log.append("Script Look Executed. May or may not have run."); } if (eventSource == mindterm) { output.append("\n" + computername + "~ $ File>Mindterm"); try { Addons.mindterm(); } catch (IOException e1) { log.append("\nMindterm Download Failed: IOException"); } log.append("\nMindterm Download Commenced."); } if (eventSource == purge) { output.append("\n" + computername + "~ $ Command>Purge"); try { Addons.purge(null); } catch (IOException e1) { log.append("\nPurge Failed: IOException");} } if (eventSource == debug) { output.append("\n" + computername + "~ $ Command>Debug"); try { Addons.debug(null); } catch (IOException e1) { log.append("\nBug JTextArea Export Failed: IOException"); } } if (eventSource == info){ output.append("\n" + computername + "~ $ Command>System Readout"); try { Addons.info(null); } catch (InterruptedException e1) { log.append("\nInformation Not Exported: InterruptedException"); } catch (IOException e1) { log.append("\nInformation Not Exported: IOException"); } } if (eventSource == ping){ input.setText("ping -c 1 "); log.append("\nPing Shortcut Accessed."); } if (eventSource == clear){ output.setText(starter); log.append("\nConsole Text Cleared"); } // Needs Work if (eventSource == viewswitch){ output.append("\n" + computername + "~ $ View>Switch View"); if (status == 0){ output.setText(null); Console.output.setText(Console.log.getText()); output.append("\nViewSwitched to Debug"); try { Thread.sleep(50); } catch (InterruptedException e1) { } status = 1; } if (status == 1){ output.setText(starter); try { Thread.sleep(50); } catch (InterruptedException e1) { } status = 0; log.append("\nViewSwitched to Output"); } } if (eventSource == del){ output.append("\n" + computername + "~ $ View>Delete iUtilities Files"); try { Addons.delete(null); } catch (IOException e1) { log.append("\nDeletion Failed: IOException"); } output.append("\nAll iUtilities files in ~/Library/Application Support/iUtilities have been deleted."); } if (eventSource == term){ output.append("\n" + computername + "~ $ View>Terminate"); log.append("\nTermination of Programme Switched"); System.exit(0); } if (eventSource == about) { output.append("\n" + computername + "~ $ Help>About"); output.append("\n== About iUtilities " + Info.version ); output.append("\n" + Info.copyright); output.append("\nVersion " + Info.version + " '" + Info.password + "'"); } if (eventSource == help){ output.append("\n" + computername + "~ $ Help>Help"); output.append(helpstring); } if (eventSource == updates){ output.append("\n" + computername + "~ $ Help>Updates"); // Fix THIS } }
diff --git a/src/main/java/org/exoplatform/treesync/diff/DiffChangeIterator.java b/src/main/java/org/exoplatform/treesync/diff/DiffChangeIterator.java index 28dfc77..092299c 100644 --- a/src/main/java/org/exoplatform/treesync/diff/DiffChangeIterator.java +++ b/src/main/java/org/exoplatform/treesync/diff/DiffChangeIterator.java @@ -1,250 +1,250 @@ /* * Copyright (C) 2011 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.treesync.diff; import org.exoplatform.treesync.SyncContext; import org.exoplatform.treesync.lcs.LCSChangeIterator; import org.exoplatform.treesync.lcs.LCS; import java.util.*; /** * @author <a href="mailto:[email protected]">Julien Viet</a> */ public class DiffChangeIterator<L1, N1, L2, N2, H> implements Iterator<DiffChangeType> { /** . */ private final Diff<L1, N1, L2, N2, H> diff; /** . */ private Frame frame; /** . */ private final SyncContext<L1, N1, H> context1; /** . */ private final SyncContext<L2, N2, H> context2; DiffChangeIterator(Diff<L1, N1, L2, N2, H> diff, SyncContext<L1, N1, H> context1, SyncContext<L2, N2, H> context2) { this.diff = diff; this.context1 = context1; this.context2 = context2; this.frame = new Frame(null, context1.getRoot(), context2.getRoot()); } /** * The internal status. */ private enum Status { INIT(null), ENTER(DiffChangeType.ENTER), ADDED(DiffChangeType.ADDED), REMOVED(DiffChangeType.REMOVED), MOVED_IN(DiffChangeType.MOVED_IN), MOVED_OUT(DiffChangeType.MOVED_OUT), LEAVE(DiffChangeType.LEAVE), ERROR(DiffChangeType.ERROR), CONTINUE(null); /** The associated change type. */ final DiffChangeType changeType; private Status(DiffChangeType changeType) { this.changeType = changeType; } } private class Frame { /** . */ private final Frame parent; /** . */ private N1 node1; /** . */ private N2 node2; /** . */ private L1 children1; /** . */ private Iterator<H> it1; /** . */ private L2 children2; /** . */ private Iterator<H> it2; /** . */ private LCSChangeIterator<L1, L2, H> it; /** . */ private Status previous; /** . */ private Status next; /** . */ private N1 source; /** . */ private N2 destination; private Frame(Frame parent, N1 node1, N2 node2) { this.parent = parent; this.node1 = node1; this.node2 = node2; this.previous = Status.INIT; } } public boolean hasNext() { if (frame != null) { if (frame.next == null) { switch (frame.previous) { case INIT: H id1 = context1.getModel().getHandle(frame.node1); H id2 = context2.getModel().getHandle(frame.node2); if (diff.comparator.compare(id1, id2) != 0) { frame.next = Status.ERROR; frame.source = frame.node1; frame.destination = frame.node2; } else { frame.next = Status.ENTER; frame.source = frame.node1; frame.destination = frame.node2; } break; case ERROR: break; case LEAVE: frame = frame.parent; if (frame != null) { frame.previous = Status.CONTINUE; return hasNext(); } else { return false; } case MOVED_IN: frame = new Frame(frame, frame.source, frame.destination); return hasNext(); case ENTER: frame.children1 = context1.getModel().getChildren(frame.node1); frame.it1 = diff.adapter1.iterator(frame.children1, false); frame.children2 = context2.getModel().getChildren(frame.node2); frame.it2 = diff.adapter2.iterator(frame.children2, false); frame.it = LCS.create( diff.adapter1, diff.adapter2, diff.comparator).perform(frame.children1, frame.children2); case ADDED: case REMOVED: case MOVED_OUT: case CONTINUE: if (frame.it.hasNext()) { switch (frame.it.next()) { case KEEP: - N1 next1 = context1.getModel().getDescendant(frame.node1, frame.it1.next()); - N2 next2 = context2.getModel().getDescendant(frame.node2, frame.it2.next()); + N1 next1 = context1.findByHandle(frame.it1.next()); + N2 next2 = context2.findByHandle(frame.it2.next()); frame = new Frame(frame, next1, next2); return hasNext(); case ADD: frame.it2.next(); H addedHandle = frame.it.getElement(); - N2 added = context2.getModel().getDescendant(frame.node2, addedHandle); + N2 added = context2.findByHandle(addedHandle); H addedId = context2.getModel().getHandle(added); N1 a = context1.findByHandle(addedId); if (a != null) { frame.next = Status.MOVED_IN; frame.source = a; frame.destination = added; } else { frame.next = Status.ADDED; frame.source = null; frame.destination = added; } break; case REMOVE: frame.it1.next(); H removedHandle = frame.it.getElement(); - N1 removed = context1.getModel().getDescendant(frame.node1, removedHandle); + N1 removed = context1.findByHandle(removedHandle); H removedId = context1.getModel().getHandle(removed); N2 b = context2.findByHandle(removedId); if (b != null) { frame.next = Status.MOVED_OUT; frame.source = removed; frame.destination = b; } else { frame.next = Status.REMOVED; frame.source = removed; frame.destination = null; } break; default: throw new AssertionError(); } } else { frame.next = Status.LEAVE; frame.source = frame.node1; frame.destination = frame.node2; } break; default: throw new AssertionError("Was not expecting status " + frame.previous); } } return frame.next != null; } return false; } public DiffChangeType next() { if (!hasNext()) { throw new NoSuchElementException(); } else { frame.previous = frame.next; frame.next = null; return frame.previous.changeType; } } public N1 getSource() { return frame.source; } public N2 getDestination() { return frame.destination; } public void remove() { throw new UnsupportedOperationException(); } }
false
true
public boolean hasNext() { if (frame != null) { if (frame.next == null) { switch (frame.previous) { case INIT: H id1 = context1.getModel().getHandle(frame.node1); H id2 = context2.getModel().getHandle(frame.node2); if (diff.comparator.compare(id1, id2) != 0) { frame.next = Status.ERROR; frame.source = frame.node1; frame.destination = frame.node2; } else { frame.next = Status.ENTER; frame.source = frame.node1; frame.destination = frame.node2; } break; case ERROR: break; case LEAVE: frame = frame.parent; if (frame != null) { frame.previous = Status.CONTINUE; return hasNext(); } else { return false; } case MOVED_IN: frame = new Frame(frame, frame.source, frame.destination); return hasNext(); case ENTER: frame.children1 = context1.getModel().getChildren(frame.node1); frame.it1 = diff.adapter1.iterator(frame.children1, false); frame.children2 = context2.getModel().getChildren(frame.node2); frame.it2 = diff.adapter2.iterator(frame.children2, false); frame.it = LCS.create( diff.adapter1, diff.adapter2, diff.comparator).perform(frame.children1, frame.children2); case ADDED: case REMOVED: case MOVED_OUT: case CONTINUE: if (frame.it.hasNext()) { switch (frame.it.next()) { case KEEP: N1 next1 = context1.getModel().getDescendant(frame.node1, frame.it1.next()); N2 next2 = context2.getModel().getDescendant(frame.node2, frame.it2.next()); frame = new Frame(frame, next1, next2); return hasNext(); case ADD: frame.it2.next(); H addedHandle = frame.it.getElement(); N2 added = context2.getModel().getDescendant(frame.node2, addedHandle); H addedId = context2.getModel().getHandle(added); N1 a = context1.findByHandle(addedId); if (a != null) { frame.next = Status.MOVED_IN; frame.source = a; frame.destination = added; } else { frame.next = Status.ADDED; frame.source = null; frame.destination = added; } break; case REMOVE: frame.it1.next(); H removedHandle = frame.it.getElement(); N1 removed = context1.getModel().getDescendant(frame.node1, removedHandle); H removedId = context1.getModel().getHandle(removed); N2 b = context2.findByHandle(removedId); if (b != null) { frame.next = Status.MOVED_OUT; frame.source = removed; frame.destination = b; } else { frame.next = Status.REMOVED; frame.source = removed; frame.destination = null; } break; default: throw new AssertionError(); } } else { frame.next = Status.LEAVE; frame.source = frame.node1; frame.destination = frame.node2; } break; default: throw new AssertionError("Was not expecting status " + frame.previous); } } return frame.next != null; } return false; }
public boolean hasNext() { if (frame != null) { if (frame.next == null) { switch (frame.previous) { case INIT: H id1 = context1.getModel().getHandle(frame.node1); H id2 = context2.getModel().getHandle(frame.node2); if (diff.comparator.compare(id1, id2) != 0) { frame.next = Status.ERROR; frame.source = frame.node1; frame.destination = frame.node2; } else { frame.next = Status.ENTER; frame.source = frame.node1; frame.destination = frame.node2; } break; case ERROR: break; case LEAVE: frame = frame.parent; if (frame != null) { frame.previous = Status.CONTINUE; return hasNext(); } else { return false; } case MOVED_IN: frame = new Frame(frame, frame.source, frame.destination); return hasNext(); case ENTER: frame.children1 = context1.getModel().getChildren(frame.node1); frame.it1 = diff.adapter1.iterator(frame.children1, false); frame.children2 = context2.getModel().getChildren(frame.node2); frame.it2 = diff.adapter2.iterator(frame.children2, false); frame.it = LCS.create( diff.adapter1, diff.adapter2, diff.comparator).perform(frame.children1, frame.children2); case ADDED: case REMOVED: case MOVED_OUT: case CONTINUE: if (frame.it.hasNext()) { switch (frame.it.next()) { case KEEP: N1 next1 = context1.findByHandle(frame.it1.next()); N2 next2 = context2.findByHandle(frame.it2.next()); frame = new Frame(frame, next1, next2); return hasNext(); case ADD: frame.it2.next(); H addedHandle = frame.it.getElement(); N2 added = context2.findByHandle(addedHandle); H addedId = context2.getModel().getHandle(added); N1 a = context1.findByHandle(addedId); if (a != null) { frame.next = Status.MOVED_IN; frame.source = a; frame.destination = added; } else { frame.next = Status.ADDED; frame.source = null; frame.destination = added; } break; case REMOVE: frame.it1.next(); H removedHandle = frame.it.getElement(); N1 removed = context1.findByHandle(removedHandle); H removedId = context1.getModel().getHandle(removed); N2 b = context2.findByHandle(removedId); if (b != null) { frame.next = Status.MOVED_OUT; frame.source = removed; frame.destination = b; } else { frame.next = Status.REMOVED; frame.source = removed; frame.destination = null; } break; default: throw new AssertionError(); } } else { frame.next = Status.LEAVE; frame.source = frame.node1; frame.destination = frame.node2; } break; default: throw new AssertionError("Was not expecting status " + frame.previous); } } return frame.next != null; } return false; }
diff --git a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest7.java b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest7.java index 5387338..29c26d4 100644 --- a/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest7.java +++ b/HttpdConfigParser/src/org/akquinet/audit/bsi/httpd/Quest7.java @@ -1,78 +1,78 @@ package org.akquinet.audit.bsi.httpd; import java.util.LinkedList; import java.util.List; import org.akquinet.audit.FormattedConsole; import org.akquinet.audit.YesNoQuestion; import org.akquinet.httpd.ConfigFile; import org.akquinet.httpd.syntax.Directive; public class Quest7 implements YesNoQuestion { private static final String _id = "Quest7"; private ConfigFile _conf; private static final FormattedConsole _console = FormattedConsole.getDefault(); private static final FormattedConsole.OutputLevel _level = FormattedConsole.OutputLevel.Q1; public Quest7(ConfigFile conf) { _conf = conf; } @Override public boolean answer() { _console.println(_level, "All options should be explicitly deactivated and only necessary options should be activated."); _console.println(_level, "Scanning for \"Options None\" in global context"); List<Directive> dirList = _conf.getDirective("Options"); List<Directive> problems = new LinkedList<Directive>(); boolean isSetGlobal = false; //will be changed if at least one directive in global context is found for (Directive directive : dirList) { - if(!directive.getValue().matches("( |\t)*None( |\t)*")) + if(!directive.getValue().matches("[ \t]*[Nn]one[ \t]*")) { - if(!directive.getValue().matches("( |\t)*-(\\S)*( |\t)*")) //maybe an option is deactivated + if(!directive.getValue().matches("[ \t]*-(\\S)*[ \t]*")) //maybe an option is deactivated { problems.add(directive); } } - if(directive.getSurroundingContexts().get(0) == null) + else if(directive.getSurroundingContexts().get(0) == null) { isSetGlobal = true; } } _console.println(_level, isSetGlobal ? "Directive \"Options None\" is correctly stated in global context." : "You haven't stated the directive \"Options None\" in global context."); boolean allOk = problems.isEmpty(); if(!allOk) { _console.println(_level, "As expected you activated some options. I will give you the line of each in you configuration file." ); _console.println(_level, "Please check whether you really need all these options." ); for (Directive directive : problems) { _console.println(_level, "line " + directive.getLinenumber() + ": " + directive.getName() + " " + directive.getValue()); } allOk = _console.askYesNoQuestion(_level, "Do you really need all these options?"); } boolean ret = isSetGlobal && allOk; _console.printAnswer(_level, ret, ret ? "(De-)Activation of options is well done." : "Please state \"Options None\" in the global context and/or do not activate unneeded options."); return ret; } @Override public boolean isCritical() { return false; } @Override public String getID() { return _id; } }
false
true
public boolean answer() { _console.println(_level, "All options should be explicitly deactivated and only necessary options should be activated."); _console.println(_level, "Scanning for \"Options None\" in global context"); List<Directive> dirList = _conf.getDirective("Options"); List<Directive> problems = new LinkedList<Directive>(); boolean isSetGlobal = false; //will be changed if at least one directive in global context is found for (Directive directive : dirList) { if(!directive.getValue().matches("( |\t)*None( |\t)*")) { if(!directive.getValue().matches("( |\t)*-(\\S)*( |\t)*")) //maybe an option is deactivated { problems.add(directive); } } if(directive.getSurroundingContexts().get(0) == null) { isSetGlobal = true; } } _console.println(_level, isSetGlobal ? "Directive \"Options None\" is correctly stated in global context." : "You haven't stated the directive \"Options None\" in global context."); boolean allOk = problems.isEmpty(); if(!allOk) { _console.println(_level, "As expected you activated some options. I will give you the line of each in you configuration file." ); _console.println(_level, "Please check whether you really need all these options." ); for (Directive directive : problems) { _console.println(_level, "line " + directive.getLinenumber() + ": " + directive.getName() + " " + directive.getValue()); } allOk = _console.askYesNoQuestion(_level, "Do you really need all these options?"); } boolean ret = isSetGlobal && allOk; _console.printAnswer(_level, ret, ret ? "(De-)Activation of options is well done." : "Please state \"Options None\" in the global context and/or do not activate unneeded options."); return ret; }
public boolean answer() { _console.println(_level, "All options should be explicitly deactivated and only necessary options should be activated."); _console.println(_level, "Scanning for \"Options None\" in global context"); List<Directive> dirList = _conf.getDirective("Options"); List<Directive> problems = new LinkedList<Directive>(); boolean isSetGlobal = false; //will be changed if at least one directive in global context is found for (Directive directive : dirList) { if(!directive.getValue().matches("[ \t]*[Nn]one[ \t]*")) { if(!directive.getValue().matches("[ \t]*-(\\S)*[ \t]*")) //maybe an option is deactivated { problems.add(directive); } } else if(directive.getSurroundingContexts().get(0) == null) { isSetGlobal = true; } } _console.println(_level, isSetGlobal ? "Directive \"Options None\" is correctly stated in global context." : "You haven't stated the directive \"Options None\" in global context."); boolean allOk = problems.isEmpty(); if(!allOk) { _console.println(_level, "As expected you activated some options. I will give you the line of each in you configuration file." ); _console.println(_level, "Please check whether you really need all these options." ); for (Directive directive : problems) { _console.println(_level, "line " + directive.getLinenumber() + ": " + directive.getName() + " " + directive.getValue()); } allOk = _console.askYesNoQuestion(_level, "Do you really need all these options?"); } boolean ret = isSetGlobal && allOk; _console.printAnswer(_level, ret, ret ? "(De-)Activation of options is well done." : "Please state \"Options None\" in the global context and/or do not activate unneeded options."); return ret; }
diff --git a/src/main/java/lcmc/gui/resources/BlockDevInfo.java b/src/main/java/lcmc/gui/resources/BlockDevInfo.java index ef772d55..9cdfe488 100644 --- a/src/main/java/lcmc/gui/resources/BlockDevInfo.java +++ b/src/main/java/lcmc/gui/resources/BlockDevInfo.java @@ -1,2659 +1,2674 @@ /* * This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH * written by Rasto Levrinc. * * Copyright (C) 2009-2010, LINBIT HA-Solutions GmbH. * Copyright (C) 2009-2010, Rasto Levrinc * * DRBD Management Console 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, or (at your option) * any later version. * * DRBD Management Console 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 drbd; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */ package lcmc.gui.resources; import lcmc.Exceptions; import lcmc.gui.Browser; import lcmc.gui.HostBrowser; import lcmc.gui.ClusterBrowser; import lcmc.gui.DrbdGraph; import lcmc.gui.dialog.lvm.PVCreate; import lcmc.gui.dialog.lvm.PVRemove; import lcmc.gui.dialog.lvm.VGCreate; import lcmc.gui.dialog.lvm.VGRemove; import lcmc.gui.dialog.lvm.LVCreate; import lcmc.gui.dialog.lvm.LVResize; import lcmc.gui.dialog.lvm.LVSnapshot; import lcmc.gui.dialog.drbd.DrbdLog; import lcmc.data.ConfigData; import lcmc.utilities.MyMenu; import lcmc.utilities.MyMenuItem; import lcmc.utilities.UpdatableItem; import lcmc.utilities.Tools; import lcmc.utilities.DRBD; import lcmc.utilities.LVM; import lcmc.utilities.ButtonCallback; import lcmc.gui.widget.Widget; import lcmc.data.Host; import lcmc.data.Subtext; import lcmc.data.Cluster; import lcmc.data.DRBDtestData; import lcmc.data.resources.BlockDevice; import lcmc.data.AccessMode; import lcmc.data.DrbdXML; import java.awt.Dimension; import java.awt.Component; import java.awt.Font; import java.awt.Color; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.BorderLayout; import java.util.LinkedHashMap; import java.util.List; import java.util.ArrayList; import java.util.Enumeration; import java.util.Map; import java.util.Set; import java.util.HashMap; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.concurrent.CountDownLatch; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.JComponent; import javax.swing.SwingUtilities; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.BoxLayout; import javax.swing.JScrollPane; /** * This class holds info data for a block device. */ public final class BlockDevInfo extends EditableInfo { /** DRBD resource in which this block device is member. */ private DrbdVolumeInfo drbdVolumeInfo; /** Map from paremeters to the fact if the last entered value was * correct. */ private final Map<String, Boolean> paramCorrectValueMap = new HashMap<String, Boolean>(); /** Cache for the info panel. */ private JComponent infoPanel = null; /** Keyword that denotes flexible meta-disk. */ private static final String DRBD_MD_TYPE_FLEXIBLE = "Flexible"; /** Internal parameter name of drbd meta-disk. */ private static final String DRBD_MD_PARAM = "DrbdMetaDisk"; /** Internal parameter name of drbd meta-disk index. */ private static final String DRBD_MD_INDEX_PARAM = "DrbdMetaDiskIndex"; /** Large harddisk icon. */ public static final ImageIcon HARDDISK_ICON_LARGE = Tools.createImageIcon( Tools.getDefault("BlockDevInfo.HarddiskIconLarge")); /** Large harddisk with drbd icon. */ public static final ImageIcon HARDDISK_DRBD_ICON_LARGE = Tools.createImageIcon( Tools.getDefault("BlockDevInfo.HarddiskDRBDIconLarge")); /** Large no harddisk icon. */ public static final ImageIcon NO_HARDDISK_ICON_LARGE = Tools.createImageIcon( Tools.getDefault("BlockDevInfo.NoHarddiskIconLarge")); /** Harddisk icon. */ public static final ImageIcon HARDDISK_ICON = Tools.createImageIcon( Tools.getDefault("BlockDevInfo.HarddiskIcon")); /** Meta-disk subtext. */ private static final Subtext METADISK_SUBTEXT = new Subtext("meta-disk", Color.BLUE, Color.BLACK); /** Swap subtext. */ private static final Subtext SWAP_SUBTEXT = new Subtext("swap", Color.BLUE, Color.BLACK); /** Mounted subtext. */ private static final Subtext MOUNTED_SUBTEXT = new Subtext("mounted", Color.BLUE, Color.BLACK); /** Physical volume subtext. */ private static final Subtext PHYSICAL_VOLUME_SUBTEXT = new Subtext("PV", Color.BLUE, Color.GREEN); /** String length after the cut. */ private static final int MAX_RIGHT_CORNER_STRING_LENGTH = 28; /** String that is displayed as a tool tip for disabled menu item. */ static final String NO_DRBD_RESOURCE_STRING = "it is not a drbd resource"; /** Allow two primaries paramater. */ private static final String ALLOW_TWO_PRIMARIES = "allow-two-primaries"; /** Name of the create PV menu item. */ private static final String PV_CREATE_MENU_ITEM = "Create PV"; /** Description. */ private static final String PV_CREATE_MENU_DESCRIPTION = "Initialize a disk or partition for use by LVM."; /** Name of the remove PV menu item. */ private static final String PV_REMOVE_MENU_ITEM = "Remove PV"; /** Description. */ private static final String PV_REMOVE_MENU_DESCRIPTION = "Remove a physical volume."; /** Name of the create VG menu item. */ private static final String VG_CREATE_MENU_ITEM = "Create VG"; /** Description create VG. */ private static final String VG_CREATE_MENU_DESCRIPTION = "Create a volume group."; /** Name of the remove VG menu item. */ private static final String VG_REMOVE_MENU_ITEM = "Remove VG"; /** Description. */ private static final String VG_REMOVE_MENU_DESCRIPTION = "Remove a volume group."; /** Name of the create menu item. */ private static final String LV_CREATE_MENU_ITEM = "Create LV in VG "; /** Description create LV. */ private static final String LV_CREATE_MENU_DESCRIPTION = "Create a logical volume."; /** Name of the LV remove menu item. */ private static final String LV_REMOVE_MENU_ITEM = "Remove LV"; /** Description for LV remove. */ private static final String LV_REMOVE_MENU_DESCRIPTION = "Remove the logical volume"; /** Name of the resize menu item. */ private static final String LV_RESIZE_MENU_ITEM = "Resize LV"; /** Description LVM resize. */ private static final String LV_RESIZE_MENU_DESCRIPTION = "Resize the logical volume"; /** Name of the snapshot menu item. */ private static final String LV_SNAPSHOT_MENU_ITEM = "Create LV Snapshot "; /** Description LV snapshot. */ private static final String LV_SNAPSHOT_MENU_DESCRIPTION = "Create a snapshot of the logical volume."; /** "Proxy up" text for graph. */ public static final String PROXY_UP = "Proxy Up"; /** "Proxy down" text for graph. */ private static final String PROXY_DOWN = "Proxy Down"; /** * Prepares a new <code>BlockDevInfo</code> object. * * @param name * name that will be shown in the tree * @param blockDevice * bock device */ public BlockDevInfo(final String name, final BlockDevice blockDevice, final Browser browser) { super(name, browser); setResource(blockDevice); } /** * Returns object of the other block device that is connected via drbd * to this block device. */ public BlockDevInfo getOtherBlockDevInfo() { final DrbdVolumeInfo dvi = drbdVolumeInfo; if (dvi == null) { return null; } return dvi.getOtherBlockDevInfo(this); } /** Returns browser object of this info. */ @Override public HostBrowser getBrowser() { return (HostBrowser) super.getBrowser(); } /** Sets info panel of this block devices. TODO: explain why. */ void setInfoPanel(final JComponent infoPanel) { this.infoPanel = infoPanel; } /** * Remove this block device. * * TODO: check this */ @Override public void removeMyself(final boolean testOnly) { getBlockDevice().setValue(DRBD_MD_PARAM, null); getBlockDevice().setValue(DRBD_MD_INDEX_PARAM, null); super.removeMyself(testOnly); if (!testOnly) { removeNode(); } infoPanel = null; } /** Returns host on which is this block device. */ public Host getHost() { return getBrowser().getHost(); } /** Returns block device icon for the menu. */ @Override public ImageIcon getMenuIcon(final boolean testOnly) { return BlockDevInfo.HARDDISK_ICON; } /** Returns info of this block device as string. */ @Override String getInfo() { final StringBuilder ret = new StringBuilder(120); ret.append("Host : "); ret.append(getHost().getName()); ret.append("\nDevice : "); ret.append(getBlockDevice().getName()); ret.append("\nMeta disk : "); ret.append(getBlockDevice().isDrbdMetaDisk()); ret.append("\nSize : "); ret.append(getBlockDevice().getBlockSize()); ret.append(" blocks"); if (getBlockDevice().getMountedOn() == null) { ret.append("\nnot mounted"); } else { ret.append("\nMounted on : "); ret.append(getBlockDevice().getMountedOn()); ret.append("\nType : "); ret.append(getBlockDevice().getFsType()); if (getUsed() >= 0) { ret.append("\nUsed: : "); ret.append(getUsed()); ret.append('%'); } } if (getBlockDevice().isDrbd()) { ret.append("\nConnection state: "); ret.append(getBlockDevice().getConnectionState()); ret.append("\nNode state : "); ret.append(getBlockDevice().getNodeState()); ret.append("\nDisk state : "); ret.append(getBlockDevice().getDiskState()); ret.append('\n'); } return ret.toString(); } /** Append hierarchy of block devices in the string buffer using HTML. */ private void appendBlockDeviceHierarchy(final BlockDevice bd, final StringBuilder tt, final int shift) { String tab = ""; for (int i = 0; i != shift; ++i) { tab += " "; } /* physical volumes */ String vg = null; String selectedPV = null; if (bd.isVolumeGroupOnPhysicalVolume()) { vg = bd.getVolumeGroupOnPhysicalVolume(); selectedPV = bd.getName(); } else if (isLVM()) { vg = bd.getVolumeGroup(); } if (vg != null) { for (final BlockDevice pv : getHost().getPhysicalVolumes(vg)) { if (pv.equals(selectedPV)) { tt.append("<b>"); tt.append(tab + pv); tt.append("</b>"); } else { tt.append(tab + pv); } tt.append('\n'); } } /* volume groups */ String selectedLV = null; if (vg != null) { if (bd.isVolumeGroupOnPhysicalVolume()) { tt.append("<b>"); tt.append(" " + tab + vg); tt.append("</b>\n"); } else if (isLVM()) { tt.append(" " + tab); tt.append(vg); tt.append('\n'); selectedLV = bd.getName(); } final Set<String> lvs = getHost().getLogicalVolumesFromVolumeGroup(vg); if (lvs != null) { for (final String lv : lvs) { tt.append(" " + tab); final String lvName = "/dev/" + vg + "/" + lv; if (lvName.equals(selectedLV)) { if (bd.isDrbd()) { tt.append(lv); tt.append("\n"); final BlockDevice drbdBD = bd.getDrbdBlockDevice(); if (drbdBD != null) { appendBlockDeviceHierarchy(drbdBD, tt, shift + 3); } } else { tt.append("<b>"); tt.append(lv); tt.append("</b>\n"); } } else { tt.append(lv); tt.append('\n'); } } } } else { final BlockDevice drbdBD = bd.getDrbdBlockDevice(); if (drbdBD != null) { tt.append(tab + bd.getName()); tt.append('\n'); appendBlockDeviceHierarchy(drbdBD, tt, shift + 1); } else { tt.append("<b>"); tt.append(tab + bd.getName()); tt.append("</b>\n"); } } } /** Returns tool tip for this block device. */ @Override public String getToolTipForGraph(final boolean testOnly) { final StringBuilder tt = new StringBuilder(60); final BlockDevice bd = getBlockDevice(); tt.append("<pre>"); appendBlockDeviceHierarchy(bd, tt, 0); tt.append("</pre>"); if (bd.isDrbdMetaDisk()) { tt.append(" (Meta Disk)\n"); for (final BlockDevice mb : getBlockDevice().getMetaDiskOfBlockDevices()) { tt.append("&nbsp;&nbsp;of "); tt.append(mb.getName()); tt.append('\n'); } } if (bd.isDrbd()) { if (getHost().isDrbdStatus()) { String cs = bd.getConnectionState(); String st = bd.getNodeState(); String ds = bd.getDiskState(); if (cs == null) { cs = "not available"; } if (st == null) { st = "not available"; } if (ds == null) { ds = "not available"; } tt.append("\n<table><tr><td><b>cs:</b></td><td>"); tt.append(cs); tt.append("</td></tr><tr><td><b>ro:</b></td><td>"); tt.append(st); tt.append("</td></tr><tr><td><b>ds:</b></td><td>"); tt.append(ds); tt.append("</td></tr></table>"); } else { tt.append('\n'); tt.append(Tools.getString("HostBrowser.Hb.NoInfoAvailable")); } } return tt.toString(); } /** Creates config for one node. */ String drbdBDConfig(final String resource, final String drbdDevice, final boolean volumesAvailable) throws Exceptions.DrbdConfigException { if (drbdDevice == null) { throw new Exceptions.DrbdConfigException( "Drbd device not defined for host " + getHost().getName() + " (" + resource + ")"); } if (getBlockDevice().getName() == null) { throw new Exceptions.DrbdConfigException( "Block device not defined for host " + getHost().getName() + " (" + resource + ")"); } final StringBuilder config = new StringBuilder(120); String tabs; if (volumesAvailable) { tabs = "\t\t\t"; } else { tabs = "\t\t"; } config.append(tabs + "device\t\t"); config.append(drbdDevice); config.append(";\n" + tabs + "disk\t\t"); config.append(getBlockDevice().getName()); config.append(";\n" + tabs); config.append(getBlockDevice().getMetaDiskString( getComboBoxValue(DRBD_MD_PARAM), getComboBoxValue(DRBD_MD_INDEX_PARAM))); config.append(';'); return config.toString(); } /** Sets whether this block device is drbd. */ void setDrbd(final boolean drbd) { getBlockDevice().setDrbd(drbd); } /** Returns section of this paramter. */ @Override protected String getSection(final String param) { return getBlockDevice().getSection(param); } /** Returns possible choices of this paramter. */ @Override protected Object[] getPossibleChoices(final String param) { return getBlockDevice().getPossibleChoices(param); } /** Returns default value of this paramter. */ protected Object getDefaultValue(final String param) { return "<select>"; } /** Returns combobox for this parameter. */ @Override protected Widget createWidget(final String param, final String prefix, final int width) { Widget paramWi; if (DRBD_MD_INDEX_PARAM.equals(param)) { final Widget gwi = super.createWidget(param, prefix, width); paramWi = gwi; //SwingUtilities.invokeLater(new Runnable() { // @Override // public void run() { // gwi.setAlwaysEditable(true); // } //}); } else { final Widget gwi = super.createWidget(param, prefix, width); paramWi = gwi; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { gwi.setEditable(false); } }); } return paramWi; } /** Returns true if a paramter is correct. */ @Override protected boolean checkParam(final String param, String value) { boolean ret = true; if (value == null) { value = ""; } if ("".equals(value) && isRequired(param)) { ret = false; } else if (DRBD_MD_PARAM.equals(param)) { if (infoPanel != null) { if (!getHost().isServerStatusLatch()) { final boolean internal = "internal".equals(value); final Widget ind = getWidget(DRBD_MD_INDEX_PARAM, null); final Widget indW = getWidget(DRBD_MD_INDEX_PARAM, "wizard"); if (internal) { ind.setValue(DRBD_MD_TYPE_FLEXIBLE); if (indW != null) { indW.setValue(DRBD_MD_TYPE_FLEXIBLE); } } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { ind.setEnabled(!internal); } }); if (indW != null) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { indW.setEnabled(!internal); } }); } } } } else if (DRBD_MD_INDEX_PARAM.equals(param)) { if (getBrowser().getUsedPorts().contains(value) && !value.equals(getBlockDevice().getValue(param))) { ret = false; } final Pattern p = Pattern.compile(".*\\D.*"); final Matcher m = p.matcher(value); if (m.matches() && !DRBD_MD_TYPE_FLEXIBLE.equals(value)) { ret = false; } } paramCorrectValueMap.remove(param); paramCorrectValueMap.put(param, ret); return ret; } /** Returns whether this parameter is required. */ @Override protected boolean isRequired(final String param) { return true; } /** Returns whether this parameter is advanced. */ @Override protected boolean isAdvanced(final String param) { return false; } /** Returns access type of this parameter. */ @Override protected ConfigData.AccessType getAccessType(final String param) { return ConfigData.AccessType.ADMIN; } /** Whether the parameter should be enabled. */ @Override protected String isEnabled(final String param) { return null; } /** Whether the parameter should be enabled only in advanced mode. */ @Override protected boolean isEnabledOnlyInAdvancedMode(final String param) { return false; } /** Returns whether this type is integer. */ @Override protected boolean isInteger(final String param) { return false; } /** Returns whether this type is a label. */ @Override protected boolean isLabel(final String param) { return false; } /** Returns whether this parameter is of a time type. */ @Override protected boolean isTimeType(final String param) { /* not required */ return false; } /** Returns whether this parameter is a checkbox. */ @Override protected boolean isCheckBox(final String param) { return false; } /** Returns type of this parameter. */ @Override protected String getParamType(final String param) { return null; } /** Returns the regexp of the parameter. */ @Override protected String getParamRegexp(final String param) { return null; } /** Returns possible choices for the parameter. */ @Override protected Object[] getParamPossibleChoices(final String param) { if (DRBD_MD_PARAM.equals(param)) { /* meta disk */ final StringInfo internalMetaDisk = new StringInfo(Tools.getString( "HostBrowser.MetaDisk.Internal"), "internal", getBrowser()); final String defaultMetaDiskString = internalMetaDisk.toString(); getBrowser().lockBlockDevInfosRead(); @SuppressWarnings("unchecked") final Info[] blockDevices = getAvailableBlockDevicesForMetaDisk( internalMetaDisk, getName(), getBrowser().getBlockDevicesNode().children()); getBrowser().unlockBlockDevInfosRead(); getBlockDevice().setDefaultValue(DRBD_MD_PARAM, defaultMetaDiskString); return blockDevices; } else if (DRBD_MD_INDEX_PARAM.equals(param)) { String defaultMetaDiskIndex = getBlockDevice().getValue( DRBD_MD_INDEX_PARAM); if ("internal".equals(defaultMetaDiskIndex)) { defaultMetaDiskIndex = Tools.getString("HostBrowser.MetaDisk.Internal"); } String[] indeces = new String[11]; int index = 0; if (defaultMetaDiskIndex == null) { defaultMetaDiskIndex = DRBD_MD_TYPE_FLEXIBLE; } else if (!DRBD_MD_TYPE_FLEXIBLE.equals(defaultMetaDiskIndex)) { index = Integer.valueOf(defaultMetaDiskIndex) - 5; if (index < 0) { index = 0; } } indeces[0] = DRBD_MD_TYPE_FLEXIBLE; for (int i = 1; i < 11; i++) { indeces[i] = Integer.toString(index); index++; } getBlockDevice().setDefaultValue(DRBD_MD_INDEX_PARAM, DRBD_MD_TYPE_FLEXIBLE); return indeces; } return null; } /** Returns default for this parameter. */ @Override protected String getParamDefault(final String param) { return getBlockDevice().getDefaultValue(param); } /** Returns preferred value of this parameter. */ @Override protected String getParamPreferred(final String param) { return getBlockDevice().getPreferredValue(param); } /** Return whether the value is correct from the cache. */ @Override protected boolean checkParamCache(final String param) { final Boolean cv = paramCorrectValueMap.get(param); if (cv == null) { return false; } return cv.booleanValue(); } /** Returns block devices that are available for drbd meta-disk. */ protected Info[] getAvailableBlockDevicesForMetaDisk( final Info defaultValue, final String serviceName, final Enumeration<DefaultMutableTreeNode> e) { final List<Info> list = new ArrayList<Info>(); final String savedMetaDisk = getBlockDevice().getValue(DRBD_MD_PARAM); if (defaultValue != null) { list.add(defaultValue); } while (e.hasMoreElements()) { final BlockDevInfo bdi = (BlockDevInfo) e.nextElement().getUserObject(); final BlockDevice bd = bdi.getBlockDevice(); if (bd.toString().equals(savedMetaDisk) || (!bd.isDrbd() && !bd.isUsedByCRM() && !bd.isMounted())) { list.add(bdi); } } return list.toArray(new Info[list.size()]); } /** DRBD attach. */ void attach(final boolean testOnly) { DRBD.attach(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** DRBD detach. */ void detach(final boolean testOnly) { DRBD.detach(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** DRBD connect. */ void connect(final boolean testOnly) { DRBD.connect(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), null, testOnly); } /** DRBD disconnect. */ void disconnect(final boolean testOnly) { DRBD.disconnect(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), null, testOnly); } /** DRBD pause sync. */ void pauseSync(final boolean testOnly) { DRBD.pauseSync(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** DRBD resume sync. */ void resumeSync(final boolean testOnly) { DRBD.resumeSync(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** DRBD up command. */ void drbdUp(final boolean testOnly) { DRBD.up(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** Sets this drbd block device to the primary state. */ void setPrimary(final boolean testOnly) { DRBD.setPrimary(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** Sets this drbd block device to the secondary state. */ public void setSecondary(final boolean testOnly) { DRBD.setSecondary(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** Initializes drbd block device. */ void initDrbd(final boolean testOnly) { DRBD.initDrbd(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** Make filesystem. */ public void makeFilesystem(final String filesystem, final boolean testOnly) { DRBD.makeFilesystem(getHost(), getDrbdVolumeInfo().getDevice(), filesystem, testOnly); } /** Initialize a physical volume. */ public boolean pvCreate(final boolean testOnly) { String device; if (getBlockDevice().isDrbd()) { device = drbdVolumeInfo.getDevice(); } else { device = getBlockDevice().getName(); } final boolean ret = LVM.pvCreate(getHost(), device, testOnly); if (ret) { getBlockDevice().setVolumeGroupOnPhysicalVolume(""); } return ret; } /** Remove a physical volume. */ public boolean pvRemove(final boolean testOnly) { String device; if (getBlockDevice().isDrbd()) { device = drbdVolumeInfo.getDevice(); } else { device = getBlockDevice().getName(); } final boolean ret = LVM.pvRemove(getHost(), device, testOnly); if (ret) { if (getBlockDevice().isDrbd()) { getBlockDevice().getDrbdBlockDevice() .setVolumeGroupOnPhysicalVolume(null); } else { getBlockDevice().setVolumeGroupOnPhysicalVolume(null); } } return ret; } /** Remove a logical volume. */ public boolean lvRemove(final boolean testOnly) { final String device = getBlockDevice().getName(); return LVM.lvRemove(getHost(), device, testOnly); } /** Make snapshot. */ public boolean lvSnapshot(final String snapshotName, final String size, final boolean testOnly) { final String device = getBlockDevice().getName(); return LVM.lvSnapshot(getHost(), snapshotName, device, size, testOnly); } /** Skip initial full sync. */ public void skipInitialFullSync(final boolean testOnly) { DRBD.skipInitialFullSync(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** Force primary. */ public void forcePrimary(final boolean testOnly) { DRBD.forcePrimary(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** Invalidate the block device. */ void invalidateBD(final boolean testOnly) { DRBD.invalidate(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** Discard the data. */ void discardData(final boolean testOnly) { DRBD.discardData(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), null, testOnly); } /** Start on-line verification. */ void verify(final boolean testOnly) { DRBD.verify(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** Resize DRBD. */ public boolean resizeDrbd(final boolean testOnly) { return DRBD.resize(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } /** Returns the graphical view. */ @Override public JPanel getGraphicalView() { if (getBlockDevice().isDrbd()) { getBrowser().getDrbdGraph().getDrbdInfo().setSelectedNode(this); } return getBrowser().getDrbdGraph().getDrbdInfo().getGraphicalView(); } /** Set the terminal panel. */ @Override protected void setTerminalPanel() { if (getHost() != null) { Tools.getGUIData().setTerminalPanel(getHost().getTerminalPanel()); } } /** Returns the info panel. */ @Override public JComponent getInfoPanel() { return getInfoPanelBD(); } /** Returns all parameters. */ @Override public String[] getParametersFromXML() { final String[] params = { DRBD_MD_PARAM, DRBD_MD_INDEX_PARAM, }; return params; } /** Apply all fields. */ public void apply(final boolean testOnly) { if (!testOnly) { final String[] params = getParametersFromXML(); Tools.invokeAndWait(new Runnable() { @Override public void run() { getApplyButton().setEnabled(false); getRevertButton().setEnabled(false); } }); getInfoPanel(); waitForInfoPanel(); if (getBlockDevice().getMetaDisk() != null) { getBlockDevice().getMetaDisk().removeMetadiskOfBlockDevice( getBlockDevice()); } getBlockDevice().setNew(false); storeComboBoxValues(params); final Object o = getWidget(DRBD_MD_PARAM, null).getValue(); if (Tools.isStringInfoClass(o)) { getBlockDevice().setMetaDisk(null); /* internal */ } else { final BlockDevice metaDisk = ((BlockDevInfo) o).getBlockDevice(); getBlockDevice().setMetaDisk(metaDisk); } getBrowser().getDrbdGraph().getDrbdInfo().setAllApplyButtons(); } } /** Returns block device panel. */ JComponent getInfoPanelBD() { if (infoPanel != null) { return infoPanel; } final BlockDevInfo thisClass = this; final ButtonCallback buttonCallback = new ButtonCallback() { private volatile boolean mouseStillOver = false; /** * Whether the whole thing should be enabled. */ @Override public boolean isEnabled() { return true; } @Override public void mouseOut() { if (!isEnabled()) { return; } mouseStillOver = false; final DrbdGraph drbdGraph = getBrowser().getDrbdGraph(); drbdGraph.stopTestAnimation(getApplyButton()); getApplyButton().setToolTipText(null); } @Override public void mouseOver() { if (!isEnabled()) { return; } mouseStillOver = true; getApplyButton().setToolTipText(Tools.getString( "ClusterBrowser.StartingDRBDtest")); getApplyButton().setToolTipBackground(Tools.getDefaultColor( "ClusterBrowser.Test.Tooltip.Background")); Tools.sleep(250); if (!mouseStillOver) { return; } mouseStillOver = false; final CountDownLatch startTestLatch = new CountDownLatch(1); final DrbdGraph drbdGraph = getBrowser().getDrbdGraph(); drbdGraph.startTestAnimation(getApplyButton(), startTestLatch); getBrowser().drbdtestLockAcquire(); thisClass.setDRBDtestData(null); apply(true); final Map<Host, String> testOutput = new LinkedHashMap<Host, String>(); try { getBrowser().getDrbdGraph().getDrbdInfo().createDrbdConfig( true); for (final Host h : getHost().getCluster().getHostsArray()) { DRBD.adjust(h, DRBD.ALL, null, true); testOutput.put(h, DRBD.getDRBDtest()); } } catch (Exceptions.DrbdConfigException dce) { Tools.appError("config failed"); } final DRBDtestData dtd = new DRBDtestData(testOutput); getApplyButton().setToolTipText(dtd.getToolTip()); thisClass.setDRBDtestData(dtd); getBrowser().drbdtestLockRelease(); startTestLatch.countDown(); } }; initApplyButton(buttonCallback); final JPanel mainPanel = new JPanel(); mainPanel.setBackground(HostBrowser.PANEL_BACKGROUND); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); final JPanel buttonPanel = new JPanel(new BorderLayout()); buttonPanel.setBackground(HostBrowser.BUTTON_PANEL_BACKGROUND); buttonPanel.setMinimumSize(new Dimension(0, 50)); buttonPanel.setPreferredSize(new Dimension(0, 50)); buttonPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 50)); final JPanel optionsPanel = new JPanel(); optionsPanel.setBackground(HostBrowser.PANEL_BACKGROUND); optionsPanel.setLayout(new BoxLayout(optionsPanel, BoxLayout.Y_AXIS)); optionsPanel.setAlignmentX(Component.LEFT_ALIGNMENT); /* Actions */ buttonPanel.add(getActionsButton(), BorderLayout.EAST); if (getBlockDevice().isDrbd()) { final String[] params = getParametersFromXML(); addParams(optionsPanel, params, Tools.getDefaultSize("HostBrowser.DrbdDevLabelWidth"), Tools.getDefaultSize("HostBrowser.DrbdDevFieldWidth"), null); /* apply button */ getApplyButton().addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final Thread thread = new Thread(new Runnable() { @Override public void run() { Tools.invokeAndWait(new Runnable() { @Override public void run() { getApplyButton().setEnabled(false); getRevertButton().setEnabled(false); } }); getBrowser().getClusterBrowser().drbdStatusLock(); try { getBrowser().getDrbdGraph().getDrbdInfo() .createDrbdConfig(false); for (final Host h : getHost().getCluster().getHostsArray()) { DRBD.adjust(h, DRBD.ALL, null, false); } } catch (Exceptions.DrbdConfigException e) { getBrowser() .getClusterBrowser() .drbdStatusUnlock(); Tools.appError("config failed"); return; } apply(false); getBrowser().getClusterBrowser().drbdStatusUnlock(); } }); thread.start(); } }); getRevertButton().addActionListener( new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { final Thread thread = new Thread(new Runnable() { @Override public void run() { revert(); } }); thread.start(); } } ); addApplyButton(buttonPanel); addRevertButton(buttonPanel); } /* info */ final Font f = new Font("Monospaced", Font.PLAIN, Tools.getConfigData().scaled(12)); final JPanel riaPanel = new JPanel(); riaPanel.setBackground(HostBrowser.PANEL_BACKGROUND); riaPanel.setAlignmentX(Component.LEFT_ALIGNMENT); riaPanel.add(super.getInfoPanel()); mainPanel.add(riaPanel); mainPanel.add(optionsPanel); final JPanel newPanel = new JPanel(); newPanel.setBackground(HostBrowser.PANEL_BACKGROUND); newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.Y_AXIS)); newPanel.add(buttonPanel); newPanel.add(new JScrollPane(mainPanel)); infoPanel = newPanel; infoPanelDone(); setApplyButtons(null, getParametersFromXML()); return infoPanel; } /** TODO: dead code? */ @Override boolean selectAutomaticallyInTreeMenu() { return infoPanel == null; } /** Sets drbd resource for this block device. */ void setDrbdVolumeInfo(final DrbdVolumeInfo drbdVolumeInfo) { this.drbdVolumeInfo = drbdVolumeInfo; } /** Returns drbd resource info in which this block device is member. */ public DrbdVolumeInfo getDrbdVolumeInfo() { return drbdVolumeInfo; } /** Returns block device resource object. */ public BlockDevice getBlockDevice() { return (BlockDevice) getResource(); } /** Removes this block device from drbd data structures. */ public void removeFromDrbd() { setDrbd(false); getBlockDevice().setDrbdBlockDevice(null); setDrbdVolumeInfo(null); } /** Returns short description of the parameter. */ @Override protected String getParamShortDesc(final String param) { return Tools.getString(param); } /** Returns long description of the parameter. */ @Override protected String getParamLongDesc(final String param) { return Tools.getString(param + ".Long"); } /** Returns 'add drbd resource' menu item. */ private MyMenuItem addDrbdResourceMenuItem(final BlockDevInfo oBdi, final boolean testOnly) { final BlockDevInfo thisClass = this; return new MyMenuItem(oBdi.toString(), null, null, new AccessMode(ConfigData.AccessType.ADMIN, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public void action() { final DrbdInfo drbdInfo = getBrowser().getDrbdGraph().getDrbdInfo(); cleanup(); setInfoPanel(null); oBdi.cleanup(); oBdi.setInfoPanel(null); drbdInfo.addDrbdVolume(thisClass, oBdi, true, testOnly); } }; } /** Returns 'PV create' menu item. */ private MyMenuItem getPVCreateItem() { final BlockDevInfo thisBDI = this; return new MyMenuItem(PV_CREATE_MENU_ITEM, null, PV_CREATE_MENU_DESCRIPTION, new AccessMode(ConfigData.AccessType.OP, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return !isLVM() && !getBlockDevice().isPhysicalVolume() && !getBlockDevice().isDrbdPhysicalVolume(); } @Override public String enablePredicate() { if (getBlockDevice().isDrbd() && !getBlockDevice().isPrimary()) { return "must be primary"; } return null; } @Override public void action() { final PVCreate pvCreate = new PVCreate(thisBDI); while (true) { pvCreate.showDialog(); if (pvCreate.isPressedCancelButton()) { pvCreate.cancelDialog(); return; } else if (pvCreate.isPressedFinishButton()) { break; } } } }; } /** Returns 'PV remove' menu item. */ private MyMenuItem getPVRemoveItem() { final BlockDevInfo thisBDI = this; return new MyMenuItem(PV_REMOVE_MENU_ITEM, null, PV_REMOVE_MENU_DESCRIPTION, new AccessMode(ConfigData.AccessType.OP, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { BlockDevice bd; if (getBlockDevice().isDrbd()) { if (!getBlockDevice().isPrimary()) { return false; } bd = getBlockDevice().getDrbdBlockDevice(); if (bd == null) { return false; } } else { bd = getBlockDevice(); } return bd.isPhysicalVolume() && !bd.isVolumeGroupOnPhysicalVolume(); } @Override public String enablePredicate() { if (getBlockDevice().isDrbd() && !getBlockDevice().isDrbdPhysicalVolume()) { return "DRBD is on it"; } return null; } @Override public void action() { final PVRemove pvRemove = new PVRemove(thisBDI); while (true) { pvRemove.showDialog(); if (pvRemove.isPressedCancelButton()) { pvRemove.cancelDialog(); return; } else if (pvRemove.isPressedFinishButton()) { break; } } } }; } /** Returns 'lv create' menu item. */ private MyMenuItem getVGCreateItem() { final BlockDevInfo thisBDI = this; return new MyMenuItem( VG_CREATE_MENU_ITEM, null, VG_CREATE_MENU_DESCRIPTION, new AccessMode(ConfigData.AccessType.OP, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; public boolean visiblePredicate() { BlockDevice bd; if (getBlockDevice().isDrbd()) { if (!getBlockDevice().isPrimary()) { return false; } bd = getBlockDevice().getDrbdBlockDevice(); if (bd == null) { return false; } } else { bd = getBlockDevice(); } return bd.isPhysicalVolume() && !bd.isVolumeGroupOnPhysicalVolume(); } public String enablePredicate() { return null; } @Override public void action() { final VGCreate vgCreate = new VGCreate(getHost(), thisBDI); while (true) { vgCreate.showDialog(); if (vgCreate.isPressedCancelButton()) { vgCreate.cancelDialog(); return; } else if (vgCreate.isPressedFinishButton()) { break; } } } }; } /** Returns 'VG remove' menu item. */ private MyMenuItem getVGRemoveItem() { final BlockDevInfo thisBDI = this; return new MyMenuItem(VG_REMOVE_MENU_ITEM, null, VG_REMOVE_MENU_DESCRIPTION, new AccessMode(ConfigData.AccessType.OP, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { BlockDevice bd; if (getBlockDevice().isDrbd()) { if (!getBlockDevice().isPrimary()) { return false; } bd = getBlockDevice().getDrbdBlockDevice(); if (bd == null) { return false; } } else { bd = getBlockDevice(); } return bd.isVolumeGroupOnPhysicalVolume(); } @Override public String enablePredicate() { String vg; final BlockDevice bd = getBlockDevice(); final BlockDevice drbdBD = bd.getDrbdBlockDevice(); if (drbdBD == null) { vg = bd.getVolumeGroupOnPhysicalVolume(); } else { vg = drbdBD.getVolumeGroupOnPhysicalVolume(); } if (getHost().getLogicalVolumesFromVolumeGroup(vg) != null) { return "has LV on it"; } return null; } @Override public void action() { final VGRemove vgRemove = new VGRemove(thisBDI); while (true) { vgRemove.showDialog(); if (vgRemove.isPressedCancelButton()) { vgRemove.cancelDialog(); return; } else if (vgRemove.isPressedFinishButton()) { break; } } } }; } /** Returns 'lv create' menu item. */ private MyMenuItem getLVCreateItem() { String name = LV_CREATE_MENU_ITEM; final String vgName = getBlockDevice().getVolumeGroup(); if (vgName != null) { name += vgName; } final BlockDevInfo thisClass = this; final MyMenuItem mi = new MyMenuItem( name, null, LV_CREATE_MENU_DESCRIPTION, new AccessMode(ConfigData.AccessType.OP, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; private String getVolumeGroup() { BlockDevice bd; if (getBlockDevice().isDrbd()) { bd = getBlockDevice().getDrbdBlockDevice(); if (bd == null) { return null; } } else { bd = getBlockDevice(); } final String vg = bd.getVolumeGroup(); if (vg == null) { /* vg on pv */ return bd.getVolumeGroupOnPhysicalVolume(); } else { /* lv on vg */ return vg; } } @Override public boolean visiblePredicate() { final String vg = getVolumeGroup(); return vg != null && !"".equals(vg) && getHost().getVolumeGroupNames().contains(vg); } @Override public String enablePredicate() { return null; } @Override public void action() { final LVCreate lvCreate = new LVCreate( getHost(), getVolumeGroup(), thisClass.getBlockDevice()); while (true) { lvCreate.showDialog(); if (lvCreate.isPressedCancelButton()) { lvCreate.cancelDialog(); return; } else if (lvCreate.isPressedFinishButton()) { break; } } } @Override public void update() { setText1(LV_CREATE_MENU_ITEM + getVolumeGroup()); super.update(); } }; mi.setToolTipText(LV_CREATE_MENU_DESCRIPTION); return mi; } /** Returns 'LV remove' menu item. */ private MyMenuItem getLVRemoveItem() { return new MyMenuItem(LV_REMOVE_MENU_ITEM, null, LV_REMOVE_MENU_DESCRIPTION, new AccessMode(ConfigData.AccessType.OP, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { return true; } @Override public boolean visiblePredicate() { return isLVM(); } @Override public String enablePredicate() { if (getBlockDevice().isDrbd()) { return "DRBD is on it"; } return null; } @Override public void action() { if (Tools.confirmDialog( "Remove Logical Volume", "Remove logical volume and DESTROY all the data on it?", "Remove", "Cancel")) { final boolean ret = lvRemove(false); final Host host = getHost(); getBrowser().getClusterBrowser().updateHWInfo(host); } } }; } /** Returns 'LV remove' menu item. */ private MyMenuItem getLVResizeItem() { final BlockDevInfo thisBDI = this; return new MyMenuItem(LV_RESIZE_MENU_ITEM, null, LV_RESIZE_MENU_DESCRIPTION, new AccessMode(ConfigData.AccessType.OP, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; public boolean visiblePredicate() { return isLVM(); } public String enablePredicate() { return null; } @Override public void action() { final LVResize lvmrd = new LVResize(thisBDI); while (true) { lvmrd.showDialog(); if (lvmrd.isPressedCancelButton()) { lvmrd.cancelDialog(); return; } else if (lvmrd.isPressedFinishButton()) { break; } } } }; } /** Returns 'LV snapshot' menu item. */ private MyMenuItem getLVSnapshotItem() { final BlockDevInfo thisBDI = this; return new MyMenuItem(LV_SNAPSHOT_MENU_ITEM, null, LV_SNAPSHOT_MENU_DESCRIPTION, new AccessMode(ConfigData.AccessType.OP, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return isLVM(); } @Override public String enablePredicate() { return null; } @Override public void action() { final LVSnapshot lvsd = new LVSnapshot(thisBDI); while (true) { lvsd.showDialog(); if (lvsd.isPressedCancelButton()) { lvsd.cancelDialog(); return; } else if (lvsd.isPressedFinishButton()) { break; } } } }; } /** Creates popup for the block device. */ @Override public List<UpdatableItem> createPopup() { final List<UpdatableItem> items = new ArrayList<UpdatableItem>(); final BlockDevInfo thisClass = this; final boolean testOnly = false; final MyMenu repMenuItem = new MyMenu( Tools.getString("HostBrowser.Drbd.AddDrbdResource"), new AccessMode(ConfigData.AccessType.ADMIN, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public String enablePredicate() { final DrbdXML dxml = getBrowser().getClusterBrowser().getDrbdXML(); if (drbdVolumeInfo != null) { return "it is already a drbd resouce"; } else if (!getHost().isConnected()) { return Host.NOT_CONNECTED_STRING; } else if (!getHost().isDrbdLoaded()) { return "drbd is not loaded"; } else if (getBlockDevice().isMounted()) { return "is mounted"; } else if (getBlockDevice().isVolumeGroupOnPhysicalVolume()) { return "is volume group"; } else if (!getBlockDevice().isAvailable()) { return "not available"; } else if (dxml.isDrbdDisabled()) { return "disabled because of config"; } return null; } @Override public void update() { super.update(); Cluster cluster = getHost().getCluster(); Host[] otherHosts = cluster.getHostsArray(); final List<MyMenu> hostMenus = new ArrayList<MyMenu>(); for (final Host oHost : otherHosts) { if (oHost == getHost()) { continue; } final MyMenu hostMenu = new MyMenu(oHost.getName(), new AccessMode( ConfigData.AccessType.ADMIN, false), new AccessMode( ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public String enablePredicate() { final DrbdXML dxml = getBrowser().getClusterBrowser().getDrbdXML(); if (!oHost.isConnected()) { return Host.NOT_CONNECTED_STRING; } else if (!oHost.isDrbdLoaded()) { return "drbd is not loaded"; } else { return null; } //return oHost.isConnected() // && oHost.isDrbdLoaded(); } @Override public void update() { super.update(); Tools.invokeAndWait(new Runnable() { @Override public void run() { removeAll(); } }); Set<BlockDevInfo> blockDevInfos = oHost.getBrowser().getBlockDevInfosInSwing(); List<BlockDevInfo> blockDevInfosS = new ArrayList<BlockDevInfo>(); for (final BlockDevInfo oBdi : blockDevInfos) { if (oBdi.getName().equals( getBlockDevice().getName())) { blockDevInfosS.add(0, oBdi); } else { blockDevInfosS.add(oBdi); } } for (final BlockDevInfo oBdi : blockDevInfosS) { if (oBdi.getDrbdVolumeInfo() == null && oBdi.getBlockDevice().isAvailable()) { add(addDrbdResourceMenuItem(oBdi, testOnly)); } if (oBdi.getName().equals( getBlockDevice().getName())) { addSeparator(); } } } }; hostMenu.update(); hostMenus.add(hostMenu); } Tools.invokeAndWait(new Runnable() { @Override public void run() { removeAll(); for (final MyMenu hostMenu : hostMenus) { add(hostMenu); } } }); } }; items.add(repMenuItem); /* PV Create */ items.add(getPVCreateItem()); /* PV Remove */ items.add(getPVRemoveItem()); /* VG Create */ items.add(getVGCreateItem()); /* VG Remove */ items.add(getVGRemoveItem()); /* LV Create */ items.add(getLVCreateItem()); /* LV Remove */ items.add(getLVRemoveItem()); /* LV Resize */ items.add(getLVResizeItem()); /* LV Snapshot */ items.add(getLVSnapshotItem()); /* attach / detach */ final MyMenuItem attachMenu = new MyMenuItem(Tools.getString("HostBrowser.Drbd.Detach"), NO_HARDDISK_ICON_LARGE, Tools.getString("HostBrowser.Drbd.Detach.ToolTip"), Tools.getString("HostBrowser.Drbd.Attach"), HARDDISK_DRBD_ICON_LARGE, Tools.getString("HostBrowser.Drbd.Attach.ToolTip"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { return !getBlockDevice().isDrbd() || getBlockDevice().isAttached(); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } return null; } @Override public void action() { if (this.getText().equals( Tools.getString("HostBrowser.Drbd.Attach"))) { attach(testOnly); } else { detach(testOnly); } } }; final ClusterBrowser wi = getBrowser().getClusterBrowser(); if (wi != null) { final ClusterBrowser.DRBDMenuItemCallback attachItemCallback = wi.new DRBDMenuItemCallback(attachMenu, getHost()) { @Override public void action(final Host host) { if (isDiskless(false)) { attach(true); } else { detach(true); } } }; addMouseOverListener(attachMenu, attachItemCallback); } items.add(attachMenu); /* connect / disconnect */ final MyMenuItem connectMenu = new MyMenuItem(Tools.getString("HostBrowser.Drbd.Disconnect"), null, Tools.getString("HostBrowser.Drbd.Disconnect"), Tools.getString("HostBrowser.Drbd.Connect"), null, Tools.getString("HostBrowser.Drbd.Connect"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { return isConnectedOrWF(testOnly); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isSyncing() || ((getBlockDevice().isPrimary() && getBlockDevice().isSyncSource()) || (getOtherBlockDevInfo().getBlockDevice(). isPrimary() && getBlockDevice().isSyncTarget()))) { return null; } else { return DrbdVolumeInfo.IS_SYNCING_STRING; } } @Override public void action() { if (this.getText().equals( Tools.getString("HostBrowser.Drbd.Connect"))) { connect(testOnly); } else { disconnect(testOnly); } } }; if (wi != null) { final ClusterBrowser.DRBDMenuItemCallback connectItemCallback = wi.new DRBDMenuItemCallback(connectMenu, getHost()) { @Override public void action(final Host host) { if (isConnectedOrWF(false)) { disconnect(true); } else { connect(true); } } }; addMouseOverListener(connectMenu, connectItemCallback); } items.add(connectMenu); /* set primary */ final MyMenuItem setPrimaryItem = new MyMenuItem(Tools.getString( "HostBrowser.Drbd.SetPrimaryOtherSecondary"), null, Tools.getString( "HostBrowser.Drbd.SetPrimaryOtherSecondary"), Tools.getString("HostBrowser.Drbd.SetPrimary"), null, Tools.getString("HostBrowser.Drbd.SetPrimary"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { if (!getBlockDevice().isDrbd()) { return false; } return getBlockDevice().isSecondary() && getOtherBlockDevInfo().getBlockDevice().isPrimary(); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isSecondary()) { return "cannot do that to the primary"; } return null; } @Override public void action() { BlockDevInfo oBdi = getOtherBlockDevInfo(); if (oBdi != null && oBdi.getBlockDevice().isPrimary() && !"yes".equals( drbdVolumeInfo.getDrbdResourceInfo().getParamSaved( ALLOW_TWO_PRIMARIES))) { oBdi.setSecondary(testOnly); } setPrimary(testOnly); } }; items.add(setPrimaryItem); /* set secondary */ final MyMenuItem setSecondaryItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.SetSecondary"), null, Tools.getString( "HostBrowser.Drbd.SetSecondary.ToolTip"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isPrimary()) { return "cannot do that to the secondary"; } return null; } @Override public void action() { setSecondary(testOnly); } }; //enableMenu(setSecondaryItem, false); items.add(setSecondaryItem); /* force primary */ final MyMenuItem forcePrimaryItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.ForcePrimary"), null, Tools.getString("HostBrowser.Drbd.ForcePrimary"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } return null; } @Override public void action() { forcePrimary(testOnly); } }; items.add(forcePrimaryItem); /* invalidate */ final MyMenuItem invalidateItem = new MyMenuItem( Tools.getString("HostBrowser.Drbd.Invalidate"), null, Tools.getString("HostBrowser.Drbd.Invalidate.ToolTip"), new AccessMode(ConfigData.AccessType.ADMIN, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } if (getDrbdVolumeInfo().isVerifying()) { return DrbdVolumeInfo.IS_VERIFYING_STRING; } return null; //return !getBlockDevice().isSyncing() // && !getDrbdVolumeInfo().isVerifying(); } @Override public void action() { invalidateBD(testOnly); } }; items.add(invalidateItem); /* resume / pause sync */ final MyMenuItem resumeSyncItem = new MyMenuItem( Tools.getString("HostBrowser.Drbd.ResumeSync"), null, Tools.getString("HostBrowser.Drbd.ResumeSync.ToolTip"), Tools.getString("HostBrowser.Drbd.PauseSync"), null, Tools.getString("HostBrowser.Drbd.PauseSync.ToolTip"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { return getBlockDevice().isSyncing() && getBlockDevice().isPausedSync(); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isSyncing()) { return "it is not being synced"; } return null; } @Override public void action() { if (this.getText().equals( Tools.getString("HostBrowser.Drbd.ResumeSync"))) { resumeSync(testOnly); } else { pauseSync(testOnly); } } }; items.add(resumeSyncItem); /* resize */ final MyMenuItem resizeItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.Resize"), null, Tools.getString("HostBrowser.Drbd.Resize.ToolTip"), new AccessMode(ConfigData.AccessType.ADMIN, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } return null; } @Override public void action() { resizeDrbd(testOnly); } }; items.add(resizeItem); /* discard my data */ final MyMenuItem discardDataItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.DiscardData"), null, Tools.getString( "HostBrowser.Drbd.DiscardData.ToolTip"), new AccessMode(ConfigData.AccessType.ADMIN, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } //if (isConnected(testOnly)) { // ? TODO: check this // return "is connected"; //} if (getBlockDevice().isPrimary()) { return "cannot do that to the primary"; } return null; //return !getBlockDevice().isSyncing() // && !isConnected(testOnly) // && !getBlockDevice().isPrimary(); } @Override public void action() { discardData(testOnly); } }; items.add(discardDataItem); /* proxy up/down */ final MyMenuItem proxyItem = new MyMenuItem(Tools.getString("BlockDevInfo.Drbd.ProxyDown"), null, getMenuToolTip("DRBD.proxyDown"), Tools.getString("BlockDevInfo.Drbd.ProxyUp"), null, getMenuToolTip("DRBD.proxyUp"), new AccessMode(ConfigData.AccessType.ADMIN, !AccessMode.ADVANCED), new AccessMode(ConfigData.AccessType.OP, !AccessMode.ADVANCED)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { if (!getBlockDevice().isDrbd()) { return false; } return getDrbdVolumeInfo().getDrbdResourceInfo().isProxy( getHost()); } @Override public String enablePredicate() { - if (!getHost().isDrbdProxyRunning()) { + final DrbdResourceInfo dri = + drbdVolumeInfo.getDrbdResourceInfo(); + final Host pHost = + dri.getProxyHost(getHost(), !DrbdResourceInfo.WIZARD); + if (!pHost.isConnected()) { + return Host.NOT_CONNECTED_STRING; + } + if (!pHost.isDrbdProxyRunning()) { return "proxy daemon is not running"; } return null; } @Override public boolean predicate() { + final DrbdResourceInfo dri = + drbdVolumeInfo.getDrbdResourceInfo(); + final Host pHost = + dri.getProxyHost(getHost(), !DrbdResourceInfo.WIZARD); if (getBlockDevice().isDrbd()) { - return getHost().isDrbdProxyUp( + return pHost.isDrbdProxyUp( drbdVolumeInfo.getDrbdResourceInfo().getName()); } else { return true; } } @Override public void action() { - if (getHost().isDrbdProxyUp( + final DrbdResourceInfo dri = + drbdVolumeInfo.getDrbdResourceInfo(); + final Host pHost = + dri.getProxyHost(getHost(), !DrbdResourceInfo.WIZARD); + if (pHost.isDrbdProxyUp( drbdVolumeInfo.getDrbdResourceInfo().getName())) { DRBD.proxyDown( - getHost(), + pHost, drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } else { DRBD.proxyUp( - getHost(), + pHost, drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } - getBrowser().getClusterBrowser().updateHWInfo(getHost()); + getBrowser().getClusterBrowser().updateProxyHWInfo(pHost); } }; items.add(proxyItem); /* view log */ final MyMenuItem viewDrbdLogItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.ViewDrbdLog"), LOGFILE_ICON, null, new AccessMode(ConfigData.AccessType.RO, false), new AccessMode(ConfigData.AccessType.RO, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { return null; } @Override public void action() { String device = getDrbdVolumeInfo().getDevice(); DrbdLog l = new DrbdLog(getHost(), device); l.showDialog(); } }; items.add(viewDrbdLogItem); return items; } /** Returns how much of the block device is used. */ @Override public int getUsed() { final DrbdVolumeInfo dvi = drbdVolumeInfo; if (dvi != null) { return dvi.getUsed(); } return getBlockDevice().getUsed(); } /** Returns text that appears above the icon. */ public String getIconTextForGraph(final boolean testOnly) { if (!getHost().isConnected()) { return Tools.getString("HostBrowser.Drbd.NoInfoAvailable"); } if (getBlockDevice().isDrbd()) { return getBlockDevice().getNodeState(); } return null; } public String getMainTextForGraph() { if (!isLVM()) { final String vg = getBlockDevice().getVolumeGroupOnPhysicalVolume(); if (vg != null && !"".equals(vg)) { return "VG " + vg; } } return getName(); } /** Returns text that appears in the corner of the drbd graph. */ public Subtext getRightCornerTextForDrbdGraph(final boolean testOnly) { String vg = null; if (isLVM()) { vg = getBlockDevice().getVolumeGroup(); } else { vg = getBlockDevice().getVolumeGroupOnPhysicalVolume(); } if (getBlockDevice().isDrbdMetaDisk()) { return METADISK_SUBTEXT; } else if (getBlockDevice().isSwap()) { return SWAP_SUBTEXT; } else if (getBlockDevice().getMountedOn() != null) { return MOUNTED_SUBTEXT; } else if (getBlockDevice().isDrbd()) { String s = getBlockDevice().getName(); // TODO: cache that if (s.length() > MAX_RIGHT_CORNER_STRING_LENGTH) { s = "..." + s.substring( s.length() - MAX_RIGHT_CORNER_STRING_LENGTH + 3, s.length()); } if (getBlockDevice().isDrbdPhysicalVolume()) { final String drbdVG = getBlockDevice().getDrbdBlockDevice() .getVolumeGroupOnPhysicalVolume(); if (drbdVG != null && !"".equals(drbdVG)) { s = s + " VG:" + drbdVG; } else { s = s + " PV"; } } return new Subtext(s, Color.BLUE, Color.BLACK); } else if (vg != null && !"".equals(vg)) { if (isLVM()) { return new Subtext("LV in " + vg, Color.BLUE, Color.GREEN); } else { return new Subtext(getName(), Color.BLUE, Color.GREEN); } } else if (getBlockDevice().isPhysicalVolume()) { return PHYSICAL_VOLUME_SUBTEXT; } return null; } /** Returns whether this device is connected via drbd. */ public boolean isConnected(final boolean testOnly) { final DRBDtestData dtd = getDRBDtestData(); if (testOnly && dtd != null) { return isConnectedTest(dtd) && !isWFConnection(testOnly); } else { return getBlockDevice().isConnected(); } } /** Returns whether this device is connected or wait-for-c via drbd. */ boolean isConnectedOrWF(final boolean testOnly) { final DRBDtestData dtd = getDRBDtestData(); if (testOnly && dtd != null) { return isConnectedTest(dtd); } else { return getBlockDevice().isConnectedOrWF(); } } /** Returns whether this device is in wait-for-connection state. */ public boolean isWFConnection(final boolean testOnly) { final DRBDtestData dtd = getDRBDtestData(); if (testOnly && dtd != null) { return isConnectedOrWF(testOnly) && isConnectedTest(dtd) && !getOtherBlockDevInfo().isConnectedTest(dtd); } else { return getBlockDevice().isWFConnection(); } } /** Returns whether this device will be disconnected. */ boolean isConnectedTest(final DRBDtestData dtd) { return dtd.isConnected(getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName()) || (!dtd.isDisconnected( getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName()) && getBlockDevice().isConnectedOrWF()); } /** Returns whether this device is diskless. */ public boolean isDiskless(final boolean testOnly) { final DRBDtestData dtd = getDRBDtestData(); final DrbdVolumeInfo dvi = drbdVolumeInfo; if (testOnly && dtd != null && dvi != null) { return dtd.isDiskless(getHost(), drbdVolumeInfo.getDevice()) || (!dtd.isAttached(getHost(), drbdVolumeInfo.getDevice()) && getBlockDevice().isDiskless()); } else { return getBlockDevice().isDiskless(); } } /** Returns drbd test data. */ DRBDtestData getDRBDtestData() { final ClusterBrowser b = getBrowser().getClusterBrowser(); if (b == null) { return null; } return b.getDRBDtestData(); } /** Sets drbd test data. */ void setDRBDtestData(final DRBDtestData drbdtestData) { final ClusterBrowser b = getBrowser().getClusterBrowser(); if (b == null) { return; } b.setDRBDtestData(drbdtestData); } /** Compares ignoring case and using drbd device names if available. */ @Override public int compareTo(final Info o) { String name; String oName; int volume = 0; int oVolume = 0; final DrbdVolumeInfo dvi = getDrbdVolumeInfo(); if (getBlockDevice().isDrbd() && dvi != null) { name = dvi.getDrbdResourceInfo().getName(); final String v = dvi.getName(); if (Tools.isNumber(v)) { volume = Integer.parseInt(v); } } else { name = getName(); } final BlockDevInfo obdi = (BlockDevInfo) o; final DrbdVolumeInfo odvi = obdi.getDrbdVolumeInfo(); if (obdi.getBlockDevice().isDrbd() && odvi != null) { oName = odvi.getDrbdResourceInfo().getName(); final String v = odvi.getName(); if (Tools.isNumber(v)) { oVolume = Integer.parseInt(v); } } else { oName = ((BlockDevInfo) o).getName(); } /* drbds up */ if (getBlockDevice().isDrbd() && !obdi.getBlockDevice().isDrbd()) { return -1; } if (!getBlockDevice().isDrbd() && obdi.getBlockDevice().isDrbd()) { return 1; } /* volume groups down */ if (getBlockDevice().isVolumeGroupOnPhysicalVolume() && !obdi.getBlockDevice().isVolumeGroupOnPhysicalVolume()) { return 1; } if (!getBlockDevice().isVolumeGroupOnPhysicalVolume() && obdi.getBlockDevice().isVolumeGroupOnPhysicalVolume()) { return -1; } final int ret = name.compareToIgnoreCase(oName); if (ret == 0) { return volume - oVolume; } return ret; } /** Sets stored parameters. */ public void setParameters(final String resName) { getBlockDevice().setNew(false); final ClusterBrowser clusterBrowser = getBrowser().getClusterBrowser(); if (clusterBrowser == null) { return; } final DrbdVolumeInfo dvi = drbdVolumeInfo; if (dvi == null) { return; } final DrbdXML dxml = clusterBrowser.getDrbdXML(); final String hostName = getHost().getName(); final DrbdGraph drbdGraph = getBrowser().getDrbdGraph(); String value = null; final String volumeNr = dvi.getName(); for (final String param : getParametersFromXML()) { if (DRBD_MD_PARAM.equals(param)) { value = dxml.getMetaDisk(hostName, resName, volumeNr); if (!"internal".equals(value)) { final BlockDevInfo mdI = drbdGraph.findBlockDevInfo(hostName, value); if (mdI != null) { getBlockDevice().setMetaDisk(mdI.getBlockDevice()); } } } else if (DRBD_MD_INDEX_PARAM.equals(param)) { value = dxml.getMetaDiskIndex(hostName, resName, volumeNr); } final String defaultValue = getParamDefault(param); if (value == null) { value = defaultValue; } if (value == null) { value = ""; } final String oldValue = getParamSaved(param); final Widget wi = getWidget(param, null); if (!Tools.areEqual(value, oldValue)) { getResource().setValue(param, value); if (wi != null) { wi.setValue(value); } } } } /** * Returns whether the specified parameter or any of the parameters * have changed. If param is null, only param will be checked, * otherwise all parameters will be checked. */ @Override public boolean checkResourceFieldsChanged(final String param, final String[] params) { return checkResourceFieldsChanged(param, params, false, false, false); } /** * Returns whether the specified parameter or any of the parameters * have changed. If param is null, only param will be checked, * otherwise all parameters will be checked. */ boolean checkResourceFieldsChanged( final String param, final String[] params, final boolean fromDrbdInfo, final boolean fromDrbdResourceInfo, final boolean fromDrbdVolumeInfo) { final DrbdVolumeInfo dvi = getDrbdVolumeInfo(); if (dvi != null && !fromDrbdVolumeInfo && !fromDrbdResourceInfo && !fromDrbdInfo) { dvi.setApplyButtons(null, dvi.getParametersFromXML()); } return super.checkResourceFieldsChanged(param, params); } /** * Returns whether all the parameters are correct. If param is null, * all paremeters will be checked, otherwise only the param, but other * parameters will be checked only in the cache. This is good if only * one value is changed and we don't want to check everything. */ @Override public boolean checkResourceFieldsCorrect(final String param, final String[] params) { return checkResourceFieldsCorrect(param, params, false, false, false); } /** * Returns whether all the parameters are correct. If param is null, * all paremeters will be checked, otherwise only the param, but other * parameters will be checked only in the cache. This is good if only * one value is changed and we don't want to check everything. */ boolean checkResourceFieldsCorrect(final String param, final String[] params, final boolean fromDrbdInfo, final boolean fromDrbdResourceInfo, final boolean fromDrbdVolumeInfo) { boolean correct = true; final DrbdXML dxml = getBrowser().getClusterBrowser().getDrbdXML(); if (dxml != null && dxml.isDrbdDisabled()) { correct = false; } return super.checkResourceFieldsCorrect(param, params) && correct; } /** Returns whether this block device is a volume group in LVM. */ public boolean isLVM() { return getBlockDevice().getVolumeGroup() != null; } /** Returns how much is free space in a volume group. */ public Long getFreeInVolumeGroup() { return getHost().getFreeInVolumeGroup( getBlockDevice().getVolumeGroup()); } /** Returns true if this is the first volume in the resource. Returns true * if this is not a DRBD resource. */ public boolean isFirstDrbdVolume() { if (!getBlockDevice().isDrbd()) { return true; } final Set<DrbdVolumeInfo> drbdVolumes = getDrbdVolumeInfo().getDrbdResourceInfo().getDrbdVolumes(); if (drbdVolumes == null || drbdVolumes.isEmpty()) { return true; } return drbdVolumes.iterator().next() == getDrbdVolumeInfo(); } /** Return whether two primaries are allowed. */ boolean allowTwoPrimaries() { final DrbdResourceInfo dri = drbdVolumeInfo.getDrbdResourceInfo(); return "yes".equals(dri.getParamSaved(ALLOW_TWO_PRIMARIES)); } /** * Proxy status for graph, null if there's no proxy configured for the * resource. */ public String getProxyStateForGraph(final boolean testOnly) { final DrbdResourceInfo dri = drbdVolumeInfo.getDrbdResourceInfo(); final Host pHost = dri.getProxyHost(getHost(), !DrbdResourceInfo.WIZARD); if (dri.isProxy(getHost())) { if (pHost.isConnected()) { if (pHost.isDrbdProxyUp(dri.getName())) { return PROXY_UP; } else { return PROXY_DOWN; } } else { if (drbdVolumeInfo.isConnected(testOnly)) { return PROXY_UP; } else { return pHost.getName(); } } } return null; } /** Tool tip for menu items. */ private String getMenuToolTip(final String cmd) { if (getBlockDevice().isDrbd()) { return DRBD.getDistCommand( cmd, getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName()).replaceAll("@.*?@", ""); } else { return null; } } }
false
true
public List<UpdatableItem> createPopup() { final List<UpdatableItem> items = new ArrayList<UpdatableItem>(); final BlockDevInfo thisClass = this; final boolean testOnly = false; final MyMenu repMenuItem = new MyMenu( Tools.getString("HostBrowser.Drbd.AddDrbdResource"), new AccessMode(ConfigData.AccessType.ADMIN, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public String enablePredicate() { final DrbdXML dxml = getBrowser().getClusterBrowser().getDrbdXML(); if (drbdVolumeInfo != null) { return "it is already a drbd resouce"; } else if (!getHost().isConnected()) { return Host.NOT_CONNECTED_STRING; } else if (!getHost().isDrbdLoaded()) { return "drbd is not loaded"; } else if (getBlockDevice().isMounted()) { return "is mounted"; } else if (getBlockDevice().isVolumeGroupOnPhysicalVolume()) { return "is volume group"; } else if (!getBlockDevice().isAvailable()) { return "not available"; } else if (dxml.isDrbdDisabled()) { return "disabled because of config"; } return null; } @Override public void update() { super.update(); Cluster cluster = getHost().getCluster(); Host[] otherHosts = cluster.getHostsArray(); final List<MyMenu> hostMenus = new ArrayList<MyMenu>(); for (final Host oHost : otherHosts) { if (oHost == getHost()) { continue; } final MyMenu hostMenu = new MyMenu(oHost.getName(), new AccessMode( ConfigData.AccessType.ADMIN, false), new AccessMode( ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public String enablePredicate() { final DrbdXML dxml = getBrowser().getClusterBrowser().getDrbdXML(); if (!oHost.isConnected()) { return Host.NOT_CONNECTED_STRING; } else if (!oHost.isDrbdLoaded()) { return "drbd is not loaded"; } else { return null; } //return oHost.isConnected() // && oHost.isDrbdLoaded(); } @Override public void update() { super.update(); Tools.invokeAndWait(new Runnable() { @Override public void run() { removeAll(); } }); Set<BlockDevInfo> blockDevInfos = oHost.getBrowser().getBlockDevInfosInSwing(); List<BlockDevInfo> blockDevInfosS = new ArrayList<BlockDevInfo>(); for (final BlockDevInfo oBdi : blockDevInfos) { if (oBdi.getName().equals( getBlockDevice().getName())) { blockDevInfosS.add(0, oBdi); } else { blockDevInfosS.add(oBdi); } } for (final BlockDevInfo oBdi : blockDevInfosS) { if (oBdi.getDrbdVolumeInfo() == null && oBdi.getBlockDevice().isAvailable()) { add(addDrbdResourceMenuItem(oBdi, testOnly)); } if (oBdi.getName().equals( getBlockDevice().getName())) { addSeparator(); } } } }; hostMenu.update(); hostMenus.add(hostMenu); } Tools.invokeAndWait(new Runnable() { @Override public void run() { removeAll(); for (final MyMenu hostMenu : hostMenus) { add(hostMenu); } } }); } }; items.add(repMenuItem); /* PV Create */ items.add(getPVCreateItem()); /* PV Remove */ items.add(getPVRemoveItem()); /* VG Create */ items.add(getVGCreateItem()); /* VG Remove */ items.add(getVGRemoveItem()); /* LV Create */ items.add(getLVCreateItem()); /* LV Remove */ items.add(getLVRemoveItem()); /* LV Resize */ items.add(getLVResizeItem()); /* LV Snapshot */ items.add(getLVSnapshotItem()); /* attach / detach */ final MyMenuItem attachMenu = new MyMenuItem(Tools.getString("HostBrowser.Drbd.Detach"), NO_HARDDISK_ICON_LARGE, Tools.getString("HostBrowser.Drbd.Detach.ToolTip"), Tools.getString("HostBrowser.Drbd.Attach"), HARDDISK_DRBD_ICON_LARGE, Tools.getString("HostBrowser.Drbd.Attach.ToolTip"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { return !getBlockDevice().isDrbd() || getBlockDevice().isAttached(); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } return null; } @Override public void action() { if (this.getText().equals( Tools.getString("HostBrowser.Drbd.Attach"))) { attach(testOnly); } else { detach(testOnly); } } }; final ClusterBrowser wi = getBrowser().getClusterBrowser(); if (wi != null) { final ClusterBrowser.DRBDMenuItemCallback attachItemCallback = wi.new DRBDMenuItemCallback(attachMenu, getHost()) { @Override public void action(final Host host) { if (isDiskless(false)) { attach(true); } else { detach(true); } } }; addMouseOverListener(attachMenu, attachItemCallback); } items.add(attachMenu); /* connect / disconnect */ final MyMenuItem connectMenu = new MyMenuItem(Tools.getString("HostBrowser.Drbd.Disconnect"), null, Tools.getString("HostBrowser.Drbd.Disconnect"), Tools.getString("HostBrowser.Drbd.Connect"), null, Tools.getString("HostBrowser.Drbd.Connect"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { return isConnectedOrWF(testOnly); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isSyncing() || ((getBlockDevice().isPrimary() && getBlockDevice().isSyncSource()) || (getOtherBlockDevInfo().getBlockDevice(). isPrimary() && getBlockDevice().isSyncTarget()))) { return null; } else { return DrbdVolumeInfo.IS_SYNCING_STRING; } } @Override public void action() { if (this.getText().equals( Tools.getString("HostBrowser.Drbd.Connect"))) { connect(testOnly); } else { disconnect(testOnly); } } }; if (wi != null) { final ClusterBrowser.DRBDMenuItemCallback connectItemCallback = wi.new DRBDMenuItemCallback(connectMenu, getHost()) { @Override public void action(final Host host) { if (isConnectedOrWF(false)) { disconnect(true); } else { connect(true); } } }; addMouseOverListener(connectMenu, connectItemCallback); } items.add(connectMenu); /* set primary */ final MyMenuItem setPrimaryItem = new MyMenuItem(Tools.getString( "HostBrowser.Drbd.SetPrimaryOtherSecondary"), null, Tools.getString( "HostBrowser.Drbd.SetPrimaryOtherSecondary"), Tools.getString("HostBrowser.Drbd.SetPrimary"), null, Tools.getString("HostBrowser.Drbd.SetPrimary"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { if (!getBlockDevice().isDrbd()) { return false; } return getBlockDevice().isSecondary() && getOtherBlockDevInfo().getBlockDevice().isPrimary(); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isSecondary()) { return "cannot do that to the primary"; } return null; } @Override public void action() { BlockDevInfo oBdi = getOtherBlockDevInfo(); if (oBdi != null && oBdi.getBlockDevice().isPrimary() && !"yes".equals( drbdVolumeInfo.getDrbdResourceInfo().getParamSaved( ALLOW_TWO_PRIMARIES))) { oBdi.setSecondary(testOnly); } setPrimary(testOnly); } }; items.add(setPrimaryItem); /* set secondary */ final MyMenuItem setSecondaryItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.SetSecondary"), null, Tools.getString( "HostBrowser.Drbd.SetSecondary.ToolTip"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isPrimary()) { return "cannot do that to the secondary"; } return null; } @Override public void action() { setSecondary(testOnly); } }; //enableMenu(setSecondaryItem, false); items.add(setSecondaryItem); /* force primary */ final MyMenuItem forcePrimaryItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.ForcePrimary"), null, Tools.getString("HostBrowser.Drbd.ForcePrimary"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } return null; } @Override public void action() { forcePrimary(testOnly); } }; items.add(forcePrimaryItem); /* invalidate */ final MyMenuItem invalidateItem = new MyMenuItem( Tools.getString("HostBrowser.Drbd.Invalidate"), null, Tools.getString("HostBrowser.Drbd.Invalidate.ToolTip"), new AccessMode(ConfigData.AccessType.ADMIN, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } if (getDrbdVolumeInfo().isVerifying()) { return DrbdVolumeInfo.IS_VERIFYING_STRING; } return null; //return !getBlockDevice().isSyncing() // && !getDrbdVolumeInfo().isVerifying(); } @Override public void action() { invalidateBD(testOnly); } }; items.add(invalidateItem); /* resume / pause sync */ final MyMenuItem resumeSyncItem = new MyMenuItem( Tools.getString("HostBrowser.Drbd.ResumeSync"), null, Tools.getString("HostBrowser.Drbd.ResumeSync.ToolTip"), Tools.getString("HostBrowser.Drbd.PauseSync"), null, Tools.getString("HostBrowser.Drbd.PauseSync.ToolTip"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { return getBlockDevice().isSyncing() && getBlockDevice().isPausedSync(); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isSyncing()) { return "it is not being synced"; } return null; } @Override public void action() { if (this.getText().equals( Tools.getString("HostBrowser.Drbd.ResumeSync"))) { resumeSync(testOnly); } else { pauseSync(testOnly); } } }; items.add(resumeSyncItem); /* resize */ final MyMenuItem resizeItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.Resize"), null, Tools.getString("HostBrowser.Drbd.Resize.ToolTip"), new AccessMode(ConfigData.AccessType.ADMIN, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } return null; } @Override public void action() { resizeDrbd(testOnly); } }; items.add(resizeItem); /* discard my data */ final MyMenuItem discardDataItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.DiscardData"), null, Tools.getString( "HostBrowser.Drbd.DiscardData.ToolTip"), new AccessMode(ConfigData.AccessType.ADMIN, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } //if (isConnected(testOnly)) { // ? TODO: check this // return "is connected"; //} if (getBlockDevice().isPrimary()) { return "cannot do that to the primary"; } return null; //return !getBlockDevice().isSyncing() // && !isConnected(testOnly) // && !getBlockDevice().isPrimary(); } @Override public void action() { discardData(testOnly); } }; items.add(discardDataItem); /* proxy up/down */ final MyMenuItem proxyItem = new MyMenuItem(Tools.getString("BlockDevInfo.Drbd.ProxyDown"), null, getMenuToolTip("DRBD.proxyDown"), Tools.getString("BlockDevInfo.Drbd.ProxyUp"), null, getMenuToolTip("DRBD.proxyUp"), new AccessMode(ConfigData.AccessType.ADMIN, !AccessMode.ADVANCED), new AccessMode(ConfigData.AccessType.OP, !AccessMode.ADVANCED)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { if (!getBlockDevice().isDrbd()) { return false; } return getDrbdVolumeInfo().getDrbdResourceInfo().isProxy( getHost()); } @Override public String enablePredicate() { if (!getHost().isDrbdProxyRunning()) { return "proxy daemon is not running"; } return null; } @Override public boolean predicate() { if (getBlockDevice().isDrbd()) { return getHost().isDrbdProxyUp( drbdVolumeInfo.getDrbdResourceInfo().getName()); } else { return true; } } @Override public void action() { if (getHost().isDrbdProxyUp( drbdVolumeInfo.getDrbdResourceInfo().getName())) { DRBD.proxyDown( getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } else { DRBD.proxyUp( getHost(), drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } getBrowser().getClusterBrowser().updateHWInfo(getHost()); } }; items.add(proxyItem); /* view log */ final MyMenuItem viewDrbdLogItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.ViewDrbdLog"), LOGFILE_ICON, null, new AccessMode(ConfigData.AccessType.RO, false), new AccessMode(ConfigData.AccessType.RO, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { return null; } @Override public void action() { String device = getDrbdVolumeInfo().getDevice(); DrbdLog l = new DrbdLog(getHost(), device); l.showDialog(); } }; items.add(viewDrbdLogItem); return items; }
public List<UpdatableItem> createPopup() { final List<UpdatableItem> items = new ArrayList<UpdatableItem>(); final BlockDevInfo thisClass = this; final boolean testOnly = false; final MyMenu repMenuItem = new MyMenu( Tools.getString("HostBrowser.Drbd.AddDrbdResource"), new AccessMode(ConfigData.AccessType.ADMIN, false), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public String enablePredicate() { final DrbdXML dxml = getBrowser().getClusterBrowser().getDrbdXML(); if (drbdVolumeInfo != null) { return "it is already a drbd resouce"; } else if (!getHost().isConnected()) { return Host.NOT_CONNECTED_STRING; } else if (!getHost().isDrbdLoaded()) { return "drbd is not loaded"; } else if (getBlockDevice().isMounted()) { return "is mounted"; } else if (getBlockDevice().isVolumeGroupOnPhysicalVolume()) { return "is volume group"; } else if (!getBlockDevice().isAvailable()) { return "not available"; } else if (dxml.isDrbdDisabled()) { return "disabled because of config"; } return null; } @Override public void update() { super.update(); Cluster cluster = getHost().getCluster(); Host[] otherHosts = cluster.getHostsArray(); final List<MyMenu> hostMenus = new ArrayList<MyMenu>(); for (final Host oHost : otherHosts) { if (oHost == getHost()) { continue; } final MyMenu hostMenu = new MyMenu(oHost.getName(), new AccessMode( ConfigData.AccessType.ADMIN, false), new AccessMode( ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public String enablePredicate() { final DrbdXML dxml = getBrowser().getClusterBrowser().getDrbdXML(); if (!oHost.isConnected()) { return Host.NOT_CONNECTED_STRING; } else if (!oHost.isDrbdLoaded()) { return "drbd is not loaded"; } else { return null; } //return oHost.isConnected() // && oHost.isDrbdLoaded(); } @Override public void update() { super.update(); Tools.invokeAndWait(new Runnable() { @Override public void run() { removeAll(); } }); Set<BlockDevInfo> blockDevInfos = oHost.getBrowser().getBlockDevInfosInSwing(); List<BlockDevInfo> blockDevInfosS = new ArrayList<BlockDevInfo>(); for (final BlockDevInfo oBdi : blockDevInfos) { if (oBdi.getName().equals( getBlockDevice().getName())) { blockDevInfosS.add(0, oBdi); } else { blockDevInfosS.add(oBdi); } } for (final BlockDevInfo oBdi : blockDevInfosS) { if (oBdi.getDrbdVolumeInfo() == null && oBdi.getBlockDevice().isAvailable()) { add(addDrbdResourceMenuItem(oBdi, testOnly)); } if (oBdi.getName().equals( getBlockDevice().getName())) { addSeparator(); } } } }; hostMenu.update(); hostMenus.add(hostMenu); } Tools.invokeAndWait(new Runnable() { @Override public void run() { removeAll(); for (final MyMenu hostMenu : hostMenus) { add(hostMenu); } } }); } }; items.add(repMenuItem); /* PV Create */ items.add(getPVCreateItem()); /* PV Remove */ items.add(getPVRemoveItem()); /* VG Create */ items.add(getVGCreateItem()); /* VG Remove */ items.add(getVGRemoveItem()); /* LV Create */ items.add(getLVCreateItem()); /* LV Remove */ items.add(getLVRemoveItem()); /* LV Resize */ items.add(getLVResizeItem()); /* LV Snapshot */ items.add(getLVSnapshotItem()); /* attach / detach */ final MyMenuItem attachMenu = new MyMenuItem(Tools.getString("HostBrowser.Drbd.Detach"), NO_HARDDISK_ICON_LARGE, Tools.getString("HostBrowser.Drbd.Detach.ToolTip"), Tools.getString("HostBrowser.Drbd.Attach"), HARDDISK_DRBD_ICON_LARGE, Tools.getString("HostBrowser.Drbd.Attach.ToolTip"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { return !getBlockDevice().isDrbd() || getBlockDevice().isAttached(); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } return null; } @Override public void action() { if (this.getText().equals( Tools.getString("HostBrowser.Drbd.Attach"))) { attach(testOnly); } else { detach(testOnly); } } }; final ClusterBrowser wi = getBrowser().getClusterBrowser(); if (wi != null) { final ClusterBrowser.DRBDMenuItemCallback attachItemCallback = wi.new DRBDMenuItemCallback(attachMenu, getHost()) { @Override public void action(final Host host) { if (isDiskless(false)) { attach(true); } else { detach(true); } } }; addMouseOverListener(attachMenu, attachItemCallback); } items.add(attachMenu); /* connect / disconnect */ final MyMenuItem connectMenu = new MyMenuItem(Tools.getString("HostBrowser.Drbd.Disconnect"), null, Tools.getString("HostBrowser.Drbd.Disconnect"), Tools.getString("HostBrowser.Drbd.Connect"), null, Tools.getString("HostBrowser.Drbd.Connect"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { return isConnectedOrWF(testOnly); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isSyncing() || ((getBlockDevice().isPrimary() && getBlockDevice().isSyncSource()) || (getOtherBlockDevInfo().getBlockDevice(). isPrimary() && getBlockDevice().isSyncTarget()))) { return null; } else { return DrbdVolumeInfo.IS_SYNCING_STRING; } } @Override public void action() { if (this.getText().equals( Tools.getString("HostBrowser.Drbd.Connect"))) { connect(testOnly); } else { disconnect(testOnly); } } }; if (wi != null) { final ClusterBrowser.DRBDMenuItemCallback connectItemCallback = wi.new DRBDMenuItemCallback(connectMenu, getHost()) { @Override public void action(final Host host) { if (isConnectedOrWF(false)) { disconnect(true); } else { connect(true); } } }; addMouseOverListener(connectMenu, connectItemCallback); } items.add(connectMenu); /* set primary */ final MyMenuItem setPrimaryItem = new MyMenuItem(Tools.getString( "HostBrowser.Drbd.SetPrimaryOtherSecondary"), null, Tools.getString( "HostBrowser.Drbd.SetPrimaryOtherSecondary"), Tools.getString("HostBrowser.Drbd.SetPrimary"), null, Tools.getString("HostBrowser.Drbd.SetPrimary"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { if (!getBlockDevice().isDrbd()) { return false; } return getBlockDevice().isSecondary() && getOtherBlockDevInfo().getBlockDevice().isPrimary(); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isSecondary()) { return "cannot do that to the primary"; } return null; } @Override public void action() { BlockDevInfo oBdi = getOtherBlockDevInfo(); if (oBdi != null && oBdi.getBlockDevice().isPrimary() && !"yes".equals( drbdVolumeInfo.getDrbdResourceInfo().getParamSaved( ALLOW_TWO_PRIMARIES))) { oBdi.setSecondary(testOnly); } setPrimary(testOnly); } }; items.add(setPrimaryItem); /* set secondary */ final MyMenuItem setSecondaryItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.SetSecondary"), null, Tools.getString( "HostBrowser.Drbd.SetSecondary.ToolTip"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isPrimary()) { return "cannot do that to the secondary"; } return null; } @Override public void action() { setSecondary(testOnly); } }; //enableMenu(setSecondaryItem, false); items.add(setSecondaryItem); /* force primary */ final MyMenuItem forcePrimaryItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.ForcePrimary"), null, Tools.getString("HostBrowser.Drbd.ForcePrimary"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } return null; } @Override public void action() { forcePrimary(testOnly); } }; items.add(forcePrimaryItem); /* invalidate */ final MyMenuItem invalidateItem = new MyMenuItem( Tools.getString("HostBrowser.Drbd.Invalidate"), null, Tools.getString("HostBrowser.Drbd.Invalidate.ToolTip"), new AccessMode(ConfigData.AccessType.ADMIN, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } if (getDrbdVolumeInfo().isVerifying()) { return DrbdVolumeInfo.IS_VERIFYING_STRING; } return null; //return !getBlockDevice().isSyncing() // && !getDrbdVolumeInfo().isVerifying(); } @Override public void action() { invalidateBD(testOnly); } }; items.add(invalidateItem); /* resume / pause sync */ final MyMenuItem resumeSyncItem = new MyMenuItem( Tools.getString("HostBrowser.Drbd.ResumeSync"), null, Tools.getString("HostBrowser.Drbd.ResumeSync.ToolTip"), Tools.getString("HostBrowser.Drbd.PauseSync"), null, Tools.getString("HostBrowser.Drbd.PauseSync.ToolTip"), new AccessMode(ConfigData.AccessType.OP, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean predicate() { return getBlockDevice().isSyncing() && getBlockDevice().isPausedSync(); } @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (!getBlockDevice().isSyncing()) { return "it is not being synced"; } return null; } @Override public void action() { if (this.getText().equals( Tools.getString("HostBrowser.Drbd.ResumeSync"))) { resumeSync(testOnly); } else { pauseSync(testOnly); } } }; items.add(resumeSyncItem); /* resize */ final MyMenuItem resizeItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.Resize"), null, Tools.getString("HostBrowser.Drbd.Resize.ToolTip"), new AccessMode(ConfigData.AccessType.ADMIN, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } return null; } @Override public void action() { resizeDrbd(testOnly); } }; items.add(resizeItem); /* discard my data */ final MyMenuItem discardDataItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.DiscardData"), null, Tools.getString( "HostBrowser.Drbd.DiscardData.ToolTip"), new AccessMode(ConfigData.AccessType.ADMIN, true), new AccessMode(ConfigData.AccessType.OP, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { if (!getBlockDevice().isDrbd()) { return NO_DRBD_RESOURCE_STRING; } if (!Tools.getConfigData().isAdvancedMode() && drbdVolumeInfo.getDrbdResourceInfo().isUsedByCRM()) { return DrbdVolumeInfo.IS_USED_BY_CRM_STRING; } if (getBlockDevice().isSyncing()) { return DrbdVolumeInfo.IS_SYNCING_STRING; } //if (isConnected(testOnly)) { // ? TODO: check this // return "is connected"; //} if (getBlockDevice().isPrimary()) { return "cannot do that to the primary"; } return null; //return !getBlockDevice().isSyncing() // && !isConnected(testOnly) // && !getBlockDevice().isPrimary(); } @Override public void action() { discardData(testOnly); } }; items.add(discardDataItem); /* proxy up/down */ final MyMenuItem proxyItem = new MyMenuItem(Tools.getString("BlockDevInfo.Drbd.ProxyDown"), null, getMenuToolTip("DRBD.proxyDown"), Tools.getString("BlockDevInfo.Drbd.ProxyUp"), null, getMenuToolTip("DRBD.proxyUp"), new AccessMode(ConfigData.AccessType.ADMIN, !AccessMode.ADVANCED), new AccessMode(ConfigData.AccessType.OP, !AccessMode.ADVANCED)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { if (!getBlockDevice().isDrbd()) { return false; } return getDrbdVolumeInfo().getDrbdResourceInfo().isProxy( getHost()); } @Override public String enablePredicate() { final DrbdResourceInfo dri = drbdVolumeInfo.getDrbdResourceInfo(); final Host pHost = dri.getProxyHost(getHost(), !DrbdResourceInfo.WIZARD); if (!pHost.isConnected()) { return Host.NOT_CONNECTED_STRING; } if (!pHost.isDrbdProxyRunning()) { return "proxy daemon is not running"; } return null; } @Override public boolean predicate() { final DrbdResourceInfo dri = drbdVolumeInfo.getDrbdResourceInfo(); final Host pHost = dri.getProxyHost(getHost(), !DrbdResourceInfo.WIZARD); if (getBlockDevice().isDrbd()) { return pHost.isDrbdProxyUp( drbdVolumeInfo.getDrbdResourceInfo().getName()); } else { return true; } } @Override public void action() { final DrbdResourceInfo dri = drbdVolumeInfo.getDrbdResourceInfo(); final Host pHost = dri.getProxyHost(getHost(), !DrbdResourceInfo.WIZARD); if (pHost.isDrbdProxyUp( drbdVolumeInfo.getDrbdResourceInfo().getName())) { DRBD.proxyDown( pHost, drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } else { DRBD.proxyUp( pHost, drbdVolumeInfo.getDrbdResourceInfo().getName(), drbdVolumeInfo.getName(), testOnly); } getBrowser().getClusterBrowser().updateProxyHWInfo(pHost); } }; items.add(proxyItem); /* view log */ final MyMenuItem viewDrbdLogItem = new MyMenuItem(Tools.getString("HostBrowser.Drbd.ViewDrbdLog"), LOGFILE_ICON, null, new AccessMode(ConfigData.AccessType.RO, false), new AccessMode(ConfigData.AccessType.RO, false)) { private static final long serialVersionUID = 1L; @Override public boolean visiblePredicate() { return getBlockDevice().isDrbd(); } @Override public String enablePredicate() { return null; } @Override public void action() { String device = getDrbdVolumeInfo().getDevice(); DrbdLog l = new DrbdLog(getHost(), device); l.showDialog(); } }; items.add(viewDrbdLogItem); return items; }
diff --git a/src/main/java/com/taobao/yarn/mpi/client/Client.java b/src/main/java/com/taobao/yarn/mpi/client/Client.java index 0762494..1472bb6 100644 --- a/src/main/java/com/taobao/yarn/mpi/client/Client.java +++ b/src/main/java/com/taobao/yarn/mpi/client/Client.java @@ -1,657 +1,662 @@ package com.taobao.yarn.mpi.client; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.ClientRMProtocol; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportResponse; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.GetNewApplicationResponse; import org.apache.hadoop.yarn.api.protocolrecords.KillApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationRequest; import org.apache.hadoop.yarn.api.protocolrecords.SubmitApplicationResponse; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ApplicationReport; import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext; import org.apache.hadoop.yarn.api.records.ContainerLaunchContext; import org.apache.hadoop.yarn.api.records.FinalApplicationStatus; import org.apache.hadoop.yarn.api.records.LocalResource; import org.apache.hadoop.yarn.api.records.LocalResourceType; import org.apache.hadoop.yarn.api.records.LocalResourceVisibility; import org.apache.hadoop.yarn.api.records.Priority; import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.api.records.YarnApplicationState; import org.apache.hadoop.yarn.exceptions.YarnRemoteException; import org.apache.hadoop.yarn.ipc.YarnRPC; import org.apache.hadoop.yarn.util.ConverterUtils; import org.apache.hadoop.yarn.util.Records; import com.taobao.yarn.mpi.MPIConfiguration; import com.taobao.yarn.mpi.MPIConstants; import com.taobao.yarn.mpi.server.ApplicationMaster; import com.taobao.yarn.mpi.server.Utilities; /** * Client for MPI application submission to YARN. */ public class Client { private static final Log LOG = LogFactory.getLog(Client.class); // Configuration private final MPIConfiguration conf; // RPC to communicate to RM private final YarnRPC rpc; // Handle to talk to the Resource Manager/Applications Manager private ClientRMProtocol applicationsManager; // Application master specific info to register a new Application with RM/ASM private String appName = "MPICH2-"; // App master priority private int amPriority = 0; // Queue for App master private String amQueue = ""; // Amt. of memory resource to request for to run the App Master private int amMemory = 64; // Application master jar file private String appMasterJar = ""; // Shell Command Container priority private int containerPriority = 0; // Amt of memory to request for container in which shell script will be executed private int containerMemory = 10; // No. of containers in which the shell script needs to be executed private int numContainers = 1; // Start time for client private final long clientStartTime = System.currentTimeMillis(); // Timeout threshold for client. Kill app after time interval expires. private long clientTimeout = 24 * 60 * 60 * 1000; // 86400000 ms, 24 hours // Location of the MPI application private String mpiApplication = ""; // Is the MPI application running private transient boolean isRunnig = false; // MPI Options private String mpiOptions = ""; // Debug flag boolean debugFlag = false; private enum TaskType { RUN, KILL } private TaskType taskType = TaskType.RUN; private String appIdToKill; private ApplicationId appId; /** * @param args Command line arguments */ public static void main(String[] args) { boolean result = false; try { Client client = new Client(); LOG.info("Initializing Client"); if (!client.init(args)) { System.exit(0); } if (client.taskType == TaskType.RUN) { result = client.run(); } else if (client.taskType == TaskType.KILL) { result = client.kill(); } } catch (Throwable t) { LOG.fatal("Error running CLient", t); System.exit(1); } if (result) { LOG.info("Application completed successfully"); System.exit(0); } LOG.error("Application failed to complete successfully"); System.exit(2); } /** * Constructor, create YarnRPC */ public Client(MPIConfiguration conf) throws Exception { // Set up the configuration and RPC this.conf = conf; rpc = YarnRPC.create(conf); } /** * Constructor, create YarnRPC */ public Client() throws Exception { this(new MPIConfiguration()); } /** * Helper function to print out usage * @param opts Parsed command line options */ private void printUsage(Options opts) { new HelpFormatter().printHelp("Client", opts); } // load/reload Configuration public void reloadConfiguration() { amMemory = conf.getInt(MPIConfiguration.MPI_EXEC_LOCATION, 64); containerMemory = conf.getInt(MPIConfiguration.MPI_CONTAINER_MEMORY, 64); amPriority = conf.getInt(MPIConfiguration.MPI_AM_PRIORITY, 0); containerPriority = conf.getInt(MPIConfiguration.MPI_CONTAINER_PRIORITY, 0); amQueue = conf.get(MPIConfiguration.MPI_QUEUE); clientTimeout = conf.getLong(MPIConfiguration.MPI_TIMEOUT, 24 * 60 * 60 * 1000); } /** * Parse command line options * @param args Parsed command line options * @return Whether the init was successful to run the client * @throws ParseException */ public boolean init(String[] args) throws ParseException { reloadConfiguration(); Options opts = new Options(); opts.addOption("M", "master-memory", true, "Amount of memory in MB to be requested to run the application master"); opts.addOption("m", "container-memory", true, "Amount of memory in MB to be requested to run the shell command"); opts.addOption("a", "mpi-application", true, "Location of the mpi application to be executed"); opts.addOption("o", "mpi-options", true, "Options for mpi program"); opts.addOption("P", "priority", true, "Application Priority. Default 0"); opts.addOption("p", "container-priority", true, "Priority for the shell command containers"); opts.addOption("q", "queue", true, "RM Queue in which this application is to be submitted"); opts.addOption("t", "timeout", true, "Wall-time, Application timeout in milliseconds, default is 86400000ms, i.e. 24hours"); opts.addOption("n", "num-containers", true, "No. of containers on which the mpi program needs to be executed"); opts.addOption("k", "kill", true, "Running MPI Application id"); opts.addOption("d", "debug", false, "Dump out debug information"); opts.addOption("h", "help", false, "Print usage"); CommandLine cliParser = new GnuParser().parse(opts, args); // empty commandline if (cliParser.getOptions().length == 0) { printUsage(opts); return false; } if (cliParser.hasOption("kill")) { taskType = TaskType.KILL; appIdToKill = cliParser.getOptionValue("kill"); return true; } if (cliParser.hasOption("master-memory")) { amMemory = Integer.parseInt(cliParser.getOptionValue("master-memory", "64")); } if (amMemory <= 0) { throw new IllegalArgumentException("Invalid memory specified for application master, exiting." + " Specified memory=" + amMemory); } if (cliParser.hasOption("container-memory")) { containerMemory = Integer.parseInt(cliParser.getOptionValue("container-memory", "64")); } if (containerMemory <= 0) { throw new IllegalArgumentException("Invalid memory specified for containers, exiting." + "Specified memory=" + containerMemory); } if (cliParser.hasOption("priority")) { amPriority = Integer.parseInt(cliParser.getOptionValue("priority", "0")); } if (cliParser.hasOption("queue")) { amQueue = cliParser.getOptionValue("queue", "default"); } // MPI executable program is a must if (!cliParser.hasOption("mpi-application")) { throw new IllegalArgumentException("No mpi executable program specified, exiting."); } mpiApplication = cliParser.getOptionValue("mpi-application"); appName += (new File(mpiApplication)).getName(); if (cliParser.hasOption("mpi-options")) { mpiOptions = cliParser.getOptionValue("mpi-options"); } if (cliParser.hasOption("container-priority")) { containerPriority = Integer.parseInt(cliParser.getOptionValue("container-priority", "0")); } numContainers = Integer.parseInt(cliParser.getOptionValue("num-containers", "1")); LOG.info("Container number is " + numContainers); if (numContainers < 1) { throw new IllegalArgumentException("Invalid no. of containers specified, exiting." + ", numContainer=" + numContainers); } if (cliParser.hasOption("timeout")) { clientTimeout = Integer.parseInt(cliParser.getOptionValue("timeout", "86400000")); } if (cliParser.hasOption("debug")) { debugFlag = true; } if (args.length == 0 || cliParser.hasOption("help")) { printUsage(opts); return false; } appMasterJar = JobConf.findContainingJar(ApplicationMaster.class); LOG.info("Application Master's jar is " + appMasterJar); return true; } /** * Main run function for the client * @return true if application completed successfully * @throws IOException */ public boolean run() throws IOException { LOG.info("Starting Client"); // Connect to ResourceManager connectToASM(); assert(applicationsManager != null); // Get a new application id GetNewApplicationResponse newApp = getApplication(); appId = newApp.getApplicationId(); LOG.info("Got Applicatioin: " + appId.toString()); // TODO get min/max resource capabilities from RM and change memory ask if needed // If we do not have min/max, we may not be able to correctly request // the required resources from the RM for the app master // Memory ask has to be a multiple of min and less than max. // Dump out information about cluster capability as seen by the resource manager int minMem = newApp.getMinimumResourceCapability().getMemory(); int maxMem = newApp.getMaximumResourceCapability().getMemory(); LOG.info("Min mem capabililty of resources in this cluster " + minMem); LOG.info("Max mem capabililty of resources in this cluster " + maxMem); // A resource ask has to be at least the minimum of the capability of the cluster, // the value has to be a multiple of the min value and cannot exceed the max. // If it is not an exact multiple of min, the RM will allocate to the nearest multiple of min if (amMemory < minMem) { LOG.info("AM memory specified below min threshold of cluster. Using min value." + ", specified=" + amMemory + ", min=" + minMem); amMemory = minMem; } else if (amMemory > maxMem) { LOG.info("AM memory specified above max threshold of cluster. Using max value." + ", specified=" + amMemory + ", max=" + maxMem); amMemory = maxMem; } + if (containerMemory * numContainers > maxMem) { + LOG.error("Container memories specified above the max threhold " + +"(yarn.scheduler.maximum-allocation-mb) of the cluster"); + return false; + } // Create launch context for app master LOG.info("Setting up application submission context for ASM"); ApplicationSubmissionContext appContext = Records.newRecord(ApplicationSubmissionContext.class); // set the application id LOG.info("Set Application Id: " + appId); appContext.setApplicationId(appId); // set the application name LOG.info("Set Application Name: " + appName); appContext.setApplicationName(appName); // Set up the container launch context for the application master ContainerLaunchContext amContainer = Records.newRecord(ContainerLaunchContext.class); LOG.info("Copy App Master jar from local filesystem and add to local environment"); // Copy the application master jar to the filesystem // Create a local resource to point to the destination jar path FileSystem fs = FileSystem.get(conf); Path appJarSrc = new Path(appMasterJar); LOG.info("Source path: " + appJarSrc.toString()); String pathSuffix = appName + "/" + appId.getId() + "/AppMaster.jar"; Path appJarDst = new Path(fs.getHomeDirectory(), pathSuffix); LOG.info("Destination path: " + appJarDst.toString()); fs.copyFromLocalFile(false, true, appJarSrc, appJarDst); FileStatus appJarDestStatus = fs.getFileStatus(appJarDst); // set local resources for the application master Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); LocalResource amJarRsrc = Records.newRecord(LocalResource.class); amJarRsrc.setType(LocalResourceType.FILE); amJarRsrc.setVisibility(LocalResourceVisibility.APPLICATION); // Set the resource to be copied over amJarRsrc.setResource(ConverterUtils.getYarnUrlFromPath(appJarDst)); // Set timestamp and length of file so that the framework can do basic sanity // checks for the local resource after it has been copied over to ensure // it is the same resource the client intended to use with the application amJarRsrc.setTimestamp(appJarDestStatus.getModificationTime()); amJarRsrc.setSize(appJarDestStatus.getLen()); localResources.put("AppMaster.jar", amJarRsrc); // Set local resource info into app master container launch context amContainer.setLocalResources(localResources); LOG.info("Copy MPI application from local filesystem to remote."); assert(!mpiApplication.isEmpty()); Path mpiAppSrc = new Path(mpiApplication); String mpiAppSuffix = appName + "/" + appId.getId() + "/MPIExec"; Path mpiAppDst = new Path(fs.getHomeDirectory(), mpiAppSuffix); fs.copyFromLocalFile(false, true, mpiAppSrc, mpiAppDst); FileStatus mpiAppFileStatus = fs.getFileStatus(mpiAppDst); // Set the env variables to be setup in the env where the application master will be run LOG.info("Set the environment for the application master and mpi application"); Map<String, String> env = new HashMap<String, String>(); // put location of mpi app and appmaster.jar into env // using the env info, the application master will create the correct local resource for the // eventual containers that will be launched to execute the shell scripts env.put(MPIConstants.MPIEXECLOCATION, mpiAppDst.toUri().toString()); env.put(MPIConstants.MPIEXECTIMESTAMP, Long.toString(mpiAppFileStatus.getModificationTime())); env.put(MPIConstants.MPIEXECLEN, Long.toString(mpiAppFileStatus.getLen())); env.put(MPIConstants.APPJARLOCATION, appJarDst.toUri().toString()); env.put(MPIConstants.APPJARTIMESTAMP, Long.toString(appJarDestStatus.getModificationTime())); env.put(MPIConstants.APPJARLEN, Long.toString(appJarDestStatus.getLen())); if (!mpiOptions.isEmpty()) { env.put(MPIConstants.MPIOPTIONS, mpiOptions); } // Add AppMaster.jar location to classpath. At some point we should not be // required to add the hadoop specific classpaths to the env. It should be // provided out of the box. For now setting all required classpaths including // the classpath to "." for the application jar StringBuilder classPathEnv = new StringBuilder("${CLASSPATH}:./*"); for (String c : conf.getStrings( MPIConfiguration.YARN_APPLICATION_CLASSPATH, MPIConfiguration.DEFAULT_MPI_APPLICATION_CLASSPATH)) { classPathEnv.append(':'); classPathEnv.append(c.trim()); } // add the runtime classpath needed for tests to work String testRuntimeClassPath = Client.getTestRuntimeClasspath(); classPathEnv.append(':'); classPathEnv.append(testRuntimeClassPath); env.put("CLASSPATH", classPathEnv.toString()); amContainer.setEnvironment(env); // Set the necessary command to execute the application master Vector<CharSequence> vargs = new Vector<CharSequence>(30); // Set java executable command LOG.info("Setting up app master command"); vargs.add("${JAVA_HOME}" + "/bin/java"); // Set Xmx based on am memory size vargs.add("-Xmx" + amMemory + "m"); // Set class name vargs.add("com.taobao.yarn.mpi.server.ApplicationMaster"); // Set params for Application Master vargs.add("--container_memory " + String.valueOf(containerMemory)); vargs.add("--num_containers " + String.valueOf(numContainers)); vargs.add("--priority " + String.valueOf(containerPriority)); if (debugFlag) { vargs.add("--debug"); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stdout"); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stderr"); // Get final commmand StringBuilder command = new StringBuilder(); for (CharSequence str : vargs) { command.append(str).append(" "); } LOG.info("Completed setting up app master command " + command.toString()); List<String> commands = new ArrayList<String>(); commands.add(command.toString()); amContainer.setCommands(commands); // Set up resource type requirements // For now, only memory is supported so we set memory requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory(amMemory); amContainer.setResource(capability); appContext.setAMContainerSpec(amContainer); // Set the priority for the application master Priority pri = Records.newRecord(Priority.class); // TODO - what is the range for priority? how to decide? pri.setPriority(amPriority); appContext.setPriority(pri); // Set the queue to which this application is to be submitted in the RM appContext.setQueue(amQueue); // Create the request to send to the applications manager SubmitApplicationRequest appRequest = Records.newRecord(SubmitApplicationRequest.class); appRequest.setApplicationSubmissionContext(appContext); // Submit the application to the applications manager // Ignore the response as either a valid response object is returned on success // or an exception thrown to denote some form of a failure LOG.info("Submitting application to ASM"); isRunnig = true; SubmitApplicationResponse submitResp = applicationsManager.submitApplication(appRequest); LOG.info("Submisstion result: " + submitResp.toString()); // TODO Try submitting the same request again. app submission failure? // Monitor the application return monitorApplication(); } /** * Monitor the submitted application for completion. * Kill application if time expires. * @param appId Application Id of application to be monitored * @return true if application completed successfully * @throws YarnRemoteException */ private boolean monitorApplication() throws YarnRemoteException { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (isRunnig) { try { killApplication(appId); } catch (YarnRemoteException e) { LOG.error("Error killing application: ", e); } } } }); while (true) { // FIXME hard coding sleep time Utilities.sleep(1000); // Get application report for the appId we are interested in GetApplicationReportRequest reportRequest = Records.newRecord(GetApplicationReportRequest.class); reportRequest.setApplicationId(appId); GetApplicationReportResponse reportResponse = applicationsManager.getApplicationReport(reportRequest); ApplicationReport report = reportResponse.getApplicationReport(); LOG.info("Got application report from ASM for" + ", appId=" + appId.getId() + ", clientToken=" + report.getClientToken() + ", appDiagnostics=" + report.getDiagnostics() + ", appMasterHost=" + report.getHost() + ", appQueue=" + report.getQueue() + ", appMasterRpcPort=" + report.getRpcPort() + ", appStartTime=" + report.getStartTime() + ", yarnAppState=" + report.getYarnApplicationState().toString() + ", distributedFinalState=" + report.getFinalApplicationStatus().toString() + ", appTrackingUrl=" + report.getTrackingUrl() + ", appUser=" + report.getUser()); YarnApplicationState state = report.getYarnApplicationState(); FinalApplicationStatus dsStatus = report.getFinalApplicationStatus(); if (YarnApplicationState.FINISHED == state) { isRunnig = false; if (FinalApplicationStatus.SUCCEEDED == dsStatus) { LOG.info("Application has completed successfully. Breaking monitoring loop"); return true; } else { LOG.info("Application did finished unsuccessfully." + " YarnState=" + state.toString() + ", DSFinalStatus=" + dsStatus.toString() + ". Breaking monitoring loop"); return false; } } else if (YarnApplicationState.KILLED == state || YarnApplicationState.FAILED == state) { isRunnig = false; LOG.info("Application did not finish." + " YarnState=" + state.toString() + ", DSFinalStatus=" + dsStatus.toString() + ". Breaking monitoring loop"); return false; } if (System.currentTimeMillis() > (clientStartTime + clientTimeout)) { LOG.info("Reached client specified timeout for application. Killing application"); killApplication(appId); isRunnig = false; return false; } } // end while } /** * Kill a submitted application by sending a call to the ASM * @param appId Application Id to be killed. * @throws YarnRemoteException */ private void killApplication(ApplicationId appId) throws YarnRemoteException { KillApplicationRequest request = Records.newRecord(KillApplicationRequest.class); // TODO clarify whether multiple jobs with the same app id can be submitted // and be running at the same time. If yes, can we kill a particular attempt only? request.setApplicationId(appId); LOG.info("Killing appliation with id: " + appId.toString()); // Response can be ignored as it is non-null on success or throws an exception in case of failures applicationsManager.forceKillApplication(request); } /** * Connect to the Resource Manager/Applications Manager * @return Handle to communicate with the ASM * @throws IOException */ private void connectToASM() throws IOException { MPIConfiguration yarnConf = new MPIConfiguration(conf); InetSocketAddress rmAddress = yarnConf.getSocketAddr( MPIConfiguration.RM_ADDRESS, MPIConfiguration.DEFAULT_RM_ADDRESS, MPIConfiguration.DEFAULT_RM_PORT); LOG.info("Connecting to ResourceManager at " + rmAddress); applicationsManager = ((ClientRMProtocol) rpc.getProxy( ClientRMProtocol.class, rmAddress, conf)); } /** * Get a new application from the ASM * @return New Application * @throws YarnRemoteException */ private GetNewApplicationResponse getApplication() throws YarnRemoteException { GetNewApplicationRequest request = Records.newRecord(GetNewApplicationRequest.class); GetNewApplicationResponse response = applicationsManager.getNewApplication(request); LOG.info("Got new application id=" + response.getApplicationId()); return response; } private static String getTestRuntimeClasspath() { InputStream classpathFileStream = null; BufferedReader reader = null; String envClassPath = ""; LOG.info("Trying to generate classpath for app master from current thread's classpath"); try { // Create classpath from generated classpath // Check maven ppom.xml for generated classpath info // Works if compile time env is same as runtime. Mainly tests. ClassLoader thisClassLoader = Thread.currentThread().getContextClassLoader(); String generatedClasspathFile = "yarn-apps-ds-generated-classpath"; classpathFileStream = thisClassLoader.getResourceAsStream(generatedClasspathFile); if (classpathFileStream == null) { LOG.info("Could not classpath resource from class loader"); return envClassPath; } LOG.info("Readable bytes from stream=" + classpathFileStream.available()); reader = new BufferedReader(new InputStreamReader(classpathFileStream)); String cp = reader.readLine(); if (cp != null) { envClassPath += cp.trim() + ":"; } // Put the file itself on classpath for tasks. envClassPath += thisClassLoader.getResource(generatedClasspathFile).getFile(); } catch (IOException e) { LOG.info("Could not find the necessary resource to generate class path for tests. Error=" + e.getMessage()); } try { if (classpathFileStream != null) { classpathFileStream.close(); } if (reader != null) { reader.close(); } } catch (IOException e) { LOG.info("Failed to close class path file stream or reader. Error=" + e.getMessage()); } return envClassPath; } /** * Kill the command-line specified appId * @return */ public boolean kill() { try { connectToASM(); ApplicationId appId = parseAppId(appIdToKill); if (null == appId) return false; killApplication(appId); } catch (YarnRemoteException e) { LOG.error("Killing " + appIdToKill + " failed", e); return false; } catch (IOException e) { LOG.error("Connecting RM to kill " + appIdToKill + " failed", e); return false; } return true; } private static ApplicationId parseAppId(String appIdStr) { Pattern p = Pattern.compile("application_(\\d+)_(\\d+)"); Matcher m = p.matcher(appIdStr); if (!m.matches()) return null; ApplicationId appId = Records.newRecord(ApplicationId.class); appId.setClusterTimestamp(Long.parseLong(m.group(1))); appId.setId(Integer.parseInt(m.group(2))); return appId; } }
true
true
public boolean run() throws IOException { LOG.info("Starting Client"); // Connect to ResourceManager connectToASM(); assert(applicationsManager != null); // Get a new application id GetNewApplicationResponse newApp = getApplication(); appId = newApp.getApplicationId(); LOG.info("Got Applicatioin: " + appId.toString()); // TODO get min/max resource capabilities from RM and change memory ask if needed // If we do not have min/max, we may not be able to correctly request // the required resources from the RM for the app master // Memory ask has to be a multiple of min and less than max. // Dump out information about cluster capability as seen by the resource manager int minMem = newApp.getMinimumResourceCapability().getMemory(); int maxMem = newApp.getMaximumResourceCapability().getMemory(); LOG.info("Min mem capabililty of resources in this cluster " + minMem); LOG.info("Max mem capabililty of resources in this cluster " + maxMem); // A resource ask has to be at least the minimum of the capability of the cluster, // the value has to be a multiple of the min value and cannot exceed the max. // If it is not an exact multiple of min, the RM will allocate to the nearest multiple of min if (amMemory < minMem) { LOG.info("AM memory specified below min threshold of cluster. Using min value." + ", specified=" + amMemory + ", min=" + minMem); amMemory = minMem; } else if (amMemory > maxMem) { LOG.info("AM memory specified above max threshold of cluster. Using max value." + ", specified=" + amMemory + ", max=" + maxMem); amMemory = maxMem; } // Create launch context for app master LOG.info("Setting up application submission context for ASM"); ApplicationSubmissionContext appContext = Records.newRecord(ApplicationSubmissionContext.class); // set the application id LOG.info("Set Application Id: " + appId); appContext.setApplicationId(appId); // set the application name LOG.info("Set Application Name: " + appName); appContext.setApplicationName(appName); // Set up the container launch context for the application master ContainerLaunchContext amContainer = Records.newRecord(ContainerLaunchContext.class); LOG.info("Copy App Master jar from local filesystem and add to local environment"); // Copy the application master jar to the filesystem // Create a local resource to point to the destination jar path FileSystem fs = FileSystem.get(conf); Path appJarSrc = new Path(appMasterJar); LOG.info("Source path: " + appJarSrc.toString()); String pathSuffix = appName + "/" + appId.getId() + "/AppMaster.jar"; Path appJarDst = new Path(fs.getHomeDirectory(), pathSuffix); LOG.info("Destination path: " + appJarDst.toString()); fs.copyFromLocalFile(false, true, appJarSrc, appJarDst); FileStatus appJarDestStatus = fs.getFileStatus(appJarDst); // set local resources for the application master Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); LocalResource amJarRsrc = Records.newRecord(LocalResource.class); amJarRsrc.setType(LocalResourceType.FILE); amJarRsrc.setVisibility(LocalResourceVisibility.APPLICATION); // Set the resource to be copied over amJarRsrc.setResource(ConverterUtils.getYarnUrlFromPath(appJarDst)); // Set timestamp and length of file so that the framework can do basic sanity // checks for the local resource after it has been copied over to ensure // it is the same resource the client intended to use with the application amJarRsrc.setTimestamp(appJarDestStatus.getModificationTime()); amJarRsrc.setSize(appJarDestStatus.getLen()); localResources.put("AppMaster.jar", amJarRsrc); // Set local resource info into app master container launch context amContainer.setLocalResources(localResources); LOG.info("Copy MPI application from local filesystem to remote."); assert(!mpiApplication.isEmpty()); Path mpiAppSrc = new Path(mpiApplication); String mpiAppSuffix = appName + "/" + appId.getId() + "/MPIExec"; Path mpiAppDst = new Path(fs.getHomeDirectory(), mpiAppSuffix); fs.copyFromLocalFile(false, true, mpiAppSrc, mpiAppDst); FileStatus mpiAppFileStatus = fs.getFileStatus(mpiAppDst); // Set the env variables to be setup in the env where the application master will be run LOG.info("Set the environment for the application master and mpi application"); Map<String, String> env = new HashMap<String, String>(); // put location of mpi app and appmaster.jar into env // using the env info, the application master will create the correct local resource for the // eventual containers that will be launched to execute the shell scripts env.put(MPIConstants.MPIEXECLOCATION, mpiAppDst.toUri().toString()); env.put(MPIConstants.MPIEXECTIMESTAMP, Long.toString(mpiAppFileStatus.getModificationTime())); env.put(MPIConstants.MPIEXECLEN, Long.toString(mpiAppFileStatus.getLen())); env.put(MPIConstants.APPJARLOCATION, appJarDst.toUri().toString()); env.put(MPIConstants.APPJARTIMESTAMP, Long.toString(appJarDestStatus.getModificationTime())); env.put(MPIConstants.APPJARLEN, Long.toString(appJarDestStatus.getLen())); if (!mpiOptions.isEmpty()) { env.put(MPIConstants.MPIOPTIONS, mpiOptions); } // Add AppMaster.jar location to classpath. At some point we should not be // required to add the hadoop specific classpaths to the env. It should be // provided out of the box. For now setting all required classpaths including // the classpath to "." for the application jar StringBuilder classPathEnv = new StringBuilder("${CLASSPATH}:./*"); for (String c : conf.getStrings( MPIConfiguration.YARN_APPLICATION_CLASSPATH, MPIConfiguration.DEFAULT_MPI_APPLICATION_CLASSPATH)) { classPathEnv.append(':'); classPathEnv.append(c.trim()); } // add the runtime classpath needed for tests to work String testRuntimeClassPath = Client.getTestRuntimeClasspath(); classPathEnv.append(':'); classPathEnv.append(testRuntimeClassPath); env.put("CLASSPATH", classPathEnv.toString()); amContainer.setEnvironment(env); // Set the necessary command to execute the application master Vector<CharSequence> vargs = new Vector<CharSequence>(30); // Set java executable command LOG.info("Setting up app master command"); vargs.add("${JAVA_HOME}" + "/bin/java"); // Set Xmx based on am memory size vargs.add("-Xmx" + amMemory + "m"); // Set class name vargs.add("com.taobao.yarn.mpi.server.ApplicationMaster"); // Set params for Application Master vargs.add("--container_memory " + String.valueOf(containerMemory)); vargs.add("--num_containers " + String.valueOf(numContainers)); vargs.add("--priority " + String.valueOf(containerPriority)); if (debugFlag) { vargs.add("--debug"); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stdout"); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stderr"); // Get final commmand StringBuilder command = new StringBuilder(); for (CharSequence str : vargs) { command.append(str).append(" "); } LOG.info("Completed setting up app master command " + command.toString()); List<String> commands = new ArrayList<String>(); commands.add(command.toString()); amContainer.setCommands(commands); // Set up resource type requirements // For now, only memory is supported so we set memory requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory(amMemory); amContainer.setResource(capability); appContext.setAMContainerSpec(amContainer); // Set the priority for the application master Priority pri = Records.newRecord(Priority.class); // TODO - what is the range for priority? how to decide? pri.setPriority(amPriority); appContext.setPriority(pri); // Set the queue to which this application is to be submitted in the RM appContext.setQueue(amQueue); // Create the request to send to the applications manager SubmitApplicationRequest appRequest = Records.newRecord(SubmitApplicationRequest.class); appRequest.setApplicationSubmissionContext(appContext); // Submit the application to the applications manager // Ignore the response as either a valid response object is returned on success // or an exception thrown to denote some form of a failure LOG.info("Submitting application to ASM"); isRunnig = true; SubmitApplicationResponse submitResp = applicationsManager.submitApplication(appRequest); LOG.info("Submisstion result: " + submitResp.toString()); // TODO Try submitting the same request again. app submission failure? // Monitor the application return monitorApplication(); }
public boolean run() throws IOException { LOG.info("Starting Client"); // Connect to ResourceManager connectToASM(); assert(applicationsManager != null); // Get a new application id GetNewApplicationResponse newApp = getApplication(); appId = newApp.getApplicationId(); LOG.info("Got Applicatioin: " + appId.toString()); // TODO get min/max resource capabilities from RM and change memory ask if needed // If we do not have min/max, we may not be able to correctly request // the required resources from the RM for the app master // Memory ask has to be a multiple of min and less than max. // Dump out information about cluster capability as seen by the resource manager int minMem = newApp.getMinimumResourceCapability().getMemory(); int maxMem = newApp.getMaximumResourceCapability().getMemory(); LOG.info("Min mem capabililty of resources in this cluster " + minMem); LOG.info("Max mem capabililty of resources in this cluster " + maxMem); // A resource ask has to be at least the minimum of the capability of the cluster, // the value has to be a multiple of the min value and cannot exceed the max. // If it is not an exact multiple of min, the RM will allocate to the nearest multiple of min if (amMemory < minMem) { LOG.info("AM memory specified below min threshold of cluster. Using min value." + ", specified=" + amMemory + ", min=" + minMem); amMemory = minMem; } else if (amMemory > maxMem) { LOG.info("AM memory specified above max threshold of cluster. Using max value." + ", specified=" + amMemory + ", max=" + maxMem); amMemory = maxMem; } if (containerMemory * numContainers > maxMem) { LOG.error("Container memories specified above the max threhold " +"(yarn.scheduler.maximum-allocation-mb) of the cluster"); return false; } // Create launch context for app master LOG.info("Setting up application submission context for ASM"); ApplicationSubmissionContext appContext = Records.newRecord(ApplicationSubmissionContext.class); // set the application id LOG.info("Set Application Id: " + appId); appContext.setApplicationId(appId); // set the application name LOG.info("Set Application Name: " + appName); appContext.setApplicationName(appName); // Set up the container launch context for the application master ContainerLaunchContext amContainer = Records.newRecord(ContainerLaunchContext.class); LOG.info("Copy App Master jar from local filesystem and add to local environment"); // Copy the application master jar to the filesystem // Create a local resource to point to the destination jar path FileSystem fs = FileSystem.get(conf); Path appJarSrc = new Path(appMasterJar); LOG.info("Source path: " + appJarSrc.toString()); String pathSuffix = appName + "/" + appId.getId() + "/AppMaster.jar"; Path appJarDst = new Path(fs.getHomeDirectory(), pathSuffix); LOG.info("Destination path: " + appJarDst.toString()); fs.copyFromLocalFile(false, true, appJarSrc, appJarDst); FileStatus appJarDestStatus = fs.getFileStatus(appJarDst); // set local resources for the application master Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); LocalResource amJarRsrc = Records.newRecord(LocalResource.class); amJarRsrc.setType(LocalResourceType.FILE); amJarRsrc.setVisibility(LocalResourceVisibility.APPLICATION); // Set the resource to be copied over amJarRsrc.setResource(ConverterUtils.getYarnUrlFromPath(appJarDst)); // Set timestamp and length of file so that the framework can do basic sanity // checks for the local resource after it has been copied over to ensure // it is the same resource the client intended to use with the application amJarRsrc.setTimestamp(appJarDestStatus.getModificationTime()); amJarRsrc.setSize(appJarDestStatus.getLen()); localResources.put("AppMaster.jar", amJarRsrc); // Set local resource info into app master container launch context amContainer.setLocalResources(localResources); LOG.info("Copy MPI application from local filesystem to remote."); assert(!mpiApplication.isEmpty()); Path mpiAppSrc = new Path(mpiApplication); String mpiAppSuffix = appName + "/" + appId.getId() + "/MPIExec"; Path mpiAppDst = new Path(fs.getHomeDirectory(), mpiAppSuffix); fs.copyFromLocalFile(false, true, mpiAppSrc, mpiAppDst); FileStatus mpiAppFileStatus = fs.getFileStatus(mpiAppDst); // Set the env variables to be setup in the env where the application master will be run LOG.info("Set the environment for the application master and mpi application"); Map<String, String> env = new HashMap<String, String>(); // put location of mpi app and appmaster.jar into env // using the env info, the application master will create the correct local resource for the // eventual containers that will be launched to execute the shell scripts env.put(MPIConstants.MPIEXECLOCATION, mpiAppDst.toUri().toString()); env.put(MPIConstants.MPIEXECTIMESTAMP, Long.toString(mpiAppFileStatus.getModificationTime())); env.put(MPIConstants.MPIEXECLEN, Long.toString(mpiAppFileStatus.getLen())); env.put(MPIConstants.APPJARLOCATION, appJarDst.toUri().toString()); env.put(MPIConstants.APPJARTIMESTAMP, Long.toString(appJarDestStatus.getModificationTime())); env.put(MPIConstants.APPJARLEN, Long.toString(appJarDestStatus.getLen())); if (!mpiOptions.isEmpty()) { env.put(MPIConstants.MPIOPTIONS, mpiOptions); } // Add AppMaster.jar location to classpath. At some point we should not be // required to add the hadoop specific classpaths to the env. It should be // provided out of the box. For now setting all required classpaths including // the classpath to "." for the application jar StringBuilder classPathEnv = new StringBuilder("${CLASSPATH}:./*"); for (String c : conf.getStrings( MPIConfiguration.YARN_APPLICATION_CLASSPATH, MPIConfiguration.DEFAULT_MPI_APPLICATION_CLASSPATH)) { classPathEnv.append(':'); classPathEnv.append(c.trim()); } // add the runtime classpath needed for tests to work String testRuntimeClassPath = Client.getTestRuntimeClasspath(); classPathEnv.append(':'); classPathEnv.append(testRuntimeClassPath); env.put("CLASSPATH", classPathEnv.toString()); amContainer.setEnvironment(env); // Set the necessary command to execute the application master Vector<CharSequence> vargs = new Vector<CharSequence>(30); // Set java executable command LOG.info("Setting up app master command"); vargs.add("${JAVA_HOME}" + "/bin/java"); // Set Xmx based on am memory size vargs.add("-Xmx" + amMemory + "m"); // Set class name vargs.add("com.taobao.yarn.mpi.server.ApplicationMaster"); // Set params for Application Master vargs.add("--container_memory " + String.valueOf(containerMemory)); vargs.add("--num_containers " + String.valueOf(numContainers)); vargs.add("--priority " + String.valueOf(containerPriority)); if (debugFlag) { vargs.add("--debug"); } vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stdout"); vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stderr"); // Get final commmand StringBuilder command = new StringBuilder(); for (CharSequence str : vargs) { command.append(str).append(" "); } LOG.info("Completed setting up app master command " + command.toString()); List<String> commands = new ArrayList<String>(); commands.add(command.toString()); amContainer.setCommands(commands); // Set up resource type requirements // For now, only memory is supported so we set memory requirements Resource capability = Records.newRecord(Resource.class); capability.setMemory(amMemory); amContainer.setResource(capability); appContext.setAMContainerSpec(amContainer); // Set the priority for the application master Priority pri = Records.newRecord(Priority.class); // TODO - what is the range for priority? how to decide? pri.setPriority(amPriority); appContext.setPriority(pri); // Set the queue to which this application is to be submitted in the RM appContext.setQueue(amQueue); // Create the request to send to the applications manager SubmitApplicationRequest appRequest = Records.newRecord(SubmitApplicationRequest.class); appRequest.setApplicationSubmissionContext(appContext); // Submit the application to the applications manager // Ignore the response as either a valid response object is returned on success // or an exception thrown to denote some form of a failure LOG.info("Submitting application to ASM"); isRunnig = true; SubmitApplicationResponse submitResp = applicationsManager.submitApplication(appRequest); LOG.info("Submisstion result: " + submitResp.toString()); // TODO Try submitting the same request again. app submission failure? // Monitor the application return monitorApplication(); }
diff --git a/projects/security-manager/source/javatests/com/google/enterprise/saml/server/MockBackEnd.java b/projects/security-manager/source/javatests/com/google/enterprise/saml/server/MockBackEnd.java index fd12ac77..15f48ad9 100644 --- a/projects/security-manager/source/javatests/com/google/enterprise/saml/server/MockBackEnd.java +++ b/projects/security-manager/source/javatests/com/google/enterprise/saml/server/MockBackEnd.java @@ -1,70 +1,71 @@ // Copyright (C) 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.enterprise.saml.server; import com.google.enterprise.sessionmanager.SessionManagerInterface; import org.opensaml.common.binding.artifact.SAMLArtifactMap; import org.opensaml.saml2.core.ArtifactResolve; import org.opensaml.saml2.core.ArtifactResponse; import org.opensaml.saml2.core.AuthnRequest; import org.opensaml.saml2.core.AuthzDecisionQuery; import org.opensaml.saml2.core.Response; import java.util.List; /** * Simple mock saml server Backend for testing. */ public class MockBackEnd implements BackEnd { private final SessionManagerInterface sessionManager; private ArtifactResolver artifactResolver; private AuthzResponder authzResponder; - public MockBackEnd(SessionManagerInterface sm, ArtifactResolver artifactResolver, AuthzResponder authzResponder) { + public MockBackEnd(SessionManagerInterface sm, ArtifactResolver artifactResolver, + AuthzResponder authzResponder) { this.sessionManager = sm; this.artifactResolver = artifactResolver; this.authzResponder = authzResponder; } public SessionManagerInterface getSessionManager() { return sessionManager; } public ArtifactResolver getArtifactResolver() { return artifactResolver; } public AuthzResponder getAuthzResponder() { return authzResponder; } public SAMLArtifactMap getArtifactMap() { throw new UnsupportedOperationException("Unimplemented method."); } public Response validateCredentials(AuthnRequest request, String username, String password) { throw new UnsupportedOperationException("Unimplemented method."); } public ArtifactResponse resolveArtifact(ArtifactResolve artifactResolve) { throw new UnsupportedOperationException("Unimplemented method."); } public List<Response> authorize(List<AuthzDecisionQuery> authzDecisionQueries) { throw new UnsupportedOperationException("Unimplemented method."); } }
true
true
public MockBackEnd(SessionManagerInterface sm, ArtifactResolver artifactResolver, AuthzResponder authzResponder) { this.sessionManager = sm; this.artifactResolver = artifactResolver; this.authzResponder = authzResponder; }
public MockBackEnd(SessionManagerInterface sm, ArtifactResolver artifactResolver, AuthzResponder authzResponder) { this.sessionManager = sm; this.artifactResolver = artifactResolver; this.authzResponder = authzResponder; }
diff --git a/api/src/test/java/org/mifos/accounts/api/AccountPaymentParametersDtoTest.java b/api/src/test/java/org/mifos/accounts/api/AccountPaymentParametersDtoTest.java index 684cb9d85..175c13783 100644 --- a/api/src/test/java/org/mifos/accounts/api/AccountPaymentParametersDtoTest.java +++ b/api/src/test/java/org/mifos/accounts/api/AccountPaymentParametersDtoTest.java @@ -1,76 +1,76 @@ /* * 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.accounts.api; import java.math.BigDecimal; import org.joda.time.LocalDate; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class AccountPaymentParametersDtoTest { UserReferenceDto user = new UserReferenceDto((short) -1); AccountReferenceDto account = new AccountReferenceDto(-1); BigDecimal paymentAmount = new BigDecimal("0.0"); LocalDate paymentDate = new LocalDate(1990, 1, 1); @Mock PaymentTypeDto paymentType; String emptyComment = ""; @Test(expected = IllegalArgumentException.class) public void userMakingPaymentCannotBeNull() { new AccountPaymentParametersDto(null, account, paymentAmount, paymentDate, paymentType, emptyComment); } @Test(expected = IllegalArgumentException.class) public void accountCannotBeNull() { new AccountPaymentParametersDto(user, null, paymentAmount, paymentDate, paymentType, emptyComment); } @Test(expected = IllegalArgumentException.class) public void paymentAmountCannotBeNull() { new AccountPaymentParametersDto(user, account, null, paymentDate, paymentType, emptyComment); } @Test(expected = IllegalArgumentException.class) public void paymentDateCannotBeNull() { new AccountPaymentParametersDto(user, account, paymentAmount, null, paymentType, emptyComment); } @Test(expected = IllegalArgumentException.class) public void paymentTypeCannotBeNull() { new AccountPaymentParametersDto(user, account, paymentAmount, paymentDate, null, emptyComment); } @Test(expected = IllegalArgumentException.class) public void commentCannotBeNull() { new AccountPaymentParametersDto(user, account, paymentAmount, paymentDate, paymentType, null); } @Test public void receiptDateAndReceiptIdCanBeNull() { new AccountPaymentParametersDto(user, account, paymentAmount, paymentDate, paymentType, emptyComment, null, - null); + null, null); } }
true
true
public void receiptDateAndReceiptIdCanBeNull() { new AccountPaymentParametersDto(user, account, paymentAmount, paymentDate, paymentType, emptyComment, null, null); }
public void receiptDateAndReceiptIdCanBeNull() { new AccountPaymentParametersDto(user, account, paymentAmount, paymentDate, paymentType, emptyComment, null, null, null); }
diff --git a/src/main/java/org/spout/vanilla/controller/living/creature/passive/Sheep.java b/src/main/java/org/spout/vanilla/controller/living/creature/passive/Sheep.java index 14c7a345..57bf59c8 100644 --- a/src/main/java/org/spout/vanilla/controller/living/creature/passive/Sheep.java +++ b/src/main/java/org/spout/vanilla/controller/living/creature/passive/Sheep.java @@ -1,115 +1,115 @@ /* * This file is part of Vanilla (http://www.spout.org/). * * Vanilla is licensed under the SpoutDev License Version 1. * * Vanilla is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * In addition, 180 days after any changes are published, you can use the * software, incorporating those changes, under the terms of the MIT license, * as described in the SpoutDev License Version 1. * * Vanilla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License, * the MIT license and the SpoutDev License Version 1 along with this program. * If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public * License and see <http://www.spout.org/SpoutDevLicenseV1.txt> for the full license, * including the MIT license. */ package org.spout.vanilla.controller.living.creature.passive; import java.util.HashSet; import java.util.Set; import org.spout.api.inventory.ItemStack; import org.spout.api.protocol.EntityProtocol; import org.spout.api.protocol.EntityProtocolStore; import org.spout.vanilla.VanillaMaterials; import org.spout.vanilla.controller.ControllerType; import org.spout.vanilla.controller.living.Creature; import org.spout.vanilla.controller.living.creature.Passive; import org.spout.vanilla.material.block.Wool; public class Sheep extends Creature implements Passive { private int countdown = 0; private int color; private static EntityProtocolStore entityProtocolStore = new EntityProtocolStore(); public Sheep() { this(0x0); } public Sheep(Wool.WoolColor color) { this(color.getData()); } public Sheep(int color) { super(); this.color = color; } @Override public void onAttached() { super.onAttached(); getParent().setData(ControllerType.KEY, ControllerType.Sheep.id); getParent().setData("SheepSheared", false); getParent().setData("SheepColor", color); } @Override public void onTick(float dt) { if (--countdown <= 0) { countdown = getRandom().nextInt(7) + 3; float x = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); float y = getRandom().nextFloat(); float z = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); - //getParent().translate(x, y, z); + getParent().translate(x, y, z); } super.onTick(dt); } @Override public EntityProtocol getEntityProtocol(int protocolId) { return entityProtocolStore.getEntityProtocol(protocolId); } public static void setEntityProtocol(int protocolId, EntityProtocol protocol) { entityProtocolStore.setEntityProtocol(protocolId, protocol); } public boolean isSheared() { return getParent().getData("SheepSheared").asBool(); } public void setSheared(boolean sheared) { getParent().setData("SheepSheared", sheared); } public int getColor() { return getParent().getData("SheepColor").asInt(); } public void setColor() { getParent().setData("SheepColor", getRandom()); } @Override public Set<ItemStack> getDeathDrops() { Set<ItemStack> drops = new HashSet<ItemStack>(); if (!isSheared()) { drops.add(new ItemStack(VanillaMaterials.WOOL.getSubMaterial((short) color), 1)); } return drops; } }
true
true
public void onTick(float dt) { if (--countdown <= 0) { countdown = getRandom().nextInt(7) + 3; float x = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); float y = getRandom().nextFloat(); float z = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); //getParent().translate(x, y, z); } super.onTick(dt); }
public void onTick(float dt) { if (--countdown <= 0) { countdown = getRandom().nextInt(7) + 3; float x = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); float y = getRandom().nextFloat(); float z = (getRandom().nextBoolean() ? 1 : -1) * getRandom().nextFloat(); getParent().translate(x, y, z); } super.onTick(dt); }
diff --git a/src/com/redhat/qe/sm/cli/tests/ComplianceTests.java b/src/com/redhat/qe/sm/cli/tests/ComplianceTests.java index feeb7f48..651611da 100644 --- a/src/com/redhat/qe/sm/cli/tests/ComplianceTests.java +++ b/src/com/redhat/qe/sm/cli/tests/ComplianceTests.java @@ -1,296 +1,297 @@ package com.redhat.qe.sm.cli.tests; import java.io.File; import java.util.List; import org.testng.SkipException; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; import com.redhat.qe.auto.testng.Assert; import com.redhat.qe.auto.testng.LogMessageUtil; import com.redhat.qe.sm.base.SubscriptionManagerCLITestScript; import com.redhat.qe.sm.data.EntitlementCert; import com.redhat.qe.sm.data.InstalledProduct; import com.redhat.qe.sm.data.ProductCert; import com.redhat.qe.sm.data.ProductNamespace; import com.redhat.qe.tools.RemoteFileTasks; import com.redhat.qe.tools.SSHCommandResult; /** * @author jsefler * * */ @Test(groups={"ComplianceTests","AcceptanceTests"}) public class ComplianceTests extends SubscriptionManagerCLITestScript{ // Test Methods *********************************************************************** @Test( description="subscription-manager: verify the system.compliant fact is False when some installed products are subscribable", groups={"configureProductCertDirForSomeProductsSubscribable","cli.tests"}, enabled=true) //@ImplementsTCMS(id="") public void VerifySystemCompliantFactWhenSomeProductsAreSubscribable() { clienttasks.register(sm_clientUsername,sm_clientPassword,sm_clientOrg,null,null,null,null,null,nullString,Boolean.TRUE,null, null, null); List<InstalledProduct> installdProducts = clienttasks.getCurrentlyInstalledProducts(); Assert.assertFalse(installdProducts.isEmpty(), "Products are currently installed for which the compliance of only SOME are covered by currently available subscription pools."); Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance).toLowerCase(), Boolean.FALSE.toString(), "Before attempting to subscribe and become compliant for all the currently installed products, the system should be incompliant."); clienttasks.subscribeToAllOfTheCurrentlyAvailableSubscriptionPools(); clienttasks.listInstalledProducts(); Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance).toLowerCase(), Boolean.FALSE.toString(), "When a system has products installed for which only SOME are covered by available subscription pools, the system should NOT become compliant even after having subscribed to every available subscription pool."); } @Test( description="rhsm-complianced: verify rhsm-complianced -d -s reports an incompliant status when some installed products are subscribable", groups={"blockedbyBug-723336","blockedbyBug-691480","cli.tests"}, dependsOnMethods={"VerifySystemCompliantFactWhenSomeProductsAreSubscribable"}, enabled=true) //@ImplementsTCMS(id="") public void VerifyRhsmCompliancedWhenSomeProductsAreSubscribable() { String command = clienttasks.rhsmComplianceD+" -s -d"; RemoteFileTasks.runCommandAndWait(client, "echo 'Testing "+command+"' >> "+clienttasks.varLogMessagesFile, LogMessageUtil.action()); // verify the stdout message RemoteFileTasks.runCommandAndAssert(client, command, Integer.valueOf(0), rhsmComplianceDStdoutMessageWhenIncompliant, null); // also verify the /var/syslog/messages RemoteFileTasks.runCommandAndAssert(client,"tail -1 "+clienttasks.varLogMessagesFile, null, rhsmComplianceDSyslogMessageWhenIncompliant, null); } @Test( description="subscription-manager: verify the system.compliant fact is True when all installed products are subscribable", groups={"configureProductCertDirForAllProductsSubscribable","cli.tests"}, enabled=true) //@ImplementsTCMS(id="") public void VerifySystemCompliantFactWhenAllProductsAreSubscribable() { clienttasks.register(sm_clientUsername,sm_clientPassword,sm_clientOrg,null,null,null,null,null,nullString,Boolean.TRUE,null, null, null); List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts(); Assert.assertFalse(installedProducts.isEmpty(), "Products are currently installed for which the compliance of ALL are covered by currently available subscription pools."); Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance).toLowerCase(), Boolean.FALSE.toString(), "Before attempting to subscribe and become compliant for all the currently installed products, the system should be incompliant."); clienttasks.subscribeToAllOfTheCurrentlyAvailableSubscriptionPools(); clienttasks.listInstalledProducts(); Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance).toLowerCase(), Boolean.TRUE.toString(), "When a system has products installed for which ALL are covered by available subscription pools, the system should become compliant after having subscribed to every available subscription pool."); } @Test( description="rhsm-complianced: verify rhsm-complianced -d -s reports a compliant status when all installed products are subscribable", groups={"blockedbyBug-723336","cli.tests"}, dependsOnMethods={"VerifySystemCompliantFactWhenAllProductsAreSubscribable"}, enabled=true) //@ImplementsTCMS(id="") public void VerifyRhsmCompliancedWhenAllProductsAreSubscribable() { String command = clienttasks.rhsmComplianceD+" -s -d"; // verify the stdout message RemoteFileTasks.runCommandAndAssert(client, command, Integer.valueOf(0), rhsmComplianceDStdoutMessageWhenCompliant, null); } @Test( description="subscription-manager: verify the system.compliant fact is False when no installed products are subscribable", groups={"configureProductCertDirForNoProductsSubscribable","cli.tests"}, enabled=true) //@ImplementsTCMS(id="") public void VerifySystemCompliantFactWhenNoProductsAreSubscribable() { clienttasks.register(sm_clientUsername,sm_clientPassword,sm_clientOrg,null,null,null,null,null,nullString,Boolean.TRUE,null, null, null); List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts(); Assert.assertFalse(installedProducts.isEmpty(), "Products are currently installed for which the compliance of NONE are covered by currently available subscription pools."); Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance).toLowerCase(), Boolean.FALSE.toString(), "Before attempting to subscribe and become compliant for all the currently installed products, the system should be incompliant."); clienttasks.subscribeToAllOfTheCurrentlyAvailableSubscriptionPools(); clienttasks.listInstalledProducts(); Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance).toLowerCase(), Boolean.FALSE.toString(), "When a system has products installed for which NONE are covered by available subscription pools, the system should NOT become compliant after having subscribed to every available subscription pool."); } @Test( description="rhsm-complianced: verify rhsm-complianced -d -s reports an incompliant status when no installed products are subscribable", groups={"blockedbyBug-723336","blockedbyBug-691480","cli.tests"}, dependsOnMethods={"VerifySystemCompliantFactWhenNoProductsAreSubscribable"}, enabled=true) //@ImplementsTCMS(id="") public void VerifyRhsmCompliancedWhenNoProductsAreSubscribable() { String command = clienttasks.rhsmComplianceD+" -s -d"; RemoteFileTasks.runCommandAndWait(client, "echo 'Testing "+command+"' >> "+clienttasks.varLogMessagesFile, LogMessageUtil.action()); // verify the stdout message RemoteFileTasks.runCommandAndAssert(client, command, Integer.valueOf(0), rhsmComplianceDStdoutMessageWhenIncompliant, null); // also verify the /var/syslog/messages RemoteFileTasks.runCommandAndAssert(client,"tail -1 "+clienttasks.varLogMessagesFile, null, rhsmComplianceDSyslogMessageWhenIncompliant, null); } @Test( description="subscription-manager: verify the system.compliant fact is True when no products are installed", groups={"configureProductCertDirForNoProductsInstalled","cli.tests"}, enabled=true) //@ImplementsTCMS(id="") public void VerifySystemCompliantFactWhenNoProductsAreInstalled() { clienttasks.register(sm_clientUsername,sm_clientPassword,sm_clientOrg,null,null,null,null,null,nullString,Boolean.TRUE,null, null, null); List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts(); Assert.assertTrue(installedProducts.isEmpty(), "No products are currently installed."); Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance).toLowerCase(), Boolean.TRUE.toString(), "Because no prodycts are currently installed, the system should inherently be compliant even without subscribing to any subscription pools."); clienttasks.subscribeToAllOfTheCurrentlyAvailableSubscriptionPools(); clienttasks.listInstalledProducts(); Assert.assertEquals(clienttasks.getFactValue(factNameForSystemCompliance).toLowerCase(), Boolean.TRUE.toString(), "Even after subscribing to all the available subscription pools, a system with no products installed should remain compliant."); } @Test( description="rhsm-complianced: verify rhsm-complianced -d -s reports a compliant status when no products are installed", groups={"blockedbyBug-723336","cli.tests"}, dependsOnMethods={"VerifySystemCompliantFactWhenNoProductsAreInstalled"}, enabled=true) //@ImplementsTCMS(id="") public void VerifyRhsmCompliancedWhenNoProductsAreInstalled() { String command = clienttasks.rhsmComplianceD+" -s -d"; // verify the stdout message RemoteFileTasks.runCommandAndAssert(client, command, Integer.valueOf(0), rhsmComplianceDStdoutMessageWhenCompliant, null); } // Candidates for an automated Test: // TODO https://bugzilla.redhat.com/show_bug.cgi?id=649068 future subscription compliance test // Protected Class Variables *********************************************************************** protected final String productCertDirForSomeProductsSubscribable = "/tmp/sm-someProductsSubscribable"; protected final String productCertDirForAllProductsSubscribable = "/tmp/sm-allProductsSubscribable"; protected final String productCertDirForNoProductsSubscribable = "/tmp/sm-noProductsSubscribable"; protected final String productCertDirForNoProductsinstalled = "/tmp/sm-noProductsInstalled"; protected String productCertDir = null; protected final String factNameForSystemCompliance = "system.entitlements_valid"; // "system.compliant"; // changed with the removal of the word "compliance" 3/30/2011 protected final String rhsmComplianceDStdoutMessageWhenIncompliant = "System has one or more certificates that are not valid"; protected final String rhsmComplianceDStdoutMessageWhenCompliant = "System entitlements appear valid"; protected final String rhsmComplianceDSyslogMessageWhenIncompliant = "This system is missing one or more valid entitlement certificates. Please run subscription-manager for more information."; // Protected Methods *********************************************************************** // Configuration Methods *********************************************************************** @BeforeClass(groups={"setup"}) public void setupProductCertDirsBeforeClass() { // clean out the productCertDirs for (String productCertDir : new String[]{productCertDirForSomeProductsSubscribable,productCertDirForAllProductsSubscribable,productCertDirForNoProductsSubscribable,productCertDirForNoProductsinstalled}) { RemoteFileTasks.runCommandAndAssert(client, "rm -rf "+productCertDir, 0); RemoteFileTasks.runCommandAndAssert(client, "mkdir "+productCertDir, 0); } // autosubscribe + clienttasks.unregister(null,null,null); // avoid Bug 733525 - [Errno 2] No such file or directory: '/etc/pki/entitlement' clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, Boolean.TRUE, nullString, Boolean.TRUE, null, null, null); // // distribute a copy of the product certs amongst the productCertDirs // List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts(); // for (File productCertFile : clienttasks.getCurrentProductCertFiles()) { // ProductCert productCert = clienttasks.getProductCertFromProductCertFile(productCertFile); // // TODO WORKAROUND NEEDED FOR Bug 733805 - the name in the subscription-manager installed product listing is changing after a valid subscribe is performed (https://bugzilla.redhat.com/show_bug.cgi?id=733805) // InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productName", productCert.productName, installedProducts); // if (installedProduct.status.equalsIgnoreCase("Not Subscribed")) { // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForNoProductsSubscribable, 0); // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); // } else if (installedProduct.status.equalsIgnoreCase("Subscribed")) { // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForAllProductsSubscribable, 0); // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); // } // } // distribute a copy of the product certs amongst the productCertDirs List<EntitlementCert> entitlementCerts = clienttasks.getCurrentEntitlementCerts(); for (File productCertFile : clienttasks.getCurrentProductCertFiles()) { ProductCert productCert = clienttasks.getProductCertFromProductCertFile(productCertFile); // WORKAROUND NEEDED FOR Bug 733805 - the name in the subscription-manager installed product listing is changing after a valid subscribe is performed (https://bugzilla.redhat.com/show_bug.cgi?id=733805) List<EntitlementCert> correspondingEntitlementCerts = clienttasks.getEntitlementCertsCorrespondingToProductCert(productCert); if (correspondingEntitlementCerts.isEmpty()) { // "Not Subscribed" case... RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForNoProductsSubscribable, 0); RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); } else { // "Subscribed" case... RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForAllProductsSubscribable, 0); RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); } // TODO "Partially Subscribed" case //InstalledProduct installedProduct = clienttasks.getInstalledProductCorrespondingToEntitlementCert(correspondingEntitlementCert); } this.productCertDir = clienttasks.productCertDir; } @AfterClass(groups={"setup"},alwaysRun=true) public void configureProductCertDirAfterClass() { if (clienttasks==null) return; if (this.productCertDir!=null) clienttasks.updateConfFileParameter(clienttasks.rhsmConfFile, "productCertDir", this.productCertDir); } @BeforeGroups(groups={"setup"},value="configureProductCertDirForSomeProductsSubscribable") protected void configureProductCertDirForSomeProductsSubscribable() { clienttasks.unregister(null, null, null); clienttasks.updateConfFileParameter(clienttasks.rhsmConfFile, "productCertDir",productCertDirForSomeProductsSubscribable); SSHCommandResult r0 = client.runCommandAndWait("ls -1 "+productCertDirForSomeProductsSubscribable+" | wc -l"); SSHCommandResult r1 = client.runCommandAndWait("ls -1 "+productCertDirForAllProductsSubscribable+" | wc -l"); SSHCommandResult r2 = client.runCommandAndWait("ls -1 "+productCertDirForNoProductsSubscribable+" | wc -l"); if (Integer.valueOf(r1.getStdout().trim())==0) throw new SkipException("Could not find any installed product certs that are subscribable based on the currently available subscriptions."); if (Integer.valueOf(r2.getStdout().trim())==0) throw new SkipException("Could not find any installed product certs that are non-subscribable based on the currently available subscriptions."); Assert.assertTrue(Integer.valueOf(r0.getStdout().trim())>0 && Integer.valueOf(r1.getStdout().trim())>0 && Integer.valueOf(r2.getStdout().trim())>0, "The "+clienttasks.rhsmConfFile+" file is currently configured with a productCertDir that contains some subscribable products based on the currently available subscriptions."); } @BeforeGroups(groups={"setup"},value="configureProductCertDirForAllProductsSubscribable") protected void configureProductCertDirForAllProductsSubscribable() { clienttasks.unregister(null, null, null); clienttasks.updateConfFileParameter(clienttasks.rhsmConfFile, "productCertDir",productCertDirForAllProductsSubscribable); SSHCommandResult r = client.runCommandAndWait("ls -1 "+productCertDirForAllProductsSubscribable+" | wc -l"); if (Integer.valueOf(r.getStdout().trim())==0) throw new SkipException("Could not find any installed product certs that are subscribable based on the currently available subscriptions."); Assert.assertTrue(Integer.valueOf(r.getStdout().trim())>0, "The "+clienttasks.rhsmConfFile+" file is currently configured with a productCertDir that contains all subscribable products based on the currently available subscriptions."); } @BeforeGroups(groups={"setup"},value="configureProductCertDirForNoProductsSubscribable") protected void configureProductCertDirForNoProductsSubscribable() { clienttasks.unregister(null, null, null); clienttasks.updateConfFileParameter(clienttasks.rhsmConfFile, "productCertDir",productCertDirForNoProductsSubscribable); SSHCommandResult r = client.runCommandAndWait("ls -1 "+productCertDirForNoProductsSubscribable+" | wc -l"); if (Integer.valueOf(r.getStdout().trim())==0) throw new SkipException("Could not find any installed product certs that are non-subscribable based on the currently available subscriptions."); Assert.assertTrue(Integer.valueOf(r.getStdout().trim())>0, "The "+clienttasks.rhsmConfFile+" file is currently configured with a productCertDir that contains all non-subscribable products based on the currently available subscriptions."); } @BeforeGroups(groups={"setup"},value="configureProductCertDirForNoProductsInstalled") protected void configureProductCertDirForNoProductsInstalled() { clienttasks.unregister(null, null, null); clienttasks.updateConfFileParameter(clienttasks.rhsmConfFile, "productCertDir",productCertDirForNoProductsinstalled); SSHCommandResult r = client.runCommandAndWait("ls -1 "+productCertDirForNoProductsinstalled+" | wc -l"); Assert.assertEquals(Integer.valueOf(r.getStdout().trim()),Integer.valueOf(0), "The "+clienttasks.rhsmConfFile+" file is currently configured with a productCertDir that contains no products."); } // Data Providers *********************************************************************** }
true
true
public void setupProductCertDirsBeforeClass() { // clean out the productCertDirs for (String productCertDir : new String[]{productCertDirForSomeProductsSubscribable,productCertDirForAllProductsSubscribable,productCertDirForNoProductsSubscribable,productCertDirForNoProductsinstalled}) { RemoteFileTasks.runCommandAndAssert(client, "rm -rf "+productCertDir, 0); RemoteFileTasks.runCommandAndAssert(client, "mkdir "+productCertDir, 0); } // autosubscribe clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, Boolean.TRUE, nullString, Boolean.TRUE, null, null, null); // // distribute a copy of the product certs amongst the productCertDirs // List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts(); // for (File productCertFile : clienttasks.getCurrentProductCertFiles()) { // ProductCert productCert = clienttasks.getProductCertFromProductCertFile(productCertFile); // // TODO WORKAROUND NEEDED FOR Bug 733805 - the name in the subscription-manager installed product listing is changing after a valid subscribe is performed (https://bugzilla.redhat.com/show_bug.cgi?id=733805) // InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productName", productCert.productName, installedProducts); // if (installedProduct.status.equalsIgnoreCase("Not Subscribed")) { // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForNoProductsSubscribable, 0); // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); // } else if (installedProduct.status.equalsIgnoreCase("Subscribed")) { // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForAllProductsSubscribable, 0); // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); // } // } // distribute a copy of the product certs amongst the productCertDirs List<EntitlementCert> entitlementCerts = clienttasks.getCurrentEntitlementCerts(); for (File productCertFile : clienttasks.getCurrentProductCertFiles()) { ProductCert productCert = clienttasks.getProductCertFromProductCertFile(productCertFile); // WORKAROUND NEEDED FOR Bug 733805 - the name in the subscription-manager installed product listing is changing after a valid subscribe is performed (https://bugzilla.redhat.com/show_bug.cgi?id=733805) List<EntitlementCert> correspondingEntitlementCerts = clienttasks.getEntitlementCertsCorrespondingToProductCert(productCert); if (correspondingEntitlementCerts.isEmpty()) { // "Not Subscribed" case... RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForNoProductsSubscribable, 0); RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); } else { // "Subscribed" case... RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForAllProductsSubscribable, 0); RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); } // TODO "Partially Subscribed" case //InstalledProduct installedProduct = clienttasks.getInstalledProductCorrespondingToEntitlementCert(correspondingEntitlementCert); } this.productCertDir = clienttasks.productCertDir; }
public void setupProductCertDirsBeforeClass() { // clean out the productCertDirs for (String productCertDir : new String[]{productCertDirForSomeProductsSubscribable,productCertDirForAllProductsSubscribable,productCertDirForNoProductsSubscribable,productCertDirForNoProductsinstalled}) { RemoteFileTasks.runCommandAndAssert(client, "rm -rf "+productCertDir, 0); RemoteFileTasks.runCommandAndAssert(client, "mkdir "+productCertDir, 0); } // autosubscribe clienttasks.unregister(null,null,null); // avoid Bug 733525 - [Errno 2] No such file or directory: '/etc/pki/entitlement' clienttasks.register(sm_clientUsername, sm_clientPassword, sm_clientOrg, null, null, null, null, Boolean.TRUE, nullString, Boolean.TRUE, null, null, null); // // distribute a copy of the product certs amongst the productCertDirs // List<InstalledProduct> installedProducts = clienttasks.getCurrentlyInstalledProducts(); // for (File productCertFile : clienttasks.getCurrentProductCertFiles()) { // ProductCert productCert = clienttasks.getProductCertFromProductCertFile(productCertFile); // // TODO WORKAROUND NEEDED FOR Bug 733805 - the name in the subscription-manager installed product listing is changing after a valid subscribe is performed (https://bugzilla.redhat.com/show_bug.cgi?id=733805) // InstalledProduct installedProduct = InstalledProduct.findFirstInstanceWithMatchingFieldFromList("productName", productCert.productName, installedProducts); // if (installedProduct.status.equalsIgnoreCase("Not Subscribed")) { // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForNoProductsSubscribable, 0); // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); // } else if (installedProduct.status.equalsIgnoreCase("Subscribed")) { // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForAllProductsSubscribable, 0); // RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); // } // } // distribute a copy of the product certs amongst the productCertDirs List<EntitlementCert> entitlementCerts = clienttasks.getCurrentEntitlementCerts(); for (File productCertFile : clienttasks.getCurrentProductCertFiles()) { ProductCert productCert = clienttasks.getProductCertFromProductCertFile(productCertFile); // WORKAROUND NEEDED FOR Bug 733805 - the name in the subscription-manager installed product listing is changing after a valid subscribe is performed (https://bugzilla.redhat.com/show_bug.cgi?id=733805) List<EntitlementCert> correspondingEntitlementCerts = clienttasks.getEntitlementCertsCorrespondingToProductCert(productCert); if (correspondingEntitlementCerts.isEmpty()) { // "Not Subscribed" case... RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForNoProductsSubscribable, 0); RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); } else { // "Subscribed" case... RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForAllProductsSubscribable, 0); RemoteFileTasks.runCommandAndAssert(client, "cp "+productCertFile+" "+productCertDirForSomeProductsSubscribable, 0); } // TODO "Partially Subscribed" case //InstalledProduct installedProduct = clienttasks.getInstalledProductCorrespondingToEntitlementCert(correspondingEntitlementCert); } this.productCertDir = clienttasks.productCertDir; }
diff --git a/motech-server-core/src/main/java/org/motechproject/server/model/MotechMessageProgramState.java b/motech-server-core/src/main/java/org/motechproject/server/model/MotechMessageProgramState.java index ff0c2d2e..d24dc5da 100644 --- a/motech-server-core/src/main/java/org/motechproject/server/model/MotechMessageProgramState.java +++ b/motech-server-core/src/main/java/org/motechproject/server/model/MotechMessageProgramState.java @@ -1,182 +1,182 @@ /** * MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT * * Copyright (c) 2010-11 The Trustees of Columbia University in the City of * New York and Grameen Foundation USA. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Grameen Foundation USA, Columbia University, or * their respective contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY * 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 GRAMEEN FOUNDATION * USA, COLUMBIA UNIVERSITY 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.motechproject.server.model; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.motechproject.server.event.MessagesCommand; import org.motechproject.server.model.db.ProgramMessageKey; import org.motechproject.server.svc.RegistrarBean; import org.motechproject.server.time.TimeBean; import org.motechproject.server.time.TimePeriod; import org.motechproject.server.time.TimeReference; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MotechMessageProgramState implements MessageProgramState { private List<MessageProgramStateTransition> transitions = new ArrayList<MessageProgramStateTransition>(); private MessagesCommand command; private Integer timeValue; private TimePeriod timePeriod; private TimeReference timeReference; private Long id; private ProgramMessageKey messageKey; private String conceptName; private String conceptValue; private String name; private TimeBean timeBean; private MotechMessageProgramState next ; private static Log log = LogFactory.getLog("motech.scheduler"); public void addTransition(MessageProgramStateTransition transition) { transitions.add(transition); } public MessageProgramStateTransition getTransition(MessageProgramEnrollment enrollment, Date currentDate, RegistrarBean registrarBean) { - log.debug("Getting transitions for " + enrollment.getProgram() + " with transitions size " + transitions.size()); + log.debug("Getting transitions for " + enrollment.getProgram() + " state id = " + id + " with transitions size " + transitions.size()); for (MessageProgramStateTransition transition : transitions) { if (transition.evaluate(enrollment, currentDate, registrarBean)) { return transition; } } return null; } public Date getDateOfAction(MessageProgramEnrollment enrollment, Date currentDate) { Date actionDate = timeBean.determineTime(timePeriod, timeReference, timeValue, null, enrollment, conceptName, conceptValue, null, null); return command.adjustActionDate(enrollment, actionDate, currentDate); } public MessagesCommand getCommand() { return command; } public void setCommand(MessagesCommand command) { this.command = command; } public void setTimeValue(Integer timeValue) { this.timeValue = timeValue; } public void setTimePeriod(TimePeriod timePeriod) { this.timePeriod = timePeriod; } public void setTimeReference(TimeReference timeReference) { this.timeReference = timeReference; } public void setTime(int timeValue, TimePeriod timePeriod, TimeReference timeReference) { setTimeValue(timeValue); setTimePeriod(timePeriod); setTimeReference(timeReference); } public List<MessageProgramStateTransition> getTransitions() { return transitions; } public void setTransitions(List<MessageProgramStateTransition> transitions) { this.transitions = transitions; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public ProgramMessageKey getMessageKey() { return messageKey; } public void setMessageKey(ProgramMessageKey messageKey) { this.messageKey = messageKey; } public String getConceptName() { return conceptName; } public void setConceptName(String conceptName) { this.conceptName = conceptName; } public String getConceptValue() { return conceptValue; } public void setConceptValue(String conceptValue) { this.conceptValue = conceptValue; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setTimeBean(TimeBean timeBean) { this.timeBean = timeBean; } public MotechMessageProgramState getNext() { return next; } public Boolean hasNext() { return null != next ; } public void setNext(MotechMessageProgramState previous) { this.next = previous; } @Override public boolean equals(Object object) { MotechMessageProgramState otherState = (MotechMessageProgramState) object; return name.equals(otherState.getName()); } }
true
true
public MessageProgramStateTransition getTransition(MessageProgramEnrollment enrollment, Date currentDate, RegistrarBean registrarBean) { log.debug("Getting transitions for " + enrollment.getProgram() + " with transitions size " + transitions.size()); for (MessageProgramStateTransition transition : transitions) { if (transition.evaluate(enrollment, currentDate, registrarBean)) { return transition; } } return null; }
public MessageProgramStateTransition getTransition(MessageProgramEnrollment enrollment, Date currentDate, RegistrarBean registrarBean) { log.debug("Getting transitions for " + enrollment.getProgram() + " state id = " + id + " with transitions size " + transitions.size()); for (MessageProgramStateTransition transition : transitions) { if (transition.evaluate(enrollment, currentDate, registrarBean)) { return transition; } } return null; }
diff --git a/GnuBackgammon/src/it/alcacoop/backgammon/gservice/GServiceClient.java b/GnuBackgammon/src/it/alcacoop/backgammon/gservice/GServiceClient.java index 6cec9a9..4ba3fcc 100644 --- a/GnuBackgammon/src/it/alcacoop/backgammon/gservice/GServiceClient.java +++ b/GnuBackgammon/src/it/alcacoop/backgammon/gservice/GServiceClient.java @@ -1,148 +1,150 @@ package it.alcacoop.backgammon.gservice; import it.alcacoop.backgammon.GnuBackgammon; import it.alcacoop.backgammon.fsm.BaseFSM.Events; import java.util.concurrent.ArrayBlockingQueue; public class GServiceClient implements GServiceMessages { public static GServiceClient instance; public GServiceNetHandler queue; public GServiceCookieMonster coockieMonster; public ArrayBlockingQueue<String> sendQueue; private Thread sendThread; private GServiceClient() { queue = new GServiceNetHandler(); coockieMonster = new GServiceCookieMonster(); sendQueue = new ArrayBlockingQueue<String>(20); sendThread = new Thread(){ @Override public void run() { while (true) { try { synchronized (sendThread) { wait(230); } String msg = sendQueue.take(); GnuBackgammon.Instance.nativeFunctions.gserviceSendReliableRealTimeMessage(msg); } catch (InterruptedException e) { e.printStackTrace(); } } } }; sendThread.start(); } public static GServiceClient getInstance() { if (instance == null) instance = new GServiceClient(); return instance; } public void connect() { } public void processReceivedMessage(String s) { int coockie = coockieMonster.fIBSCookie(s); switch (coockie) { case GSERVICE_CONNECTED: GnuBackgammon.fsm.processEvent(Events.GSERVICE_CONNECTED, null); break; case GSERVICE_READY: queue.post(Events.GSERVICE_READY, null); //GnuBackgammon.fsm.processEvent(Events.GSERVICE_READY, null); break; case GSERVICE_INIT_RATING: String chunks[] = s.split(" "); queue.post(Events.GSERVICE_INIT_RATING, Double.parseDouble(chunks[1])); //GnuBackgammon.fsm.processEvent(Events.GSERVICE_INIT_RATING, Double.parseDouble(chunks[1])); break; case GSERVICE_HANDSHAKE: chunks = s.split(" "); queue.post(Events.GSERVICE_HANDSHAKE, Long.parseLong(chunks[1])); //GnuBackgammon.fsm.processEvent(Events.GSERVICE_HANDSHAKE, Long.parseLong(chunks[1])); break; case GSERVICE_OPENING_ROLL: chunks = s.split(" "); int p[] = {Integer.parseInt(chunks[1]), Integer.parseInt(chunks[2]), Integer.parseInt(chunks[3])}; queue.post(Events.GSERVICE_FIRSTROLL, p); break; case GSERVICE_ROLL: chunks = s.split(" "); int dices[] ={0, 0}; for (int i=1;i<3;i++) dices[i-1] = Integer.parseInt(chunks[i]); queue.post(Events.GSERVICE_ROLL, dices); break; case GSERVICE_MOVE: chunks = s.split(" "); int moves[] ={-1, -1, -1, -1, -1, -1, -1, -1}; for (int i=0;i<8;i++) moves[i] = Integer.parseInt(chunks[i+1]); queue.post(Events.GSERVICE_MOVES, moves); break; case GSERVICE_BOARD: chunks = s.split(" "); int[][] board = new int[2][25]; for (int i=0;i<25;i++) board[0][i] = Integer.parseInt(chunks[i+1]); for (int i=25;i<50;i++) board[1][i-25] = Integer.parseInt(chunks[i+1]); queue.post(Events.GSERVICE_BOARD, board); break; case GSERVICE_CHATMSG: s = s.replace("90 ", ""); GnuBackgammon.fsm.processEvent(Events.GSERVICE_CHATMSG, s); break; case GSERVICE_ABANDON: chunks = s.split(" "); GnuBackgammon.fsm.processEvent(Events.GSERVICE_ABANDON, Integer.parseInt(chunks[1])); break; case GSERVICE_PING: + GServiceClient.getInstance().sendMessage("90 \nWARNING: Your application version is outdated and it will not be supported anymore! Please update from Google Play Store"); + break; case GSERVICE_ERROR: break; case GSERVICE_BYE: GnuBackgammon.fsm.processEvent(Events.GSERVICE_BYE, null); break; } } public synchronized void sendMessage(String msg) { try { sendQueue.put(msg); } catch (InterruptedException e) { e.printStackTrace(); } } private final static int STATUS_OK = 0; private final static int STATUS_NETWORK_ERROR_OPERATION_FAILED = 6; public void leaveRoom(int code) { GnuBackgammon.Instance.nativeFunctions.gserviceResetRoom(); switch (code) { case STATUS_OK: // opponent disconnected GnuBackgammon.fsm.processEvent(Events.GSERVICE_ERROR, 0); break; case STATUS_NETWORK_ERROR_OPERATION_FAILED: // you disconnected GnuBackgammon.fsm.processEvent(Events.GSERVICE_ERROR, 1); break; case 10000: // activity stopped GnuBackgammon.fsm.processEvent(Events.GSERVICE_ERROR, 2); break; default: GnuBackgammon.fsm.processEvent(Events.GSERVICE_BYE, null); break; } } }
true
true
public void processReceivedMessage(String s) { int coockie = coockieMonster.fIBSCookie(s); switch (coockie) { case GSERVICE_CONNECTED: GnuBackgammon.fsm.processEvent(Events.GSERVICE_CONNECTED, null); break; case GSERVICE_READY: queue.post(Events.GSERVICE_READY, null); //GnuBackgammon.fsm.processEvent(Events.GSERVICE_READY, null); break; case GSERVICE_INIT_RATING: String chunks[] = s.split(" "); queue.post(Events.GSERVICE_INIT_RATING, Double.parseDouble(chunks[1])); //GnuBackgammon.fsm.processEvent(Events.GSERVICE_INIT_RATING, Double.parseDouble(chunks[1])); break; case GSERVICE_HANDSHAKE: chunks = s.split(" "); queue.post(Events.GSERVICE_HANDSHAKE, Long.parseLong(chunks[1])); //GnuBackgammon.fsm.processEvent(Events.GSERVICE_HANDSHAKE, Long.parseLong(chunks[1])); break; case GSERVICE_OPENING_ROLL: chunks = s.split(" "); int p[] = {Integer.parseInt(chunks[1]), Integer.parseInt(chunks[2]), Integer.parseInt(chunks[3])}; queue.post(Events.GSERVICE_FIRSTROLL, p); break; case GSERVICE_ROLL: chunks = s.split(" "); int dices[] ={0, 0}; for (int i=1;i<3;i++) dices[i-1] = Integer.parseInt(chunks[i]); queue.post(Events.GSERVICE_ROLL, dices); break; case GSERVICE_MOVE: chunks = s.split(" "); int moves[] ={-1, -1, -1, -1, -1, -1, -1, -1}; for (int i=0;i<8;i++) moves[i] = Integer.parseInt(chunks[i+1]); queue.post(Events.GSERVICE_MOVES, moves); break; case GSERVICE_BOARD: chunks = s.split(" "); int[][] board = new int[2][25]; for (int i=0;i<25;i++) board[0][i] = Integer.parseInt(chunks[i+1]); for (int i=25;i<50;i++) board[1][i-25] = Integer.parseInt(chunks[i+1]); queue.post(Events.GSERVICE_BOARD, board); break; case GSERVICE_CHATMSG: s = s.replace("90 ", ""); GnuBackgammon.fsm.processEvent(Events.GSERVICE_CHATMSG, s); break; case GSERVICE_ABANDON: chunks = s.split(" "); GnuBackgammon.fsm.processEvent(Events.GSERVICE_ABANDON, Integer.parseInt(chunks[1])); break; case GSERVICE_PING: case GSERVICE_ERROR: break; case GSERVICE_BYE: GnuBackgammon.fsm.processEvent(Events.GSERVICE_BYE, null); break; } }
public void processReceivedMessage(String s) { int coockie = coockieMonster.fIBSCookie(s); switch (coockie) { case GSERVICE_CONNECTED: GnuBackgammon.fsm.processEvent(Events.GSERVICE_CONNECTED, null); break; case GSERVICE_READY: queue.post(Events.GSERVICE_READY, null); //GnuBackgammon.fsm.processEvent(Events.GSERVICE_READY, null); break; case GSERVICE_INIT_RATING: String chunks[] = s.split(" "); queue.post(Events.GSERVICE_INIT_RATING, Double.parseDouble(chunks[1])); //GnuBackgammon.fsm.processEvent(Events.GSERVICE_INIT_RATING, Double.parseDouble(chunks[1])); break; case GSERVICE_HANDSHAKE: chunks = s.split(" "); queue.post(Events.GSERVICE_HANDSHAKE, Long.parseLong(chunks[1])); //GnuBackgammon.fsm.processEvent(Events.GSERVICE_HANDSHAKE, Long.parseLong(chunks[1])); break; case GSERVICE_OPENING_ROLL: chunks = s.split(" "); int p[] = {Integer.parseInt(chunks[1]), Integer.parseInt(chunks[2]), Integer.parseInt(chunks[3])}; queue.post(Events.GSERVICE_FIRSTROLL, p); break; case GSERVICE_ROLL: chunks = s.split(" "); int dices[] ={0, 0}; for (int i=1;i<3;i++) dices[i-1] = Integer.parseInt(chunks[i]); queue.post(Events.GSERVICE_ROLL, dices); break; case GSERVICE_MOVE: chunks = s.split(" "); int moves[] ={-1, -1, -1, -1, -1, -1, -1, -1}; for (int i=0;i<8;i++) moves[i] = Integer.parseInt(chunks[i+1]); queue.post(Events.GSERVICE_MOVES, moves); break; case GSERVICE_BOARD: chunks = s.split(" "); int[][] board = new int[2][25]; for (int i=0;i<25;i++) board[0][i] = Integer.parseInt(chunks[i+1]); for (int i=25;i<50;i++) board[1][i-25] = Integer.parseInt(chunks[i+1]); queue.post(Events.GSERVICE_BOARD, board); break; case GSERVICE_CHATMSG: s = s.replace("90 ", ""); GnuBackgammon.fsm.processEvent(Events.GSERVICE_CHATMSG, s); break; case GSERVICE_ABANDON: chunks = s.split(" "); GnuBackgammon.fsm.processEvent(Events.GSERVICE_ABANDON, Integer.parseInt(chunks[1])); break; case GSERVICE_PING: GServiceClient.getInstance().sendMessage("90 \nWARNING: Your application version is outdated and it will not be supported anymore! Please update from Google Play Store"); break; case GSERVICE_ERROR: break; case GSERVICE_BYE: GnuBackgammon.fsm.processEvent(Events.GSERVICE_BYE, null); break; } }
diff --git a/E-EYE-O_RIAVaadin/src/com/jtbdevelopment/e_eye_o/ria/vaadin/components/workareas/ReportsWorkArea.java b/E-EYE-O_RIAVaadin/src/com/jtbdevelopment/e_eye_o/ria/vaadin/components/workareas/ReportsWorkArea.java index 09fafe2..76e98b8 100644 --- a/E-EYE-O_RIAVaadin/src/com/jtbdevelopment/e_eye_o/ria/vaadin/components/workareas/ReportsWorkArea.java +++ b/E-EYE-O_RIAVaadin/src/com/jtbdevelopment/e_eye_o/ria/vaadin/components/workareas/ReportsWorkArea.java @@ -1,245 +1,245 @@ package com.jtbdevelopment.e_eye_o.ria.vaadin.components.workareas; import com.google.common.eventbus.Subscribe; import com.jtbdevelopment.e_eye_o.DAO.ReadOnlyDAO; import com.jtbdevelopment.e_eye_o.entities.*; import com.jtbdevelopment.e_eye_o.entities.events.AppUserOwnedObjectChanged; import com.jtbdevelopment.e_eye_o.reports.ReportBuilder; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.server.ConnectorResource; import com.vaadin.server.DownloadStream; import com.vaadin.shared.ui.datefield.Resolution; import com.vaadin.ui.*; import com.vaadin.ui.themes.Runo; import org.joda.time.LocalDate; import org.joda.time.LocalDateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.io.ByteArrayInputStream; import java.util.Set; /** * Date: 5/7/13 * Time: 11:26 AM */ @Component @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) // TODO - everything public class ReportsWorkArea extends CustomComponent { public static final String BY_STUDENT_BY_CATEGORY = "By Student, By Category"; public static final String BY_CATEGORY_BY_STUDENT = "By Category, By Student"; public static final String SUMMARY_REPORT = "Summary Report"; public static final String STUDENT_DISPLAY_PROPERTY = "summaryDescription"; public static final String CATEGORY_DISPLAY_PROPERTY = "description"; public static final String CLASS_DISPLAY_PROPERTY = "description"; private DateField fromField; private DateField toField; private ListSelect reportTypeField; @Autowired private ReportBuilder reportBuilder; @Autowired private ReadOnlyDAO readOnlyDAO; private AppUser appUser; private ListSelect classListField; private ListSelect categoryListField; private ListSelect studentListField; @Override public void attach() { appUser = getUI().getSession().getAttribute(AppUser.class); refreshLists(); super.attach(); } private void refreshLists() { BeanItemContainer<ObservationCategory> categories = new BeanItemContainer<>(ObservationCategory.class); categories.addAll(readOnlyDAO.getActiveEntitiesForUser(ObservationCategory.class, appUser)); categories.sort(new String[]{CATEGORY_DISPLAY_PROPERTY}, new boolean[]{true}); categoryListField.setContainerDataSource(categories); categoryListField.setRows(categories.size()); BeanItemContainer<ClassList> classes = new BeanItemContainer<>(ClassList.class); classes.addAll(readOnlyDAO.getActiveEntitiesForUser(ClassList.class, appUser)); classes.sort(new String[]{CLASS_DISPLAY_PROPERTY}, new boolean[]{true}); classListField.setContainerDataSource(classes); classListField.setRows(classes.size()); BeanItemContainer<Student> students = new BeanItemContainer<>(Student.class); students.addAll(readOnlyDAO.getActiveEntitiesForUser(Student.class, appUser)); students.sort(new String[]{STUDENT_DISPLAY_PROPERTY}, new boolean[]{true}); studentListField.setContainerDataSource(students); studentListField.setRows(students.size()); } @PostConstruct public void postConstruct() { setSizeFull(); VerticalLayout mainLayout = new VerticalLayout(); mainLayout.setImmediate(true); mainLayout.setSpacing(true); mainLayout.setMargin(true); setCompositionRoot(mainLayout); Label instruction = new Label("All ACTIVE classes, students and categories will be included by default unless you limit to specific ones."); instruction.setSizeUndefined(); mainLayout.addComponent(instruction); mainLayout.setComponentAlignment(instruction, Alignment.MIDDLE_CENTER); HorizontalLayout selectionRow = new HorizontalLayout(); selectionRow.setSpacing(true); reportTypeField = new ListSelect("Report Type:"); reportTypeField.addItem(BY_STUDENT_BY_CATEGORY); reportTypeField.addItem(BY_CATEGORY_BY_STUDENT); reportTypeField.addItem(SUMMARY_REPORT); reportTypeField.setMultiSelect(false); reportTypeField.setValue(BY_STUDENT_BY_CATEGORY); reportTypeField.setNullSelectionAllowed(false); - reportTypeField.setRows(2); + reportTypeField.setRows(3); selectionRow.addComponent(reportTypeField); VerticalLayout dates = new VerticalLayout(); dates.setSpacing(true); final LocalDate now = new LocalDate(); final LocalDate lastAugust; if (now.getMonthOfYear() < 8) { lastAugust = new LocalDate(now.getYear() - 1, 8, 1); } else { lastAugust = new LocalDate(now.getYear(), 8, 1); } fromField = new DateField("From:"); fromField.setResolution(Resolution.DAY); fromField.setValue(lastAugust.toDate()); dates.addComponent(fromField); toField = new DateField("To:"); toField.setResolution(Resolution.DAY); toField.setValue(now.toDate()); dates.addComponent(toField); selectionRow.addComponent(dates); classListField = new ListSelect("Only Include Classes:"); classListField.setMultiSelect(true); classListField.setItemCaptionPropertyId(CLASS_DISPLAY_PROPERTY); selectionRow.addComponent(classListField); categoryListField = new ListSelect("Only Include Categories:"); categoryListField.setMultiSelect(true); categoryListField.setItemCaptionPropertyId(CATEGORY_DISPLAY_PROPERTY); selectionRow.addComponent(categoryListField); studentListField = new ListSelect("Only Include Students:"); studentListField.setMultiSelect(true); studentListField.setItemCaptionPropertyId(STUDENT_DISPLAY_PROPERTY); selectionRow.addComponent(studentListField); VerticalLayout buttons = new VerticalLayout(); buttons.setSpacing(true); Button generate = new Button("Generate"); buttons.addComponent(generate); Button reset = new Button("Reset"); buttons.addComponent(reset); selectionRow.addComponent(buttons); selectionRow.setComponentAlignment(buttons, Alignment.MIDDLE_LEFT); generate.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { final byte[] pdf; switch ((String) reportTypeField.getValue()) { case BY_CATEGORY_BY_STUDENT: pdf = reportBuilder.generateObservationReportByCategoryAndStudent(appUser, (Set<ClassList>) classListField.getValue(), (Set<Student>) studentListField.getValue(), (Set<ObservationCategory>) categoryListField.getValue(), new LocalDate(fromField.getValue()), new LocalDate(toField.getValue())); break; case BY_STUDENT_BY_CATEGORY: pdf = reportBuilder.generateObservationReportByStudentAndCategory(appUser, (Set<ClassList>) classListField.getValue(), (Set<Student>) studentListField.getValue(), (Set<ObservationCategory>) categoryListField.getValue(), new LocalDate(fromField.getValue()), new LocalDate(toField.getValue())); break; case SUMMARY_REPORT: pdf = reportBuilder.generateObservationStudentSummaryReport(appUser, (Set<ClassList>) classListField.getValue(), (Set<Student>) studentListField.getValue(), (Set<ObservationCategory>) categoryListField.getValue(), new LocalDate(fromField.getValue()), new LocalDate(toField.getValue())); break; default: throw new RuntimeException("Unknown Report Type"); } BrowserFrame report = new BrowserFrame(null, new ConnectorResource() { @Override public String getMIMEType() { return "application/pdf"; } @Override public DownloadStream getStream() { return new DownloadStream(new ByteArrayInputStream(pdf), getMIMEType(), getFilename()); } @Override public String getFilename() { return "Report" + new LocalDateTime().toString("yyyyMMddHHmmss") + ".pdf"; } }); Window window = new Window(); VerticalLayout mainLayout = new VerticalLayout(); window.setContent(mainLayout); window.setResizable(true); window.setSizeFull(); window.center(); mainLayout.setSizeFull(); report.setSizeFull(); mainLayout.addComponent(report); window.addStyleName(Runo.WINDOW_DIALOG); window.setModal(true); window.setCaption("Report Contents"); getUI().addWindow(window); } }); reset.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { getUI().setFocusedComponent(reportTypeField); classListField.setValue(null); studentListField.setValue(null); categoryListField.setValue(null); fromField.setValue(lastAugust.toDate()); toField.setValue(now.toDate()); reportTypeField.setValue(BY_STUDENT_BY_CATEGORY); } }); mainLayout.addComponent(selectionRow); mainLayout.setComponentAlignment(selectionRow, Alignment.TOP_CENTER); } @Subscribe @SuppressWarnings({"unused", "unchecked"}) public void handleIdObjectChange(final AppUserOwnedObjectChanged msg) { if (!getSession().getAttribute(AppUser.class).equals(msg.getEntity().getAppUser())) { return; } if (Observation.class.isAssignableFrom(msg.getEntityType())) { return; } refreshLists(); } }
true
true
public void postConstruct() { setSizeFull(); VerticalLayout mainLayout = new VerticalLayout(); mainLayout.setImmediate(true); mainLayout.setSpacing(true); mainLayout.setMargin(true); setCompositionRoot(mainLayout); Label instruction = new Label("All ACTIVE classes, students and categories will be included by default unless you limit to specific ones."); instruction.setSizeUndefined(); mainLayout.addComponent(instruction); mainLayout.setComponentAlignment(instruction, Alignment.MIDDLE_CENTER); HorizontalLayout selectionRow = new HorizontalLayout(); selectionRow.setSpacing(true); reportTypeField = new ListSelect("Report Type:"); reportTypeField.addItem(BY_STUDENT_BY_CATEGORY); reportTypeField.addItem(BY_CATEGORY_BY_STUDENT); reportTypeField.addItem(SUMMARY_REPORT); reportTypeField.setMultiSelect(false); reportTypeField.setValue(BY_STUDENT_BY_CATEGORY); reportTypeField.setNullSelectionAllowed(false); reportTypeField.setRows(2); selectionRow.addComponent(reportTypeField); VerticalLayout dates = new VerticalLayout(); dates.setSpacing(true); final LocalDate now = new LocalDate(); final LocalDate lastAugust; if (now.getMonthOfYear() < 8) { lastAugust = new LocalDate(now.getYear() - 1, 8, 1); } else { lastAugust = new LocalDate(now.getYear(), 8, 1); } fromField = new DateField("From:"); fromField.setResolution(Resolution.DAY); fromField.setValue(lastAugust.toDate()); dates.addComponent(fromField); toField = new DateField("To:"); toField.setResolution(Resolution.DAY); toField.setValue(now.toDate()); dates.addComponent(toField); selectionRow.addComponent(dates); classListField = new ListSelect("Only Include Classes:"); classListField.setMultiSelect(true); classListField.setItemCaptionPropertyId(CLASS_DISPLAY_PROPERTY); selectionRow.addComponent(classListField); categoryListField = new ListSelect("Only Include Categories:"); categoryListField.setMultiSelect(true); categoryListField.setItemCaptionPropertyId(CATEGORY_DISPLAY_PROPERTY); selectionRow.addComponent(categoryListField); studentListField = new ListSelect("Only Include Students:"); studentListField.setMultiSelect(true); studentListField.setItemCaptionPropertyId(STUDENT_DISPLAY_PROPERTY); selectionRow.addComponent(studentListField); VerticalLayout buttons = new VerticalLayout(); buttons.setSpacing(true); Button generate = new Button("Generate"); buttons.addComponent(generate); Button reset = new Button("Reset"); buttons.addComponent(reset); selectionRow.addComponent(buttons); selectionRow.setComponentAlignment(buttons, Alignment.MIDDLE_LEFT); generate.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { final byte[] pdf; switch ((String) reportTypeField.getValue()) { case BY_CATEGORY_BY_STUDENT: pdf = reportBuilder.generateObservationReportByCategoryAndStudent(appUser, (Set<ClassList>) classListField.getValue(), (Set<Student>) studentListField.getValue(), (Set<ObservationCategory>) categoryListField.getValue(), new LocalDate(fromField.getValue()), new LocalDate(toField.getValue())); break; case BY_STUDENT_BY_CATEGORY: pdf = reportBuilder.generateObservationReportByStudentAndCategory(appUser, (Set<ClassList>) classListField.getValue(), (Set<Student>) studentListField.getValue(), (Set<ObservationCategory>) categoryListField.getValue(), new LocalDate(fromField.getValue()), new LocalDate(toField.getValue())); break; case SUMMARY_REPORT: pdf = reportBuilder.generateObservationStudentSummaryReport(appUser, (Set<ClassList>) classListField.getValue(), (Set<Student>) studentListField.getValue(), (Set<ObservationCategory>) categoryListField.getValue(), new LocalDate(fromField.getValue()), new LocalDate(toField.getValue())); break; default: throw new RuntimeException("Unknown Report Type"); } BrowserFrame report = new BrowserFrame(null, new ConnectorResource() { @Override public String getMIMEType() { return "application/pdf"; } @Override public DownloadStream getStream() { return new DownloadStream(new ByteArrayInputStream(pdf), getMIMEType(), getFilename()); } @Override public String getFilename() { return "Report" + new LocalDateTime().toString("yyyyMMddHHmmss") + ".pdf"; } }); Window window = new Window(); VerticalLayout mainLayout = new VerticalLayout(); window.setContent(mainLayout); window.setResizable(true); window.setSizeFull(); window.center(); mainLayout.setSizeFull(); report.setSizeFull(); mainLayout.addComponent(report); window.addStyleName(Runo.WINDOW_DIALOG); window.setModal(true); window.setCaption("Report Contents"); getUI().addWindow(window); } }); reset.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { getUI().setFocusedComponent(reportTypeField); classListField.setValue(null); studentListField.setValue(null); categoryListField.setValue(null); fromField.setValue(lastAugust.toDate()); toField.setValue(now.toDate()); reportTypeField.setValue(BY_STUDENT_BY_CATEGORY); } }); mainLayout.addComponent(selectionRow); mainLayout.setComponentAlignment(selectionRow, Alignment.TOP_CENTER); }
public void postConstruct() { setSizeFull(); VerticalLayout mainLayout = new VerticalLayout(); mainLayout.setImmediate(true); mainLayout.setSpacing(true); mainLayout.setMargin(true); setCompositionRoot(mainLayout); Label instruction = new Label("All ACTIVE classes, students and categories will be included by default unless you limit to specific ones."); instruction.setSizeUndefined(); mainLayout.addComponent(instruction); mainLayout.setComponentAlignment(instruction, Alignment.MIDDLE_CENTER); HorizontalLayout selectionRow = new HorizontalLayout(); selectionRow.setSpacing(true); reportTypeField = new ListSelect("Report Type:"); reportTypeField.addItem(BY_STUDENT_BY_CATEGORY); reportTypeField.addItem(BY_CATEGORY_BY_STUDENT); reportTypeField.addItem(SUMMARY_REPORT); reportTypeField.setMultiSelect(false); reportTypeField.setValue(BY_STUDENT_BY_CATEGORY); reportTypeField.setNullSelectionAllowed(false); reportTypeField.setRows(3); selectionRow.addComponent(reportTypeField); VerticalLayout dates = new VerticalLayout(); dates.setSpacing(true); final LocalDate now = new LocalDate(); final LocalDate lastAugust; if (now.getMonthOfYear() < 8) { lastAugust = new LocalDate(now.getYear() - 1, 8, 1); } else { lastAugust = new LocalDate(now.getYear(), 8, 1); } fromField = new DateField("From:"); fromField.setResolution(Resolution.DAY); fromField.setValue(lastAugust.toDate()); dates.addComponent(fromField); toField = new DateField("To:"); toField.setResolution(Resolution.DAY); toField.setValue(now.toDate()); dates.addComponent(toField); selectionRow.addComponent(dates); classListField = new ListSelect("Only Include Classes:"); classListField.setMultiSelect(true); classListField.setItemCaptionPropertyId(CLASS_DISPLAY_PROPERTY); selectionRow.addComponent(classListField); categoryListField = new ListSelect("Only Include Categories:"); categoryListField.setMultiSelect(true); categoryListField.setItemCaptionPropertyId(CATEGORY_DISPLAY_PROPERTY); selectionRow.addComponent(categoryListField); studentListField = new ListSelect("Only Include Students:"); studentListField.setMultiSelect(true); studentListField.setItemCaptionPropertyId(STUDENT_DISPLAY_PROPERTY); selectionRow.addComponent(studentListField); VerticalLayout buttons = new VerticalLayout(); buttons.setSpacing(true); Button generate = new Button("Generate"); buttons.addComponent(generate); Button reset = new Button("Reset"); buttons.addComponent(reset); selectionRow.addComponent(buttons); selectionRow.setComponentAlignment(buttons, Alignment.MIDDLE_LEFT); generate.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { final byte[] pdf; switch ((String) reportTypeField.getValue()) { case BY_CATEGORY_BY_STUDENT: pdf = reportBuilder.generateObservationReportByCategoryAndStudent(appUser, (Set<ClassList>) classListField.getValue(), (Set<Student>) studentListField.getValue(), (Set<ObservationCategory>) categoryListField.getValue(), new LocalDate(fromField.getValue()), new LocalDate(toField.getValue())); break; case BY_STUDENT_BY_CATEGORY: pdf = reportBuilder.generateObservationReportByStudentAndCategory(appUser, (Set<ClassList>) classListField.getValue(), (Set<Student>) studentListField.getValue(), (Set<ObservationCategory>) categoryListField.getValue(), new LocalDate(fromField.getValue()), new LocalDate(toField.getValue())); break; case SUMMARY_REPORT: pdf = reportBuilder.generateObservationStudentSummaryReport(appUser, (Set<ClassList>) classListField.getValue(), (Set<Student>) studentListField.getValue(), (Set<ObservationCategory>) categoryListField.getValue(), new LocalDate(fromField.getValue()), new LocalDate(toField.getValue())); break; default: throw new RuntimeException("Unknown Report Type"); } BrowserFrame report = new BrowserFrame(null, new ConnectorResource() { @Override public String getMIMEType() { return "application/pdf"; } @Override public DownloadStream getStream() { return new DownloadStream(new ByteArrayInputStream(pdf), getMIMEType(), getFilename()); } @Override public String getFilename() { return "Report" + new LocalDateTime().toString("yyyyMMddHHmmss") + ".pdf"; } }); Window window = new Window(); VerticalLayout mainLayout = new VerticalLayout(); window.setContent(mainLayout); window.setResizable(true); window.setSizeFull(); window.center(); mainLayout.setSizeFull(); report.setSizeFull(); mainLayout.addComponent(report); window.addStyleName(Runo.WINDOW_DIALOG); window.setModal(true); window.setCaption("Report Contents"); getUI().addWindow(window); } }); reset.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { getUI().setFocusedComponent(reportTypeField); classListField.setValue(null); studentListField.setValue(null); categoryListField.setValue(null); fromField.setValue(lastAugust.toDate()); toField.setValue(now.toDate()); reportTypeField.setValue(BY_STUDENT_BY_CATEGORY); } }); mainLayout.addComponent(selectionRow); mainLayout.setComponentAlignment(selectionRow, Alignment.TOP_CENTER); }
diff --git a/optaplanner-examples/src/test/java/org/optaplanner/examples/common/persistence/SolutionDaoTest.java b/optaplanner-examples/src/test/java/org/optaplanner/examples/common/persistence/SolutionDaoTest.java index 29e1bb592..2dd140fd0 100644 --- a/optaplanner-examples/src/test/java/org/optaplanner/examples/common/persistence/SolutionDaoTest.java +++ b/optaplanner-examples/src/test/java/org/optaplanner/examples/common/persistence/SolutionDaoTest.java @@ -1,81 +1,83 @@ /* * Copyright 2013 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.optaplanner.examples.common.persistence; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.optaplanner.examples.common.app.LoggingTest; import org.optaplanner.examples.common.business.ExtensionFileFilter; import org.optaplanner.examples.common.business.ProblemFileComparator; @RunWith(Parameterized.class) public abstract class SolutionDaoTest extends LoggingTest { protected static Collection<Object[]> getSolutionFilesAsParameters(SolutionDao solutionDao) { List<File> fileList = new ArrayList<File>(0); File dataDir = solutionDao.getDataDir(); File unsolvedDataDir = new File(dataDir, "unsolved"); if (!unsolvedDataDir.exists()) { throw new IllegalStateException("The directory unsolvedDataDir (" + unsolvedDataDir.getAbsolutePath() + ") does not exist."); } fileList.addAll( FileUtils.listFiles(unsolvedDataDir, new String[]{solutionDao.getFileExtension()}, true)); File solvedDataDir = new File(dataDir, "solved"); - fileList.addAll( - FileUtils.listFiles(solvedDataDir, new String[]{solutionDao.getFileExtension()}, true)); + if (solvedDataDir.exists()) { + fileList.addAll( + FileUtils.listFiles(solvedDataDir, new String[]{solutionDao.getFileExtension()}, true)); + } Collections.sort(fileList, new ProblemFileComparator()); List<Object[]> filesAsParameters = new ArrayList<Object[]>(); for (File file : fileList) { filesAsParameters.add(new Object[]{file}); } return filesAsParameters; } protected SolutionDao solutionDao; protected File solutionFile; protected SolutionDaoTest(File solutionFile) { this.solutionFile = solutionFile; } @Before public void setUp() { solutionDao = createSolutionDao(); } protected abstract SolutionDao createSolutionDao(); @Test public void readSolution() { solutionDao.readSolution(solutionFile); } }
true
true
protected static Collection<Object[]> getSolutionFilesAsParameters(SolutionDao solutionDao) { List<File> fileList = new ArrayList<File>(0); File dataDir = solutionDao.getDataDir(); File unsolvedDataDir = new File(dataDir, "unsolved"); if (!unsolvedDataDir.exists()) { throw new IllegalStateException("The directory unsolvedDataDir (" + unsolvedDataDir.getAbsolutePath() + ") does not exist."); } fileList.addAll( FileUtils.listFiles(unsolvedDataDir, new String[]{solutionDao.getFileExtension()}, true)); File solvedDataDir = new File(dataDir, "solved"); fileList.addAll( FileUtils.listFiles(solvedDataDir, new String[]{solutionDao.getFileExtension()}, true)); Collections.sort(fileList, new ProblemFileComparator()); List<Object[]> filesAsParameters = new ArrayList<Object[]>(); for (File file : fileList) { filesAsParameters.add(new Object[]{file}); } return filesAsParameters; }
protected static Collection<Object[]> getSolutionFilesAsParameters(SolutionDao solutionDao) { List<File> fileList = new ArrayList<File>(0); File dataDir = solutionDao.getDataDir(); File unsolvedDataDir = new File(dataDir, "unsolved"); if (!unsolvedDataDir.exists()) { throw new IllegalStateException("The directory unsolvedDataDir (" + unsolvedDataDir.getAbsolutePath() + ") does not exist."); } fileList.addAll( FileUtils.listFiles(unsolvedDataDir, new String[]{solutionDao.getFileExtension()}, true)); File solvedDataDir = new File(dataDir, "solved"); if (solvedDataDir.exists()) { fileList.addAll( FileUtils.listFiles(solvedDataDir, new String[]{solutionDao.getFileExtension()}, true)); } Collections.sort(fileList, new ProblemFileComparator()); List<Object[]> filesAsParameters = new ArrayList<Object[]>(); for (File file : fileList) { filesAsParameters.add(new Object[]{file}); } return filesAsParameters; }
diff --git a/src/org/eclipse/core/internal/resources/Folder.java b/src/org/eclipse/core/internal/resources/Folder.java index 8784402a..5d9328e4 100644 --- a/src/org/eclipse/core/internal/resources/Folder.java +++ b/src/org/eclipse/core/internal/resources/Folder.java @@ -1,122 +1,122 @@ package org.eclipse.core.internal.resources; /* * Licensed Materials - Property of IBM, * WebSphere Studio Workbench * (c) Copyright IBM Corp 2000 */ import org.eclipse.core.resources.*; import org.eclipse.core.runtime.*; import org.eclipse.core.internal.utils.Policy; public class Folder extends Container implements IFolder { protected Folder(IPath path, Workspace container) { super(path, container); } /** * Changes this folder to be a file in the resource tree and returns * the newly created file. All related * properties are deleted. It is assumed that on disk the resource is * already a file so no action is taken to delete the disk contents. * <p> * <b>This method is for the exclusive use of the local resource manager</b> * * @see FileSystemResourceManager#reportChanges */ public IFile changeToFile() throws CoreException { getPropertyManager().deleteProperties(this); workspace.deleteResource(this); IFile result = workspace.getRoot().getFile(path); workspace.createResource(result, false); return result; } /** * @see IFolder */ public void create(boolean force, boolean local, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask(Policy.bind("creating", new String[] { getFullPath().toString()}), Policy.totalWork); checkValidPath(path, FOLDER); try { workspace.prepareOperation(); ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); checkDoesNotExist(flags, false); workspace.beginOperation(true); refreshLocal(DEPTH_ZERO, null); Container parent = (Container) getParent(); info = parent.getResourceInfo(false, false); flags = getFlags(info); parent.checkAccessible(flags); info = getResourceInfo(false, false); flags = getFlags(info); if (force) { if (exists(flags, false)) return; } else { checkDoesNotExist(flags, false); } - internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.totalWork)); + internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.opWork)); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } } /** * Ensures that this folder exists in the workspace. This is similar in * concept to mkdirs but it does not work on projects. * If this folder is created, it will be marked as being local. */ public void ensureExists(IProgressMonitor monitor) throws CoreException { ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); if (exists(flags, true)) return; if (exists(flags, false)) { String message = Policy.bind("folderOverFile", new String[] { getFullPath().toString()}); throw new ResourceException(IResourceStatus.RESOURCE_WRONG_TYPE, getFullPath(), message, null); } Container parent = (Container) getParent(); if (parent.getType() == PROJECT) { info = parent.getResourceInfo(false, false); parent.checkExists(getFlags(info), true); } else ((Folder) parent).ensureExists(monitor); internalCreate(true, true, monitor); } /** * @see IResource#getType */ public int getType() { return FOLDER; } public void internalCreate(boolean force, boolean local, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask("Creating file.", Policy.totalWork); workspace.createResource(this, false); if (local) { try { getLocalManager().write(this, force, Policy.subMonitorFor(monitor, Policy.totalWork * 75 / 100)); } catch (CoreException e) { // a problem happened creating the folder on disk, so delete from the workspace workspace.deleteResource(this); throw e; // rethrow } } setLocal(local, DEPTH_ZERO, Policy.subMonitorFor(monitor, Policy.totalWork * 25 / 100)); if (!local) getResourceInfo(true, true).setModificationStamp(IResource.NULL_STAMP); } finally { monitor.done(); } } }
true
true
public void create(boolean force, boolean local, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask(Policy.bind("creating", new String[] { getFullPath().toString()}), Policy.totalWork); checkValidPath(path, FOLDER); try { workspace.prepareOperation(); ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); checkDoesNotExist(flags, false); workspace.beginOperation(true); refreshLocal(DEPTH_ZERO, null); Container parent = (Container) getParent(); info = parent.getResourceInfo(false, false); flags = getFlags(info); parent.checkAccessible(flags); info = getResourceInfo(false, false); flags = getFlags(info); if (force) { if (exists(flags, false)) return; } else { checkDoesNotExist(flags, false); } internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.totalWork)); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } }
public void create(boolean force, boolean local, IProgressMonitor monitor) throws CoreException { monitor = Policy.monitorFor(monitor); try { monitor.beginTask(Policy.bind("creating", new String[] { getFullPath().toString()}), Policy.totalWork); checkValidPath(path, FOLDER); try { workspace.prepareOperation(); ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); checkDoesNotExist(flags, false); workspace.beginOperation(true); refreshLocal(DEPTH_ZERO, null); Container parent = (Container) getParent(); info = parent.getResourceInfo(false, false); flags = getFlags(info); parent.checkAccessible(flags); info = getResourceInfo(false, false); flags = getFlags(info); if (force) { if (exists(flags, false)) return; } else { checkDoesNotExist(flags, false); } internalCreate(force, local, Policy.subMonitorFor(monitor, Policy.opWork)); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; } finally { workspace.endOperation(true, Policy.subMonitorFor(monitor, Policy.buildWork)); } } finally { monitor.done(); } }
diff --git a/Lab2/src/lab2/StraightLine.java b/Lab2/src/lab2/StraightLine.java index 87e1b88..96f924f 100644 --- a/Lab2/src/lab2/StraightLine.java +++ b/Lab2/src/lab2/StraightLine.java @@ -1,210 +1,227 @@ package lab2; /****************************************************** Cours : LOG121 Session : A2013 Groupe : 01 Projet : Laboratoire #1 �tudiant(e)(s) : Maude Payette Andr�-Philippe Boulet Hugo Desjardins-De Libero Code(s) perm. : PAYM03549202 BOUA29058709 DESH29099109 Professeur : Ghizlane El boussaidi Charg�s de labo : Alvine Boaye Belle et Mathieu Battah Nom du fichier : Line.java Date cr�� : 2013-09-25 Date dern. modif. 2013-10-17 ******************************************************* Historique des modifications ******************************************************* 2013-09-25 Version initiale *******************************************************/ import java.awt.BasicStroke; import java.awt.Graphics; import java.awt.Color; import java.awt.Graphics2D; /** * @author Maude * */ public class StraightLine extends AbstractCustomShape { private int secondX; private int secondY; /** * Constructeur de la classe * * @param sequenceNumber * Est le num�ro de s�quence re�u * @param parametres * Est la chaine de caract�res qui contient les param�tres de la * forme */ public StraightLine(int sequenceNumber, String parametres) { super(sequenceNumber, Color.black); decoderParametres(parametres); } /** * Trouve les param�tres et les associe * * @param parametres * Est la chaine de caract�res qui contient les param�tres de la * forme. */ protected void decoderParametres(String parametres) { // D�coder la string de param�tres pour trouver le x, le y, la hauteur // et la largeur String str[] = parametres.split(" "); // Sauvegarde les x et les y try { setFirstX(Integer.parseInt(str[0])); setFirstY(Integer.parseInt(str[1])); setSecondX(Integer.parseInt(str[2])); setSecondY(Integer.parseInt(str[3])); } catch (Exception e) { // Afficher exception e.printStackTrace(); } } /** * Fonction qui dessine la forme * * @param pGraphic * Objet graphique qui est utilis� pour dessiner */ public void draw(Graphics pGraphic, int drawX, int drawY) { drawRectangle(pGraphic, drawX, drawY); pGraphic.setColor(this.color); Graphics2D test = (Graphics2D)pGraphic; test.setStroke(new BasicStroke(BasicStroke.CAP_BUTT)); pGraphic.drawLine(drawX, drawY, getSecondX()+(drawX-getFirstX()), getSecondY()+(drawY-getFirstY())); } /** * Fonction qui dessine le contour rectangle de la forme * * @param pGraphic * Objet graphique qui est utilis� pour dessiner */ protected void drawRectangle(Graphics pGraphic, int drawX, int drawY) { pGraphic.setColor(Color.black); Graphics2D test = (Graphics2D)pGraphic; test.setStroke( new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f, new float[] {3f}, 0f)); //pGraphic.drawRect(drawX - 1, drawY - 1, getSecondX()-getFirstX() +1, getSecondY()-getFirstY() +1); + int x = 0; + int y = 0; + int widthX = 0; + int widthY = 0; if(getSecondX()-getFirstX() >= 0 && getSecondY()-getFirstY() >= 0) { - pGraphic.drawRect(drawX - 1, drawY - 1, getSecondX()-getFirstX() +1, getSecondY()-getFirstY() +1); + x = drawX-1; + y = drawY-1; + widthX = getSecondX()-getFirstX() + 1; + widthY = getSecondY()-getFirstY() + 1; } - if(getSecondX()-getFirstX() <= 0 && getSecondY()-getFirstY() >= 0) + if(getSecondX()-getFirstX() < 0 && getSecondY()-getFirstY() >= 0) { - pGraphic.drawRect(getSecondX()+(drawX-getFirstX()) - 1, drawY - 1, drawX, getSecondY()-getFirstY() +1); + x = getSecondX()+(drawX-getFirstX()) - 1; + y = drawY - 1; + widthX = getFirstX()-getSecondX() + 1; + widthY = getSecondY()-getFirstY() + 1; } - if(getSecondX()-getFirstX() <= 0 && getSecondY()-getFirstY() <= 0) + if(getSecondX()-getFirstX() < 0 && getSecondY()-getFirstY() < 0) { - pGraphic.drawRect(getSecondX()+(drawX-getFirstX()) - 1, getSecondY()+(drawY-getFirstY()) - 1, drawX, drawY); + x = getSecondX()+(drawX-getFirstX()) - 1; + y = getSecondY()+(drawY-getFirstY()) - 1; + widthX = getFirstX()-getSecondX() + 1; + widthY = getFirstY()-getSecondY() + 1; } - if(getSecondX()-getFirstX() >= 0 && getSecondY()-getFirstY() <= 0) + if(getSecondX()-getFirstX() >= 0 && getSecondY()-getFirstY() < 0) { - pGraphic.drawRect(drawX - 1, getSecondY()+(drawY-getFirstY()) - 1, getSecondX()-getFirstX() +1, drawY); + x = drawX-1; + y = getSecondY()+(drawY-getFirstY()) - 1; + widthX = getSecondX()-getFirstX() + 1; + widthY = getFirstY()-getSecondY() + 1; } + pGraphic.drawRect(x,y,widthX,widthY); } // Getters & Setters// /** * @return the secondX */ public int getSecondX() { return secondX; } /** * @param secondX * the secondX to set */ public void setSecondX(int secondX) { this.secondX = secondX; } /** * @return the secondY */ public int getSecondY() { return secondY; } /** * @param secondY * the secondY to set */ public void setSecondY(int secondY) { this.secondY = secondY; } /** * @param area * the area to set */ protected void setArea() { this.area = this.width * this.height; } /** * @param maxRange * the maxRange to set */ protected void setMaxRange() { this.maxRange = Math.sqrt(Math.pow(this.secondX - this.firstX, 2) + Math.pow(this.secondY - this.firstY, 2)); } /** * @param width * the width to set */ protected void setWidth(int width) { this.width = width; } /** * @param height * the height to set */ protected void setHeight(int height) { this.height = 1; } }
false
true
protected void drawRectangle(Graphics pGraphic, int drawX, int drawY) { pGraphic.setColor(Color.black); Graphics2D test = (Graphics2D)pGraphic; test.setStroke( new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f, new float[] {3f}, 0f)); //pGraphic.drawRect(drawX - 1, drawY - 1, getSecondX()-getFirstX() +1, getSecondY()-getFirstY() +1); if(getSecondX()-getFirstX() >= 0 && getSecondY()-getFirstY() >= 0) { pGraphic.drawRect(drawX - 1, drawY - 1, getSecondX()-getFirstX() +1, getSecondY()-getFirstY() +1); } if(getSecondX()-getFirstX() <= 0 && getSecondY()-getFirstY() >= 0) { pGraphic.drawRect(getSecondX()+(drawX-getFirstX()) - 1, drawY - 1, drawX, getSecondY()-getFirstY() +1); } if(getSecondX()-getFirstX() <= 0 && getSecondY()-getFirstY() <= 0) { pGraphic.drawRect(getSecondX()+(drawX-getFirstX()) - 1, getSecondY()+(drawY-getFirstY()) - 1, drawX, drawY); } if(getSecondX()-getFirstX() >= 0 && getSecondY()-getFirstY() <= 0) { pGraphic.drawRect(drawX - 1, getSecondY()+(drawY-getFirstY()) - 1, getSecondX()-getFirstX() +1, drawY); } }
protected void drawRectangle(Graphics pGraphic, int drawX, int drawY) { pGraphic.setColor(Color.black); Graphics2D test = (Graphics2D)pGraphic; test.setStroke( new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f, new float[] {3f}, 0f)); //pGraphic.drawRect(drawX - 1, drawY - 1, getSecondX()-getFirstX() +1, getSecondY()-getFirstY() +1); int x = 0; int y = 0; int widthX = 0; int widthY = 0; if(getSecondX()-getFirstX() >= 0 && getSecondY()-getFirstY() >= 0) { x = drawX-1; y = drawY-1; widthX = getSecondX()-getFirstX() + 1; widthY = getSecondY()-getFirstY() + 1; } if(getSecondX()-getFirstX() < 0 && getSecondY()-getFirstY() >= 0) { x = getSecondX()+(drawX-getFirstX()) - 1; y = drawY - 1; widthX = getFirstX()-getSecondX() + 1; widthY = getSecondY()-getFirstY() + 1; } if(getSecondX()-getFirstX() < 0 && getSecondY()-getFirstY() < 0) { x = getSecondX()+(drawX-getFirstX()) - 1; y = getSecondY()+(drawY-getFirstY()) - 1; widthX = getFirstX()-getSecondX() + 1; widthY = getFirstY()-getSecondY() + 1; } if(getSecondX()-getFirstX() >= 0 && getSecondY()-getFirstY() < 0) { x = drawX-1; y = getSecondY()+(drawY-getFirstY()) - 1; widthX = getSecondX()-getFirstX() + 1; widthY = getFirstY()-getSecondY() + 1; } pGraphic.drawRect(x,y,widthX,widthY); }
diff --git a/org.dawnsci.plotting.draw2d/src/org/dawnsci/plotting/draw2d/swtxy/ImageTrace.java b/org.dawnsci.plotting.draw2d/src/org/dawnsci/plotting/draw2d/swtxy/ImageTrace.java index 24593f1c2..83def5fc5 100644 --- a/org.dawnsci.plotting.draw2d/src/org/dawnsci/plotting/draw2d/swtxy/ImageTrace.java +++ b/org.dawnsci.plotting.draw2d/src/org/dawnsci/plotting/draw2d/swtxy/ImageTrace.java @@ -1,1352 +1,1352 @@ package org.dawnsci.plotting.draw2d.swtxy; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.csstudio.swt.widgets.figureparts.ColorMapRamp; import org.csstudio.swt.xygraph.figures.Axis; import org.csstudio.swt.xygraph.figures.IAxisListener; import org.csstudio.swt.xygraph.linearscale.Range; import org.dawb.common.services.IPaletteService; import org.dawb.common.ui.plot.AbstractPlottingSystem; import org.dawnsci.plotting.api.histogram.HistogramBound; import org.dawnsci.plotting.api.histogram.IImageService; import org.dawnsci.plotting.api.histogram.ImageServiceBean; import org.dawnsci.plotting.api.histogram.ImageServiceBean.HistoType; import org.dawnsci.plotting.api.histogram.ImageServiceBean.ImageOrigin; import org.dawnsci.plotting.api.preferences.BasePlottingConstants; import org.dawnsci.plotting.api.trace.DownSampleEvent; import org.dawnsci.plotting.api.trace.IDownSampleListener; import org.dawnsci.plotting.api.trace.IImageTrace; import org.dawnsci.plotting.api.trace.IPaletteListener; import org.dawnsci.plotting.api.trace.ITrace; import org.dawnsci.plotting.api.trace.ITraceContainer; import org.dawnsci.plotting.api.trace.PaletteEvent; import org.dawnsci.plotting.api.trace.TraceEvent; import org.dawnsci.plotting.api.trace.TraceUtils; import org.dawnsci.plotting.api.trace.TraceWillPlotEvent; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.preferences.InstanceScope; import org.eclipse.draw2d.Figure; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.ImageData; import org.eclipse.swt.graphics.PaletteData; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.preferences.ScopedPreferenceStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; import uk.ac.diamond.scisoft.analysis.dataset.BooleanDataset; import uk.ac.diamond.scisoft.analysis.dataset.DatasetUtils; import uk.ac.diamond.scisoft.analysis.dataset.DoubleDataset; import uk.ac.diamond.scisoft.analysis.dataset.IDataset; import uk.ac.diamond.scisoft.analysis.dataset.function.Downsample; import uk.ac.diamond.scisoft.analysis.dataset.function.DownsampleMode; import uk.ac.diamond.scisoft.analysis.roi.IROI; import uk.ac.diamond.scisoft.analysis.roi.LinearROI; import uk.ac.diamond.scisoft.analysis.roi.PointROI; import uk.ac.diamond.scisoft.analysis.roi.PolygonalROI; import uk.ac.diamond.scisoft.analysis.roi.PolylineROI; import uk.ac.diamond.scisoft.analysis.roi.RectangularROI; /** * A trace which draws an image to the plot. * * @author fcp94556 * */ public class ImageTrace extends Figure implements IImageTrace, IAxisListener, ITraceContainer { private static final Logger logger = LoggerFactory.getLogger(ImageTrace.class); private static final int MINIMUM_ZOOM_SIZE = 4; private String name; private Axis xAxis; private Axis yAxis; private ColorMapRamp intensityScale; private AbstractDataset image; private DownsampleType downsampleType=DownsampleType.MAXIMUM; private int currentDownSampleBin=-1; private List<IDataset> axes; private ImageServiceBean imageServiceBean; private boolean isMaximumZoom; private AbstractPlottingSystem plottingSystem; private IImageService service; public ImageTrace(final String name, final Axis xAxis, final Axis yAxis, final ColorMapRamp intensityScale) { this.name = name; this.xAxis = xAxis; this.yAxis = yAxis; this.intensityScale = intensityScale; this.imageServiceBean = new ImageServiceBean(); try { final IPaletteService pservice = (IPaletteService)PlatformUI.getWorkbench().getService(IPaletteService.class); final String scheme = getPreferenceStore().getString(BasePlottingConstants.COLOUR_SCHEME); imageServiceBean.setPalette(pservice.getPaletteData(scheme)); } catch (Exception e) { logger.error("Cannot create palette!", e); } imageServiceBean.setOrigin(ImageOrigin.forLabel(getPreferenceStore().getString(BasePlottingConstants.ORIGIN_PREF))); imageServiceBean.setHistogramType(HistoType.forLabel(getPreferenceStore().getString(BasePlottingConstants.HISTO_PREF))); imageServiceBean.setMinimumCutBound(HistogramBound.fromString(getPreferenceStore().getString(BasePlottingConstants.MIN_CUT))); imageServiceBean.setMaximumCutBound(HistogramBound.fromString(getPreferenceStore().getString(BasePlottingConstants.MAX_CUT))); imageServiceBean.setNanBound(HistogramBound.fromString(getPreferenceStore().getString(BasePlottingConstants.NAN_CUT))); imageServiceBean.setLo(getPreferenceStore().getDouble(BasePlottingConstants.HISTO_LO)); imageServiceBean.setHi(getPreferenceStore().getDouble(BasePlottingConstants.HISTO_HI)); this.service = (IImageService)PlatformUI.getWorkbench().getService(IImageService.class); downsampleType = DownsampleType.forLabel(getPreferenceStore().getString(BasePlottingConstants.DOWNSAMPLE_PREF)); xAxis.addListener(this); yAxis.addListener(this); xAxis.setTicksAtEnds(false); yAxis.setTicksAtEnds(false); xAxis.setTicksIndexBased(true); yAxis.setTicksIndexBased(true); if (xAxis instanceof AspectAxis && yAxis instanceof AspectAxis) { AspectAxis x = (AspectAxis)xAxis; AspectAxis y = (AspectAxis)yAxis; x.setKeepAspectWith(y); y.setKeepAspectWith(x); } } private IPreferenceStore store; private IPreferenceStore getPreferenceStore() { if (store!=null) return store; store = new ScopedPreferenceStore(InstanceScope.INSTANCE, "org.dawnsci.plotting"); return store; } public String getName() { return name; } public void setName(String name) { this.name = name; } public AspectAxis getXAxis() { return (AspectAxis)xAxis; } public void setXAxis(Axis xAxis) { this.xAxis = xAxis; xAxis.setTicksIndexBased(true); } public AspectAxis getYAxis() { return (AspectAxis)yAxis; } public void setYAxis(Axis yAxis) { this.yAxis = yAxis; yAxis.setTicksIndexBased(true); } public AbstractDataset getImage() { return image; } public PaletteData getPaletteData() { if (imageServiceBean==null) return null; return imageServiceBean.getPalette(); } public void setPaletteData(PaletteData paletteData) { if (imageServiceBean==null) return; imageServiceBean.setPalette(paletteData); createScaledImage(ImageScaleType.FORCE_REIMAGE, null); intensityScale.repaint(); repaint(); firePaletteDataListeners(paletteData); } private enum ImageScaleType { // Going up in order of work done NO_REIMAGE, REIMAGE_ALLOWED, FORCE_REIMAGE, REHISTOGRAM; } private Image scaledImage; private ImageData imageData; private boolean imageCreationAllowed = true; /** * When this is called the SWT image is created * and saved in the swtImage field. The image is downsampled. If rescaleAllowed * is set to false, the current bin is not checked and the last scaled image * is always used. * * Do not synchronized this method - it can cause a race condition on linux only. * * @return true if scaledImage created. */ private double xOffset; private double yOffset; private org.eclipse.swt.graphics.Rectangle screenRectangle; private boolean createScaledImage(ImageScaleType rescaleType, final IProgressMonitor monitor) { if (!imageCreationAllowed) return false; boolean requireImageGeneration = imageData==null || rescaleType==ImageScaleType.FORCE_REIMAGE || rescaleType==ImageScaleType.REHISTOGRAM; // We know that it is needed // If we just changed downsample scale, we force the update. // This allows user resizes of the plot area to be picked up // and the larger data size used if it fits. if (!requireImageGeneration && rescaleType==ImageScaleType.REIMAGE_ALLOWED && currentDownSampleBin>0) { if (getDownsampleBin()!=currentDownSampleBin) { requireImageGeneration = true; } } final XYRegionGraph graph = (XYRegionGraph)getXAxis().getParent(); final Rectangle rbounds = graph.getRegionArea().getBounds(); if (rbounds.width<1 || rbounds.height<1) return false; if (!imageCreationAllowed) return false; if (monitor!=null && monitor.isCanceled()) return false; if (requireImageGeneration) { try { imageCreationAllowed = false; if (image==null) return false; AbstractDataset reducedFullImage = getDownsampled(image); imageServiceBean.setImage(reducedFullImage); imageServiceBean.setMonitor(monitor); if (fullMask!=null) { // For masks, we preserve the min (the falses) to avoid loosing fine lines // which are masked. imageServiceBean.setMask(getDownsampled(fullMask, DownsampleMode.MINIMUM)); } else { imageServiceBean.setMask(null); // Ensure we lose the mask! } if (rescaleType==ImageScaleType.REHISTOGRAM) { // Avoids changing colouring to // max and min of new selection. AbstractDataset slice = slice(getYAxis().getRange(), getXAxis().getRange(), (AbstractDataset)getData()); ImageServiceBean histoBean = imageServiceBean.clone(); histoBean.setImage(slice); if (fullMask!=null) histoBean.setMask(slice(getYAxis().getRange(), getXAxis().getRange(), fullMask)); float[] fa = service.getFastStatistics(histoBean); setMin(fa[0]); setMax(fa[1]); } this.imageData = service.getImageData(imageServiceBean); try { ImageServiceBean intensityScaleBean = imageServiceBean.clone(); // We send the image drawn with the same palette to the // intensityScale // TODO FIXME This will not work in log mode final DoubleDataset dds = new DoubleDataset(256,1); double inc = (getMax().doubleValue()-getMin().doubleValue())/256d; for (int i = 0; i < 256; i++) { double val = getMax().doubleValue()-(i*inc); dds.set(val, i, 0); } intensityScaleBean.setImage(dds); intensityScaleBean.setMask(null); intensityScale.setImageData(service.getImageData(intensityScaleBean)); intensityScale.setLog10(getImageServiceBean().isLogColorScale()); } catch (Throwable ne) { logger.warn("Cannot update intensity!"); } } catch (Exception e) { logger.error("Cannot create image from data!", e); } finally { imageCreationAllowed = true; } } if (monitor!=null && monitor.isCanceled()) return false; try { isMaximumZoom = false; if (imageData!=null && imageData.width==bounds.width && imageData.height==bounds.height) { // No slice, faster if (monitor!=null && monitor.isCanceled()) return false; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = new Image(Display.getDefault(), imageData); } else { // slice data to get current zoom area /** * x1,y1--------------x2,y2 * | | * | | * | | * x3,y3--------------x4,y4 */ ImageData data = imageData; ImageOrigin origin = getImageOrigin(); Range xRange = xAxis.getRange(); Range yRange = yAxis.getRange(); double minX = xRange.getLower()/currentDownSampleBin; double minY = yRange.getLower()/currentDownSampleBin; double maxX = xRange.getUpper()/currentDownSampleBin; double maxY = yRange.getUpper()/currentDownSampleBin; int xSize = imageData.width; int ySize = imageData.height; // check as getLower and getUpper don't work as expected if(maxX < minX){ double temp = maxX; maxX = minX; minX = temp; } if(maxY < minY){ double temp = maxY; maxY = minY; minY = temp; } double xSpread = maxX - minX; double ySpread = maxY - minY; double xScale = rbounds.width / xSpread; double yScale = rbounds.height / ySpread; // System.err.println("Area is " + rbounds + " with scale (x,y) " + xScale + ", " + yScale); // Deliberately get the over-sized dimensions so that the edge pixels can be smoothly panned through. int minXI = (int) Math.floor(minX); int minYI = (int) Math.floor(minY); int maxXI = (int) Math.ceil(maxX); int maxYI = (int) Math.ceil(maxY); int fullWidth = (int) (maxXI-minXI); int fullHeight = (int) (maxYI-minYI); // Force a minimum size on the system if (fullWidth <= MINIMUM_ZOOM_SIZE) { if (fullWidth > imageData.width) fullWidth = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } if (fullHeight <= MINIMUM_ZOOM_SIZE) { if (fullHeight > imageData.height) fullHeight = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } int scaleWidth = (int) (fullWidth*xScale); int scaleHeight = (int) (fullHeight*yScale); // System.err.println("Scaling to " + scaleWidth + "x" + scaleHeight); int xPix = (int)minX; int yPix = (int)minY; double xPixD = 0; double yPixD = 0; // These offsets are used when the scaled images is drawn to the screen. xOffset = (minX - Math.floor(minX))*xScale; yOffset = (minY - Math.floor(minY))*yScale; // Deal with the origin orientations correctly. switch (origin) { case TOP_LEFT: break; case TOP_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; break; case BOTTOM_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; case BOTTOM_LEFT: yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; } // Slice the data. // Pixel slice on downsampled data = fast! if (imageData.depth <= 8) { // NOTE Assumes 8-bit images final int size = fullWidth*fullHeight; final byte[] pixels = new byte[size]; for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, fullWidth*y); } data = new ImageData(fullWidth, fullHeight, data.depth, getPaletteData(), 1, pixels); } else { // NOTE Assumes 24 Bit Images final int[] pixels = new int[fullWidth]; data = new ImageData(fullWidth, fullHeight, 24, new PaletteData(0xff0000, 0x00ff00, 0x0000ff)); for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, 0); data.setPixels(0, y, fullWidth, pixels, 0); } } // create the scaled image - // We suspicious if the algorithm wants to create an image + // We are suspicious if the algorithm wants to create an image // bigger than the screen size and in that case do not scale // Fix to http://jira.diamond.ac.uk/browse/SCI-926 boolean proceedWithScale = true; try { if (screenRectangle == null) { screenRectangle = Display.getCurrent().getPrimaryMonitor().getClientArea(); } - if (scaleWidth>screenRectangle.width || - scaleHeight>screenRectangle.height) { + if (scaleWidth>screenRectangle.width*2 || + scaleHeight>screenRectangle.height*2) { logger.error("Image scaling algorithm has malfunctioned and asked for an image bigger than the screen!"); logger.debug("scaleWidth="+scaleWidth); logger.debug("scaleHeight="+scaleHeight); proceedWithScale = false; } } catch (Throwable ne) { proceedWithScale = true; } if (proceedWithScale) { data = data!=null ? data.scaledTo(scaleWidth, scaleHeight) : null; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = data!=null ? new Image(Display.getDefault(), data) : null; } else if (scaledImage==null) { scaledImage = data!=null ? new Image(Display.getDefault(), data) : null; } } return true; } catch (IllegalArgumentException ie) { logger.error(ie.toString()); return false; } catch (java.lang.NegativeArraySizeException allowed) { return false; } catch (NullPointerException ne) { throw ne; } catch (Throwable ne) { logger.error("Image scale error!", ne); return false; } } private static final int[] getBounds(Range xr, Range yr) { return new int[] {(int) Math.floor(xr.getLower()), (int) Math.floor(yr.getLower()), (int) Math.ceil(xr.getUpper()), (int) Math.ceil(yr.getUpper())}; } private Map<Integer, Reference<Object>> mipMap; private Map<Integer, Reference<Object>> maskMap; private Collection<IDownSampleListener> downsampleListeners; private AbstractDataset getDownsampled(AbstractDataset image) { return getDownsampled(image, getDownsampleTypeDiamond()); } /** * Uses caches based on bin, not DownsampleMode. * @param image * @param mode * @return */ private AbstractDataset getDownsampled(AbstractDataset image, DownsampleMode mode) { // Down sample, no point histogramming the whole thing final int bin = getDownsampleBin(); boolean newBin = false; if (currentDownSampleBin!=bin) newBin = true; try { this.currentDownSampleBin = bin; if (bin==1) { logger.trace("No downsample bin (or bin=1)"); return image; // nothing to downsample } if (image.getDtype()!=AbstractDataset.BOOL) { if (mipMap!=null && mipMap.containsKey(bin) && mipMap.get(bin).get()!=null) { logger.trace("Downsample bin used, "+bin); return (AbstractDataset)mipMap.get(bin).get(); } } else { if (maskMap!=null && maskMap.containsKey(bin) && maskMap.get(bin).get()!=null) { logger.trace("Downsample mask bin used, "+bin); return (AbstractDataset)maskMap.get(bin).get(); } } final Downsample downSampler = new Downsample(mode, new int[]{bin,bin}); List<AbstractDataset> sets = downSampler.value(image); final AbstractDataset set = sets.get(0); if (image.getDtype()!=AbstractDataset.BOOL) { if (mipMap==null) mipMap = new HashMap<Integer,Reference<Object>>(3); mipMap.put(bin, new SoftReference<Object>(set)); logger.trace("Downsample bin created, "+bin); } else { if (maskMap==null) maskMap = new HashMap<Integer,Reference<Object>>(3); maskMap.put(bin, new SoftReference<Object>(set)); logger.trace("Downsample mask bin created, "+bin); } return set; } finally { if (newBin) { // We fire a downsample event. fireDownsampleListeners(new DownSampleEvent(this, bin)); } } } protected void fireDownsampleListeners(DownSampleEvent evt) { if (downsampleListeners==null) return; for (IDownSampleListener l : downsampleListeners) l.downSampleChanged(evt); } @Override public int getBin() { return currentDownSampleBin; } /** * Add listener to be notifed if the dawnsampling changes. * @param l */ @Override public void addDownsampleListener(IDownSampleListener l) { if (downsampleListeners==null) downsampleListeners = new HashSet<IDownSampleListener>(7); downsampleListeners.add(l); } /** * Remove listener so that it is not notified. * @param l */ @Override public void removeDownsampleListener(IDownSampleListener l) { if (downsampleListeners==null) return; downsampleListeners.remove(l); } @Override public AbstractDataset getDownsampled() { return getDownsampled(getImage()); } public AbstractDataset getDownsampledMask() { if (getMask()==null) return null; return getDownsampled(getMask(), DownsampleMode.MINIMUM); } /** * Returns the bin for downsampling, either 1,2,4 or 8 currently. * This gives a pixel count of 1,4,16 or 64 for the bin. If 1 no * binning at all is done and no downsampling is being done, getDownsampled() * will return the AbstractDataset ok even if bin is one (no downsampling). * * @param slice * @param bounds * @return */ public int getDownsampleBin() { final XYRegionGraph graph = (XYRegionGraph)getXAxis().getParent(); final Rectangle realBounds = graph.getRegionArea().getBounds(); double rwidth = getSpan(getXAxis()); double rheight = getSpan(getYAxis()); int iwidth = realBounds.width; int iheight = realBounds.height; if (iwidth>(rwidth/2d) || iheight>(rheight/2d)) { return 1; } if (iwidth>(rwidth/4d) || iheight>(rheight/4d)) { return 2; } if (iwidth>(rwidth/8d) || iheight>(rheight/8d)) { return 4; } return 8; } private double getSpan(Axis axis) { final Range range = axis.getRange(); return Math.max(range.getUpper(),range.getLower()) - Math.min(range.getUpper(), range.getLower()); } private boolean lastAspectRatio = true; @Override protected void paintFigure(Graphics graphics) { super.paintFigure(graphics); /** * This is not actually needed except that when there * are a number of opens of an image, e.g. when moving * around an h5 gallery with arrow keys, it looks smooth * with this in. */ if (scaledImage==null || !isKeepAspectRatio() || lastAspectRatio!=isKeepAspectRatio()) { boolean imageReady = createScaledImage(ImageScaleType.NO_REIMAGE, null); if (!imageReady) return; lastAspectRatio = isKeepAspectRatio(); } graphics.pushState(); final XYRegionGraph graph = (XYRegionGraph)xAxis.getParent(); final Point loc = graph.getRegionArea().getLocation(); // Offsets and scaled image are calculated in the createScaledImage method. graphics.drawImage(scaledImage, loc.x-((int)xOffset), loc.y-((int)yOffset)); graphics.popState(); } private boolean isKeepAspectRatio() { return getXAxis().isKeepAspect() && getYAxis().isKeepAspect(); } public void remove() { if (mipMap!=null) mipMap.clear(); if (maskMap!=null) maskMap.clear(); if (scaledImage!=null) scaledImage.dispose(); if (paletteListeners!=null) paletteListeners.clear(); paletteListeners = null; if (downsampleListeners!=null) downsampleListeners.clear(); downsampleListeners = null; clearAspect(xAxis); clearAspect(yAxis); if (getParent()!=null) getParent().remove(this); xAxis.removeListener(this); yAxis.removeListener(this); xAxis.setTicksAtEnds(true); yAxis.setTicksAtEnds(true); xAxis.setTicksIndexBased(false); yAxis.setTicksIndexBased(false); axisRedrawActive = false; if (imageServiceBean!=null) imageServiceBean.dispose(); if (this.scaledImage!=null && !scaledImage.isDisposed()) scaledImage.dispose(); this.imageServiceBean = null; this.service = null; this.intensityScale = null; this.image = null; } public void dispose() { remove(); } private void clearAspect(Axis axis) { if (axis instanceof AspectAxis ) { AspectAxis aaxis = (AspectAxis)axis; aaxis.setKeepAspectWith(null); aaxis.setMaximumRange(null); } } @Override public IDataset getData() { return image; } /** * Create a slice of data from given ranges * @param xr * @param yr * @return */ private final AbstractDataset slice(Range xr, Range yr, final AbstractDataset data) { // Check that a slice needed, this speeds up the initial show of the image. final int[] shape = data.getShape(); final int[] imageRanges = getImageBounds(shape, getImageOrigin()); final int[] bounds = getBounds(xr, yr); if (imageRanges!=null && Arrays.equals(imageRanges, bounds)) { return data; } int[] xRange = getRange(bounds, shape[0], 0, false); int[] yRange = getRange(bounds, shape[1], 1, false); try { return data.getSlice(new int[]{xRange[0],yRange[0]}, new int[]{xRange[1],yRange[1]}, null); } catch (IllegalArgumentException iae) { logger.error("Cannot slice image", iae); return data; } } private static final int[] getRange(int[] bounds, int side, int index, boolean inverted) { int start = bounds[index]; if (inverted) start = side-start; int stop = bounds[2+index]; if (inverted) stop = side-stop; if (start>stop) { start = bounds[2+index]; if (inverted) start = side-start; stop = bounds[index]; if (inverted) stop = side-stop; } return new int[]{start, stop}; } private boolean axisRedrawActive = true; @Override public void axisRangeChanged(Axis axis, Range old_range, Range new_range) { createScaledImage(ImageScaleType.REIMAGE_ALLOWED, null); } /** * We do a bit here to ensure that * not too many calls to createScaledImage(...) are made. */ @Override public void axisRevalidated(Axis axis) { if (axis.isYAxis()) updateAxisRange(axis); } private void updateAxisRange(Axis axis) { if (!axisRedrawActive) return; createScaledImage(ImageScaleType.REIMAGE_ALLOWED, null); } private void setAxisRedrawActive(boolean b) { this.axisRedrawActive = b; } public void performAutoscale() { final int[] shape = image.getShape(); switch(getImageOrigin()) { case TOP_LEFT: xAxis.setRange(0, shape[1]); yAxis.setRange(shape[0], 0); break; case BOTTOM_LEFT: xAxis.setRange(0, shape[0]); yAxis.setRange(0, shape[1]); break; case BOTTOM_RIGHT: xAxis.setRange(shape[1], 0); yAxis.setRange(0, shape[0]); break; case TOP_RIGHT: xAxis.setRange(shape[0], 0); yAxis.setRange(shape[1], 0); break; } } private static final int[] getImageBounds(int[] shape, ImageOrigin origin) { if (origin==null) origin = ImageOrigin.TOP_LEFT; switch (origin) { case TOP_LEFT: return new int[] {0, shape[0], shape[1], 0}; case BOTTOM_LEFT: return new int[] {0, 0, shape[0], shape[1]}; case BOTTOM_RIGHT: return new int[] {shape[1], 0, 0, shape[0]}; case TOP_RIGHT: return new int[] {shape[0], shape[1], 0, 0}; } return null; } public void setImageOrigin(ImageOrigin imageOrigin) { if (this.mipMap!=null) mipMap.clear(); imageServiceBean.setOrigin(imageOrigin); createAxisBounds(); performAutoscale(); createScaledImage(ImageScaleType.FORCE_REIMAGE, null); repaint(); fireImageOriginListeners(); } /** * Creates new axis bounds, updates the label data set */ private void createAxisBounds() { final int[] shape = image.getShape(); if (getImageOrigin()==ImageOrigin.TOP_LEFT || getImageOrigin()==ImageOrigin.BOTTOM_RIGHT) { setupAxis(getXAxis(), new Range(0,shape[1]), axes!=null&&axes.size()>0 ? axes.get(0) : null); setupAxis(getYAxis(), new Range(0,shape[0]), axes!=null&&axes.size()>1 ? axes.get(1) : null); } else { setupAxis(getXAxis(), new Range(0,shape[0]), axes!=null&&axes.size()>1 ? axes.get(1) : null); setupAxis(getYAxis(), new Range(0,shape[1]), axes!=null&&axes.size()>0 ? axes.get(0) : null); } } private void setupAxis(Axis axis, Range bounds, IDataset labels) { ((AspectAxis)axis).setMaximumRange(bounds); ((AspectAxis)axis).setLabelDataAndTitle(labels); } @Override public ImageOrigin getImageOrigin() { if (imageServiceBean==null) return ImageOrigin.TOP_LEFT; return imageServiceBean.getOrigin(); } private boolean rescaleHistogram = true; public boolean isRescaleHistogram() { return rescaleHistogram; } @Override public void setRescaleHistogram(boolean rescaleHistogram) { this.rescaleHistogram = rescaleHistogram; } @Override public boolean setData(IDataset image, List<? extends IDataset> axes, boolean performAuto) { if (plottingSystem!=null) try { if (plottingSystem.getTraces().contains(this)) { final TraceWillPlotEvent evt = new TraceWillPlotEvent(this, false); evt.setImageData(image, axes); evt.setNewImageDataSet(false); plottingSystem.fireWillPlot(evt); if (!evt.doit) return false; if (evt.isNewImageDataSet()) { image = evt.getImage(); axes = evt.getAxes(); } } } catch (Throwable ignored) { // We allow things to proceed without a warning. } // The image is drawn low y to the top left but the axes are low y to the bottom right // We do not currently reflect it as it takes too long. Instead in the slice // method, we allow for the fact that the dataset is in a different orientation to // what is plotted. this.image = (AbstractDataset)image; if (this.mipMap!=null) mipMap.clear(); if (imageServiceBean==null) imageServiceBean = new ImageServiceBean(); imageServiceBean.setImage(image); if (service==null) service = (IImageService)PlatformUI.getWorkbench().getService(IImageService.class); if (rescaleHistogram) { final float[] fa = service.getFastStatistics(imageServiceBean); setMin(fa[0]); setMax(fa[1]); } setAxes(axes, performAuto); if (plottingSystem!=null) try { if (plottingSystem.getTraces().contains(this)) { plottingSystem.fireTraceUpdated(new TraceEvent(this)); } } catch (Throwable ignored) { // We allow things to proceed without a warning. } return true; } @SuppressWarnings("unchecked") @Override public void setAxes(List<? extends IDataset> axes, boolean performAuto) { this.axes = (List<IDataset>) axes; createAxisBounds(); if (performAuto) { try { setAxisRedrawActive(false); performAutoscale(); } finally { setAxisRedrawActive(true); } } else { createScaledImage(ImageScaleType.FORCE_REIMAGE, null); repaint(); } } public Number getMin() { return imageServiceBean.getMin(); } public void setMin(Number min) { if (imageServiceBean==null) return; imageServiceBean.setMin(min); try { intensityScale.setMin(min.doubleValue()); } catch (Exception e) { logger.error("Cannot set scale of intensity!",e); } fireMinDataListeners(); } public Number getMax() { return imageServiceBean.getMax(); } public void setMax(Number max) { if (imageServiceBean==null) return; imageServiceBean.setMax(max); try { intensityScale.setMax(max.doubleValue()); } catch (Exception e) { logger.error("Cannot set scale of intensity!",e); } fireMaxDataListeners(); } @Override public ImageServiceBean getImageServiceBean() { return imageServiceBean; } private Collection<IPaletteListener> paletteListeners; @Override public void addPaletteListener(IPaletteListener pl) { if (paletteListeners==null) paletteListeners = new HashSet<IPaletteListener>(11); paletteListeners.add(pl); } @Override public void removePaletteListener(IPaletteListener pl) { if (paletteListeners==null) return; paletteListeners.remove(pl); } private void firePaletteDataListeners(PaletteData paletteData) { if (paletteListeners==null) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); // Important do not let Mark get at it :) for (IPaletteListener pl : paletteListeners) pl.paletteChanged(evt); } private void fireMinDataListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.minChanged(evt); } private void fireMaxDataListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.maxChanged(evt); } private void fireMaxCutListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.maxCutChanged(evt); } private void fireMinCutListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.minCutChanged(evt); } private void fireNanBoundsListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.nanBoundsChanged(evt); } private void fireMaskListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.maskChanged(evt); } private void fireImageOriginListeners() { if (paletteListeners==null) return; if (!imageCreationAllowed) return; final PaletteEvent evt = new PaletteEvent(this, getPaletteData()); for (IPaletteListener pl : paletteListeners) pl.imageOriginChanged(evt); } @Override public DownsampleType getDownsampleType() { return downsampleType; } @Override public void setDownsampleType(DownsampleType type) { if (this.mipMap!=null) mipMap.clear(); if (this.maskMap!=null) maskMap.clear(); this.downsampleType = type; createScaledImage(ImageScaleType.FORCE_REIMAGE, null); getPreferenceStore().setValue(BasePlottingConstants.DOWNSAMPLE_PREF, type.getLabel()); repaint(); } private DownsampleMode getDownsampleTypeDiamond() { switch(getDownsampleType()) { case MEAN: return DownsampleMode.MEAN; case MAXIMUM: return DownsampleMode.MAXIMUM; case MINIMUM: return DownsampleMode.MINIMUM; case POINT: return DownsampleMode.POINT; } return DownsampleMode.MEAN; } @Override public void rehistogram() { if (imageServiceBean==null) return; imageServiceBean.setMax(null); imageServiceBean.setMin(null); createScaledImage(ImageScaleType.REHISTOGRAM, null); // Max and min changed in all likely-hood fireMaxDataListeners(); fireMinDataListeners(); repaint(); } @Override public List<IDataset> getAxes() { return (List<IDataset>) axes; } /** * return the HistoType being used * @return */ @Override public HistoType getHistoType() { if (imageServiceBean==null) return null; return imageServiceBean.getHistogramType(); } /** * Sets the histo type. */ @Override public boolean setHistoType(HistoType type) { if (imageServiceBean==null) return false; imageServiceBean.setHistogramType(type); getPreferenceStore().setValue(BasePlottingConstants.HISTO_PREF, type.getLabel()); boolean histoOk = createScaledImage(ImageScaleType.REHISTOGRAM, null); repaint(); return histoOk; } @Override public ITrace getTrace() { return this; } @Override public void setTrace(ITrace trace) { // Does nothing, you cannot change the trace, this is the trace. } public void setImageUpdateActive(boolean active) { this.imageCreationAllowed = active; if (active) { createScaledImage(ImageScaleType.FORCE_REIMAGE, null); repaint(); } firePaletteDataListeners(getPaletteData()); } @Override public HistogramBound getMinCut() { return imageServiceBean.getMinimumCutBound(); } @Override public void setMinCut(HistogramBound bound) { storeBound(bound, BasePlottingConstants.MIN_CUT); if (imageServiceBean==null) return; imageServiceBean.setMinimumCutBound(bound); fireMinCutListeners(); } private void storeBound(HistogramBound bound, String prop) { if (bound!=null) { getPreferenceStore().setValue(prop, bound.toString()); } else { getPreferenceStore().setValue(prop, ""); } } @Override public HistogramBound getMaxCut() { return imageServiceBean.getMaximumCutBound(); } @Override public void setMaxCut(HistogramBound bound) { storeBound(bound, BasePlottingConstants.MAX_CUT); if (imageServiceBean==null) return; imageServiceBean.setMaximumCutBound(bound); fireMaxCutListeners(); } @Override public HistogramBound getNanBound() { return imageServiceBean.getNanBound(); } @Override public void setNanBound(HistogramBound bound) { storeBound(bound, BasePlottingConstants.NAN_CUT); if (imageServiceBean==null) return; imageServiceBean.setNanBound(bound); fireNanBoundsListeners(); } private AbstractDataset fullMask; /** * The masking dataset of there is one, normally null. * @return */ public AbstractDataset getMask() { return fullMask; } /** * * @param bd */ public void setMask(IDataset mask) { if (mask!=null && image!=null && !image.isCompatibleWith(mask)) { BooleanDataset maskDataset = new BooleanDataset(image.getShape()); maskDataset.setName("mask"); maskDataset.fill(true); final int[] shape = mask.getShape(); for (int y = 0; y<shape[0]; ++y) { for (int x = 0; x<shape[1]; ++x) { try { // We only add the falses if (!mask.getBoolean(y,x)) { maskDataset.set(Boolean.FALSE, y,x); } } catch (Throwable ignored) { continue; } } } mask = maskDataset; } if (maskMap!=null) maskMap.clear(); fullMask = (AbstractDataset)mask; rehistogram(); fireMaskListeners(); } private boolean userTrace = true; @Override public boolean isUserTrace() { return userTrace; } @Override public void setUserTrace(boolean isUserTrace) { this.userTrace = isUserTrace; } public boolean isMaximumZoom() { return isMaximumZoom; } private Object userObject; public Object getUserObject() { return userObject; } public void setUserObject(Object userObject) { this.userObject = userObject; } /** * If the axis data set has been set, this method will return * a selection region in the coordinates of the axes labels rather * than the indices. * * Ellipse and Sector rois are not currently supported. * * @return ROI in label coordinates. This roi is not that useful after it * is created. The data processing needs rois with indices. */ @Override public IROI getRegionInAxisCoordinates(final IROI roi) throws Exception { if (!TraceUtils.isCustomAxes(this)) return roi; final AbstractDataset xl = (AbstractDataset)axes.get(0); // May be null final AbstractDataset yl = (AbstractDataset)axes.get(1); // May be null if (roi instanceof LinearROI) { double[] sp = ((LinearROI)roi).getPoint(); double[] ep = ((LinearROI)roi).getEndPoint(); transform(xl,0,sp,ep); transform(yl,1,sp,ep); return new LinearROI(sp, ep); } else if (roi instanceof PolylineROI) { PolylineROI proi = (PolylineROI)roi; final PolylineROI ret = (proi instanceof PolygonalROI) ? new PolygonalROI() : new PolylineROI(); for (PointROI pointROI : proi) { double[] dp = pointROI.getPoint(); transform(xl,0,dp); transform(yl,1,dp); ret.insertPoint(dp); } } else if (roi instanceof PointROI) { double[] dp = ((PointROI)roi).getPoint(); transform(xl,0,dp); transform(yl,1,dp); return new PointROI(dp); } else if (roi instanceof RectangularROI) { RectangularROI rroi = (RectangularROI)roi; double[] sp=roi.getPoint(); double[] ep=rroi.getEndPoint(); transform(xl,0,sp,ep); transform(yl,1,sp,ep); return new RectangularROI(sp[0], sp[1], ep[0]-sp[0], sp[1]-ep[1], rroi.getAngle()); } else { throw new Exception("Unsupported roi "+roi.getClass()); } return roi; } @Override public double[] getPointInAxisCoordinates(final double[] point) throws Exception { if (!TraceUtils.isCustomAxes(this)) return point; final AbstractDataset xl = (AbstractDataset)axes.get(0); // May be null final AbstractDataset yl = (AbstractDataset)axes.get(1); // May be null final double[] ret = point.clone(); transform(xl,0,ret); transform(yl,1,ret); return ret; } @Override public double[] getPointInImageCoordinates(final double[] axisLocation) throws Exception { if (!TraceUtils.isCustomAxes(this)) return axisLocation; final AbstractDataset xl = (AbstractDataset)axes.get(0); // May be null final AbstractDataset yl = (AbstractDataset)axes.get(1); // May be null final double xIndex = Double.isNaN(axisLocation[0]) ? Double.NaN : DatasetUtils.crossings(xl, axisLocation[0]).get(0); final double yIndex = Double.isNaN(axisLocation[1]) ? Double.NaN : DatasetUtils.crossings(yl, axisLocation[1]).get(0); return new double[]{xIndex, yIndex}; } private void transform(AbstractDataset label, int index, double[]... points) { if (label!=null) { for (double[] ds : points) { int dataIndex = (int)ds[index]; ds[index] = label.getDouble(dataIndex); } } } public AbstractPlottingSystem getPlottingSystem() { return plottingSystem; } public void setPlottingSystem(AbstractPlottingSystem plottingSystem) { this.plottingSystem = plottingSystem; } @Override public boolean isActive() { return getParent()!=null; } @Override public List<String> getAxesNames() { return Arrays.asList(xAxis.getTitle(), yAxis.getTitle()); } @Override public boolean is3DTrace() { return false; } }
false
true
private boolean createScaledImage(ImageScaleType rescaleType, final IProgressMonitor monitor) { if (!imageCreationAllowed) return false; boolean requireImageGeneration = imageData==null || rescaleType==ImageScaleType.FORCE_REIMAGE || rescaleType==ImageScaleType.REHISTOGRAM; // We know that it is needed // If we just changed downsample scale, we force the update. // This allows user resizes of the plot area to be picked up // and the larger data size used if it fits. if (!requireImageGeneration && rescaleType==ImageScaleType.REIMAGE_ALLOWED && currentDownSampleBin>0) { if (getDownsampleBin()!=currentDownSampleBin) { requireImageGeneration = true; } } final XYRegionGraph graph = (XYRegionGraph)getXAxis().getParent(); final Rectangle rbounds = graph.getRegionArea().getBounds(); if (rbounds.width<1 || rbounds.height<1) return false; if (!imageCreationAllowed) return false; if (monitor!=null && monitor.isCanceled()) return false; if (requireImageGeneration) { try { imageCreationAllowed = false; if (image==null) return false; AbstractDataset reducedFullImage = getDownsampled(image); imageServiceBean.setImage(reducedFullImage); imageServiceBean.setMonitor(monitor); if (fullMask!=null) { // For masks, we preserve the min (the falses) to avoid loosing fine lines // which are masked. imageServiceBean.setMask(getDownsampled(fullMask, DownsampleMode.MINIMUM)); } else { imageServiceBean.setMask(null); // Ensure we lose the mask! } if (rescaleType==ImageScaleType.REHISTOGRAM) { // Avoids changing colouring to // max and min of new selection. AbstractDataset slice = slice(getYAxis().getRange(), getXAxis().getRange(), (AbstractDataset)getData()); ImageServiceBean histoBean = imageServiceBean.clone(); histoBean.setImage(slice); if (fullMask!=null) histoBean.setMask(slice(getYAxis().getRange(), getXAxis().getRange(), fullMask)); float[] fa = service.getFastStatistics(histoBean); setMin(fa[0]); setMax(fa[1]); } this.imageData = service.getImageData(imageServiceBean); try { ImageServiceBean intensityScaleBean = imageServiceBean.clone(); // We send the image drawn with the same palette to the // intensityScale // TODO FIXME This will not work in log mode final DoubleDataset dds = new DoubleDataset(256,1); double inc = (getMax().doubleValue()-getMin().doubleValue())/256d; for (int i = 0; i < 256; i++) { double val = getMax().doubleValue()-(i*inc); dds.set(val, i, 0); } intensityScaleBean.setImage(dds); intensityScaleBean.setMask(null); intensityScale.setImageData(service.getImageData(intensityScaleBean)); intensityScale.setLog10(getImageServiceBean().isLogColorScale()); } catch (Throwable ne) { logger.warn("Cannot update intensity!"); } } catch (Exception e) { logger.error("Cannot create image from data!", e); } finally { imageCreationAllowed = true; } } if (monitor!=null && monitor.isCanceled()) return false; try { isMaximumZoom = false; if (imageData!=null && imageData.width==bounds.width && imageData.height==bounds.height) { // No slice, faster if (monitor!=null && monitor.isCanceled()) return false; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = new Image(Display.getDefault(), imageData); } else { // slice data to get current zoom area /** * x1,y1--------------x2,y2 * | | * | | * | | * x3,y3--------------x4,y4 */ ImageData data = imageData; ImageOrigin origin = getImageOrigin(); Range xRange = xAxis.getRange(); Range yRange = yAxis.getRange(); double minX = xRange.getLower()/currentDownSampleBin; double minY = yRange.getLower()/currentDownSampleBin; double maxX = xRange.getUpper()/currentDownSampleBin; double maxY = yRange.getUpper()/currentDownSampleBin; int xSize = imageData.width; int ySize = imageData.height; // check as getLower and getUpper don't work as expected if(maxX < minX){ double temp = maxX; maxX = minX; minX = temp; } if(maxY < minY){ double temp = maxY; maxY = minY; minY = temp; } double xSpread = maxX - minX; double ySpread = maxY - minY; double xScale = rbounds.width / xSpread; double yScale = rbounds.height / ySpread; // System.err.println("Area is " + rbounds + " with scale (x,y) " + xScale + ", " + yScale); // Deliberately get the over-sized dimensions so that the edge pixels can be smoothly panned through. int minXI = (int) Math.floor(minX); int minYI = (int) Math.floor(minY); int maxXI = (int) Math.ceil(maxX); int maxYI = (int) Math.ceil(maxY); int fullWidth = (int) (maxXI-minXI); int fullHeight = (int) (maxYI-minYI); // Force a minimum size on the system if (fullWidth <= MINIMUM_ZOOM_SIZE) { if (fullWidth > imageData.width) fullWidth = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } if (fullHeight <= MINIMUM_ZOOM_SIZE) { if (fullHeight > imageData.height) fullHeight = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } int scaleWidth = (int) (fullWidth*xScale); int scaleHeight = (int) (fullHeight*yScale); // System.err.println("Scaling to " + scaleWidth + "x" + scaleHeight); int xPix = (int)minX; int yPix = (int)minY; double xPixD = 0; double yPixD = 0; // These offsets are used when the scaled images is drawn to the screen. xOffset = (minX - Math.floor(minX))*xScale; yOffset = (minY - Math.floor(minY))*yScale; // Deal with the origin orientations correctly. switch (origin) { case TOP_LEFT: break; case TOP_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; break; case BOTTOM_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; case BOTTOM_LEFT: yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; } // Slice the data. // Pixel slice on downsampled data = fast! if (imageData.depth <= 8) { // NOTE Assumes 8-bit images final int size = fullWidth*fullHeight; final byte[] pixels = new byte[size]; for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, fullWidth*y); } data = new ImageData(fullWidth, fullHeight, data.depth, getPaletteData(), 1, pixels); } else { // NOTE Assumes 24 Bit Images final int[] pixels = new int[fullWidth]; data = new ImageData(fullWidth, fullHeight, 24, new PaletteData(0xff0000, 0x00ff00, 0x0000ff)); for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, 0); data.setPixels(0, y, fullWidth, pixels, 0); } } // create the scaled image // We suspicious if the algorithm wants to create an image // bigger than the screen size and in that case do not scale // Fix to http://jira.diamond.ac.uk/browse/SCI-926 boolean proceedWithScale = true; try { if (screenRectangle == null) { screenRectangle = Display.getCurrent().getPrimaryMonitor().getClientArea(); } if (scaleWidth>screenRectangle.width || scaleHeight>screenRectangle.height) { logger.error("Image scaling algorithm has malfunctioned and asked for an image bigger than the screen!"); logger.debug("scaleWidth="+scaleWidth); logger.debug("scaleHeight="+scaleHeight); proceedWithScale = false; } } catch (Throwable ne) { proceedWithScale = true; } if (proceedWithScale) { data = data!=null ? data.scaledTo(scaleWidth, scaleHeight) : null; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = data!=null ? new Image(Display.getDefault(), data) : null; } else if (scaledImage==null) { scaledImage = data!=null ? new Image(Display.getDefault(), data) : null; } } return true; } catch (IllegalArgumentException ie) { logger.error(ie.toString()); return false; } catch (java.lang.NegativeArraySizeException allowed) { return false; } catch (NullPointerException ne) { throw ne; } catch (Throwable ne) { logger.error("Image scale error!", ne); return false; } }
private boolean createScaledImage(ImageScaleType rescaleType, final IProgressMonitor monitor) { if (!imageCreationAllowed) return false; boolean requireImageGeneration = imageData==null || rescaleType==ImageScaleType.FORCE_REIMAGE || rescaleType==ImageScaleType.REHISTOGRAM; // We know that it is needed // If we just changed downsample scale, we force the update. // This allows user resizes of the plot area to be picked up // and the larger data size used if it fits. if (!requireImageGeneration && rescaleType==ImageScaleType.REIMAGE_ALLOWED && currentDownSampleBin>0) { if (getDownsampleBin()!=currentDownSampleBin) { requireImageGeneration = true; } } final XYRegionGraph graph = (XYRegionGraph)getXAxis().getParent(); final Rectangle rbounds = graph.getRegionArea().getBounds(); if (rbounds.width<1 || rbounds.height<1) return false; if (!imageCreationAllowed) return false; if (monitor!=null && monitor.isCanceled()) return false; if (requireImageGeneration) { try { imageCreationAllowed = false; if (image==null) return false; AbstractDataset reducedFullImage = getDownsampled(image); imageServiceBean.setImage(reducedFullImage); imageServiceBean.setMonitor(monitor); if (fullMask!=null) { // For masks, we preserve the min (the falses) to avoid loosing fine lines // which are masked. imageServiceBean.setMask(getDownsampled(fullMask, DownsampleMode.MINIMUM)); } else { imageServiceBean.setMask(null); // Ensure we lose the mask! } if (rescaleType==ImageScaleType.REHISTOGRAM) { // Avoids changing colouring to // max and min of new selection. AbstractDataset slice = slice(getYAxis().getRange(), getXAxis().getRange(), (AbstractDataset)getData()); ImageServiceBean histoBean = imageServiceBean.clone(); histoBean.setImage(slice); if (fullMask!=null) histoBean.setMask(slice(getYAxis().getRange(), getXAxis().getRange(), fullMask)); float[] fa = service.getFastStatistics(histoBean); setMin(fa[0]); setMax(fa[1]); } this.imageData = service.getImageData(imageServiceBean); try { ImageServiceBean intensityScaleBean = imageServiceBean.clone(); // We send the image drawn with the same palette to the // intensityScale // TODO FIXME This will not work in log mode final DoubleDataset dds = new DoubleDataset(256,1); double inc = (getMax().doubleValue()-getMin().doubleValue())/256d; for (int i = 0; i < 256; i++) { double val = getMax().doubleValue()-(i*inc); dds.set(val, i, 0); } intensityScaleBean.setImage(dds); intensityScaleBean.setMask(null); intensityScale.setImageData(service.getImageData(intensityScaleBean)); intensityScale.setLog10(getImageServiceBean().isLogColorScale()); } catch (Throwable ne) { logger.warn("Cannot update intensity!"); } } catch (Exception e) { logger.error("Cannot create image from data!", e); } finally { imageCreationAllowed = true; } } if (monitor!=null && monitor.isCanceled()) return false; try { isMaximumZoom = false; if (imageData!=null && imageData.width==bounds.width && imageData.height==bounds.height) { // No slice, faster if (monitor!=null && monitor.isCanceled()) return false; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = new Image(Display.getDefault(), imageData); } else { // slice data to get current zoom area /** * x1,y1--------------x2,y2 * | | * | | * | | * x3,y3--------------x4,y4 */ ImageData data = imageData; ImageOrigin origin = getImageOrigin(); Range xRange = xAxis.getRange(); Range yRange = yAxis.getRange(); double minX = xRange.getLower()/currentDownSampleBin; double minY = yRange.getLower()/currentDownSampleBin; double maxX = xRange.getUpper()/currentDownSampleBin; double maxY = yRange.getUpper()/currentDownSampleBin; int xSize = imageData.width; int ySize = imageData.height; // check as getLower and getUpper don't work as expected if(maxX < minX){ double temp = maxX; maxX = minX; minX = temp; } if(maxY < minY){ double temp = maxY; maxY = minY; minY = temp; } double xSpread = maxX - minX; double ySpread = maxY - minY; double xScale = rbounds.width / xSpread; double yScale = rbounds.height / ySpread; // System.err.println("Area is " + rbounds + " with scale (x,y) " + xScale + ", " + yScale); // Deliberately get the over-sized dimensions so that the edge pixels can be smoothly panned through. int minXI = (int) Math.floor(minX); int minYI = (int) Math.floor(minY); int maxXI = (int) Math.ceil(maxX); int maxYI = (int) Math.ceil(maxY); int fullWidth = (int) (maxXI-minXI); int fullHeight = (int) (maxYI-minYI); // Force a minimum size on the system if (fullWidth <= MINIMUM_ZOOM_SIZE) { if (fullWidth > imageData.width) fullWidth = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } if (fullHeight <= MINIMUM_ZOOM_SIZE) { if (fullHeight > imageData.height) fullHeight = MINIMUM_ZOOM_SIZE; isMaximumZoom = true; } int scaleWidth = (int) (fullWidth*xScale); int scaleHeight = (int) (fullHeight*yScale); // System.err.println("Scaling to " + scaleWidth + "x" + scaleHeight); int xPix = (int)minX; int yPix = (int)minY; double xPixD = 0; double yPixD = 0; // These offsets are used when the scaled images is drawn to the screen. xOffset = (minX - Math.floor(minX))*xScale; yOffset = (minY - Math.floor(minY))*yScale; // Deal with the origin orientations correctly. switch (origin) { case TOP_LEFT: break; case TOP_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; break; case BOTTOM_RIGHT: xPixD = xSize-maxX; xPix = (int) Math.floor(xPixD); xOffset = (xPixD - xPix)*xScale; yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; case BOTTOM_LEFT: yPixD = ySize-maxY; yPix = (int) Math.floor(yPixD); yOffset = (yPixD - yPix)*yScale; break; } // Slice the data. // Pixel slice on downsampled data = fast! if (imageData.depth <= 8) { // NOTE Assumes 8-bit images final int size = fullWidth*fullHeight; final byte[] pixels = new byte[size]; for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, fullWidth*y); } data = new ImageData(fullWidth, fullHeight, data.depth, getPaletteData(), 1, pixels); } else { // NOTE Assumes 24 Bit Images final int[] pixels = new int[fullWidth]; data = new ImageData(fullWidth, fullHeight, 24, new PaletteData(0xff0000, 0x00ff00, 0x0000ff)); for (int y = 0; y < fullHeight; y++) { imageData.getPixels(xPix, yPix+y, fullWidth, pixels, 0); data.setPixels(0, y, fullWidth, pixels, 0); } } // create the scaled image // We are suspicious if the algorithm wants to create an image // bigger than the screen size and in that case do not scale // Fix to http://jira.diamond.ac.uk/browse/SCI-926 boolean proceedWithScale = true; try { if (screenRectangle == null) { screenRectangle = Display.getCurrent().getPrimaryMonitor().getClientArea(); } if (scaleWidth>screenRectangle.width*2 || scaleHeight>screenRectangle.height*2) { logger.error("Image scaling algorithm has malfunctioned and asked for an image bigger than the screen!"); logger.debug("scaleWidth="+scaleWidth); logger.debug("scaleHeight="+scaleHeight); proceedWithScale = false; } } catch (Throwable ne) { proceedWithScale = true; } if (proceedWithScale) { data = data!=null ? data.scaledTo(scaleWidth, scaleHeight) : null; if (scaledImage!=null &&!scaledImage.isDisposed()) scaledImage.dispose(); // IMPORTANT scaledImage = data!=null ? new Image(Display.getDefault(), data) : null; } else if (scaledImage==null) { scaledImage = data!=null ? new Image(Display.getDefault(), data) : null; } } return true; } catch (IllegalArgumentException ie) { logger.error(ie.toString()); return false; } catch (java.lang.NegativeArraySizeException allowed) { return false; } catch (NullPointerException ne) { throw ne; } catch (Throwable ne) { logger.error("Image scale error!", ne); return false; } }
diff --git a/src/MRDriver.java b/src/MRDriver.java index ebcdfae..a271f54 100644 --- a/src/MRDriver.java +++ b/src/MRDriver.java @@ -1,325 +1,330 @@ /************************************************************************************************************************** * File: MRDriver.java * Authors: Justin A. DeBrabant ([email protected]) Matteo Riondato ([email protected]) * Last Modified: 12/27/2011 * Description: Driver for Hadoop implementation of parallel association rule mining. * Usage: java MRDriver <mapper id> <path to input database> <path to output local FIs> <path to output global FIs> * mapper id - specifies which Map method should be used 1 for partition mapper, 2 for binomial mapper, 3 for weighted coin flip sampler * path to input database - path to file containing transactions in .dat format (1 transaction per line) * local FI output - path to directory to write local (per-reducer) FIs * global FI output - path to directory to write global FIs (combined from all local FIs) ***************************************************************************************************************************/ import java.net.URI; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.util.Hashtable; import java.util.Random; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.filecache.DistributedCache; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DefaultStringifier; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.MapWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.lib.IdentityMapper; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.SequenceFileInputFormat; import org.apache.hadoop.mapred.SequenceFileOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class MRDriver extends Configured implements Tool { public final int MR_TIMEOUT_MILLI = 60000000; public static void main(String args[]) throws Exception { if (args.length != 11) { System.out.println("usage: java MRDriver <epsilon> <delta> <minFreqPercent> <d> <datasetSize> <numSamples> <phi> <mapper id> <path to input database> " + "<path to output local FIs> <path to output global FIs>"); System.exit(1); } int res = ToolRunner.run(new MRDriver(), args); System.exit(res); } public int run(String args[]) throws Exception { FileSystem fs = null; Path samplesMapPath = null; long job_start_time, job_end_time; long job_runtime; float epsilon = Float.parseFloat(args[0]); double delta = Double.parseDouble(args[1]); int minFreqPercent = Integer.parseInt(args[2]); int d = Integer.parseInt(args[3]); int datasetSize = Integer.parseInt(args[4]); int numSamples = Integer.parseInt(args[5]); double phi = Double.parseDouble(args[6]); Random rand; /************************ Job 1 (local FIM) Configuration ************************/ JobConf conf = new JobConf(getConf()); /* * Compute the number of required "votes" for an itemsets to be * declared frequent */ int reqApproxNum = reqApproxNum = (int) Math.floor(numSamples*(1-phi)-Math.sqrt(numSamples*(1-phi)*2*Math.log(1/delta)) + 1); int sampleSize = (int) Math.ceil((2 / Math.pow(epsilon, 2))*(d + Math.log(1/ phi))); conf.setInt("PARMM.reducersNum", numSamples); conf.setInt("PARMM.datasetSize", datasetSize); conf.setInt("PARMM.minFreqPercent", minFreqPercent); conf.setInt("PARMM.sampleSize", sampleSize); conf.setFloat("PARMM.epsilon", epsilon); // Set the number of reducers equal to the number of samples, to // maximize parallelism. Required by our Partitioner. conf.setNumReduceTasks(numSamples); // XXX: why do we disable the speculative execution? MR conf.setBoolean("mapred.reduce.tasks.speculative.execution", false); conf.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI); /* * Enable compression of map output. * * We do it for this job and not for the aggregation one because * each mapper there only print out one record for each itemset, * so there isn't much to compress, I'd say. MR * * XXX: We should use LZO compression because it's faster. We * should check whether it is the default for Amazon MapReduce. * MR */ conf.setBoolean("mapred.compress.map.output", true); conf.setJarByClass(MRDriver.class); conf.setMapOutputKeyClass(IntWritable.class); conf.setMapOutputValueClass(Text.class); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(DoubleWritable.class); conf.setInputFormat(SequenceFileInputFormat.class); // We write the collections found in a reducers as a SequenceFile conf.setOutputFormat(SequenceFileOutputFormat.class); SequenceFileOutputFormat.setOutputPath(conf, new Path(args[9])); // set the mapper class based on command line option switch(Integer.parseInt(args[7])) { case 1: System.out.println("running partition mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(PartitionMapper.class); break; case 2: System.out.println("running binomial mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(BinomialSamplerMapper.class); break; case 3: System.out.println("running coin mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(CoinFlipSamplerMapper.class); case 4: System.out.println("running sampler mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(InputSamplerMapper.class); // create a random sample of size T*m rand = new Random(); job_start_time = System.nanoTime(); int[] samples = new int[numSamples * sampleSize]; for (int i = 0; i < numSamples * sampleSize; i++) { samples[i] = rand.nextInt(datasetSize); } // for each key in the sample, create a list of all T samples to which this key belongs Hashtable<LongWritable, ArrayList<IntWritable>> hashTable = new Hashtable<LongWritable, ArrayList<IntWritable>>(); for (int i=0; i < numSamples * sampleSize; i++) { ArrayList<IntWritable> sampleIDs = null; LongWritable key = new LongWritable(samples[i]); if (hashTable.containsKey(key)) sampleIDs = hashTable.get(key); else sampleIDs = new ArrayList<IntWritable>(); sampleIDs.add(new IntWritable(i / sampleSize)); hashTable.put(key, sampleIDs); } /* * Convert the Hastable to a MapWritable which we will * write to HDFS and distribute to all Mappers using * DistributedCache */ MapWritable map = new MapWritable(); for (LongWritable key : hashTable.keySet()) { ArrayList<IntWritable> sampleIDs = hashTable.get(key); IntArrayWritable sampleIDsIAW = new IntArrayWritable(); sampleIDsIAW.set(sampleIDs.toArray(new IntWritable[sampleIDs.size()])); map.put(key, sampleIDsIAW); } fs = FileSystem.get(URI.create("samplesMap.ser"), conf); samplesMapPath = new Path("samplesMap.ser"); FSDataOutputStream out = fs.create(samplesMapPath, true); map.write(out); out.sync(); out.close(); DistributedCache.addCacheFile(new URI(fs.getWorkingDirectory() + "/samplesMap.ser#samplesMap.ser"), conf); // stop the sampling timer job_end_time = System.nanoTime(); job_runtime = (job_end_time-job_start_time) / 1000000; System.out.println("sampling runtime (milliseconds): " + job_runtime); break; // end switch case case 5: System.out.println("running random integer partition mapper..."); conf.setInputFormat(WholeSplitInputFormat.class); Path inputFilePath = new Path(args[8]); WholeSplitInputFormat.addInputPath(conf, inputFilePath); conf.setMapperClass(RandIntPartSamplerMapper.class); // Compute number of map tasks. // XXX I hope this is correct =) fs = inputFilePath.getFileSystem(conf); FileStatus inputFileStatus = fs.getFileStatus(inputFilePath); long len = inputFileStatus.getLen(); long blockSize = inputFileStatus.getBlockSize(); conf.setInt("mapred.min.split.size", (int) blockSize); int mapTasksNum = ((int) (len / blockSize)) + 1; // TODO 2) Extract random integer partition of total sample // size into up to mapTasksNum partitions. // XXX I'm not sure this is a correct way to do // it. rand = new Random(); int sum = 0; int i = 0; IntWritable[] toSampleArr = new IntWritable[mapTasksNum]; for (i = 0; i < mapTasksNum -1; i++) { int size = rand.nextInt(numSamples * sampleSize - sum); toSampleArr[i]= new IntWritable(size); sum += size; - if (sum >= numSamples * sampleSize) + if (sum > numSamples * sampleSize) + { + System.out.println("Something went wrong generating the sample Sizes"); + System.exit(1); + } + if (sum == numSamples * sampleSize) { break; } } if (i == mapTasksNum -1) { toSampleArr[i] = new IntWritable(numSamples * sampleSize - sum); } else { for (; i < mapTasksNum; i++) { toSampleArr[i] = new IntWritable(0); } } Collections.shuffle(Arrays.asList(toSampleArr)); DefaultStringifier.storeArray(conf, toSampleArr, "PARMM.toSampleArr"); break; default: System.err.println("Wrong Mapper ID. Can only be in [1,5]"); System.exit(1); break; } /* * We don't use the default hash partitioner because we want to * maximize the parallelism. That's why we also fix the number * of reducers. */ conf.setPartitionerClass(FIMPartitioner.class); conf.setReducerClass(FIMReducer.class); job_start_time = System.nanoTime(); JobClient.runJob(conf); job_end_time = System.nanoTime(); job_runtime = (job_end_time-job_start_time) / 1000000; System.out.println("local FIM runtime (milliseconds): " + job_runtime); /************************ Job 2 (aggregation) Configuration ************************/ JobConf confAggr = new JobConf(getConf()); confAggr.setInt("PARMM.reducersNum", numSamples); confAggr.setInt("PARMM.reqApproxNum", reqApproxNum); confAggr.setInt("PARMM.sampleSize", sampleSize); confAggr.setFloat("PARMM.epsilon", epsilon); // XXX: Why do we disable speculative execution? MR confAggr.setBoolean("mapred.reduce.tasks.speculative.execution", false); confAggr.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI); confAggr.setJarByClass(MRDriver.class); confAggr.setMapOutputKeyClass(Text.class); confAggr.setMapOutputValueClass(DoubleWritable.class); confAggr.setOutputKeyClass(Text.class); confAggr.setOutputValueClass(Text.class); confAggr.setMapperClass(IdentityMapper.class); confAggr.setReducerClass(AggregateReducer.class); confAggr.setInputFormat(SequenceFileInputFormat.class); SequenceFileInputFormat.addInputPath(confAggr, new Path(args[9])); FileOutputFormat.setOutputPath(confAggr, new Path(args[10])); job_start_time = System.nanoTime(); JobClient.runJob(confAggr); job_end_time = System.nanoTime(); job_runtime = (job_end_time-job_start_time) / 1000000; System.out.println("aggregation runtime (milliseconds): " + job_runtime); if (args[7].equals("4")) { // Remove samplesMap file fs.delete(samplesMapPath, false); } return 0; } }
true
true
public int run(String args[]) throws Exception { FileSystem fs = null; Path samplesMapPath = null; long job_start_time, job_end_time; long job_runtime; float epsilon = Float.parseFloat(args[0]); double delta = Double.parseDouble(args[1]); int minFreqPercent = Integer.parseInt(args[2]); int d = Integer.parseInt(args[3]); int datasetSize = Integer.parseInt(args[4]); int numSamples = Integer.parseInt(args[5]); double phi = Double.parseDouble(args[6]); Random rand; /************************ Job 1 (local FIM) Configuration ************************/ JobConf conf = new JobConf(getConf()); /* * Compute the number of required "votes" for an itemsets to be * declared frequent */ int reqApproxNum = reqApproxNum = (int) Math.floor(numSamples*(1-phi)-Math.sqrt(numSamples*(1-phi)*2*Math.log(1/delta)) + 1); int sampleSize = (int) Math.ceil((2 / Math.pow(epsilon, 2))*(d + Math.log(1/ phi))); conf.setInt("PARMM.reducersNum", numSamples); conf.setInt("PARMM.datasetSize", datasetSize); conf.setInt("PARMM.minFreqPercent", minFreqPercent); conf.setInt("PARMM.sampleSize", sampleSize); conf.setFloat("PARMM.epsilon", epsilon); // Set the number of reducers equal to the number of samples, to // maximize parallelism. Required by our Partitioner. conf.setNumReduceTasks(numSamples); // XXX: why do we disable the speculative execution? MR conf.setBoolean("mapred.reduce.tasks.speculative.execution", false); conf.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI); /* * Enable compression of map output. * * We do it for this job and not for the aggregation one because * each mapper there only print out one record for each itemset, * so there isn't much to compress, I'd say. MR * * XXX: We should use LZO compression because it's faster. We * should check whether it is the default for Amazon MapReduce. * MR */ conf.setBoolean("mapred.compress.map.output", true); conf.setJarByClass(MRDriver.class); conf.setMapOutputKeyClass(IntWritable.class); conf.setMapOutputValueClass(Text.class); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(DoubleWritable.class); conf.setInputFormat(SequenceFileInputFormat.class); // We write the collections found in a reducers as a SequenceFile conf.setOutputFormat(SequenceFileOutputFormat.class); SequenceFileOutputFormat.setOutputPath(conf, new Path(args[9])); // set the mapper class based on command line option switch(Integer.parseInt(args[7])) { case 1: System.out.println("running partition mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(PartitionMapper.class); break; case 2: System.out.println("running binomial mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(BinomialSamplerMapper.class); break; case 3: System.out.println("running coin mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(CoinFlipSamplerMapper.class); case 4: System.out.println("running sampler mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(InputSamplerMapper.class); // create a random sample of size T*m rand = new Random(); job_start_time = System.nanoTime(); int[] samples = new int[numSamples * sampleSize]; for (int i = 0; i < numSamples * sampleSize; i++) { samples[i] = rand.nextInt(datasetSize); } // for each key in the sample, create a list of all T samples to which this key belongs Hashtable<LongWritable, ArrayList<IntWritable>> hashTable = new Hashtable<LongWritable, ArrayList<IntWritable>>(); for (int i=0; i < numSamples * sampleSize; i++) { ArrayList<IntWritable> sampleIDs = null; LongWritable key = new LongWritable(samples[i]); if (hashTable.containsKey(key)) sampleIDs = hashTable.get(key); else sampleIDs = new ArrayList<IntWritable>(); sampleIDs.add(new IntWritable(i / sampleSize)); hashTable.put(key, sampleIDs); } /* * Convert the Hastable to a MapWritable which we will * write to HDFS and distribute to all Mappers using * DistributedCache */ MapWritable map = new MapWritable(); for (LongWritable key : hashTable.keySet()) { ArrayList<IntWritable> sampleIDs = hashTable.get(key); IntArrayWritable sampleIDsIAW = new IntArrayWritable(); sampleIDsIAW.set(sampleIDs.toArray(new IntWritable[sampleIDs.size()])); map.put(key, sampleIDsIAW); } fs = FileSystem.get(URI.create("samplesMap.ser"), conf); samplesMapPath = new Path("samplesMap.ser"); FSDataOutputStream out = fs.create(samplesMapPath, true); map.write(out); out.sync(); out.close(); DistributedCache.addCacheFile(new URI(fs.getWorkingDirectory() + "/samplesMap.ser#samplesMap.ser"), conf); // stop the sampling timer job_end_time = System.nanoTime(); job_runtime = (job_end_time-job_start_time) / 1000000; System.out.println("sampling runtime (milliseconds): " + job_runtime); break; // end switch case case 5: System.out.println("running random integer partition mapper..."); conf.setInputFormat(WholeSplitInputFormat.class); Path inputFilePath = new Path(args[8]); WholeSplitInputFormat.addInputPath(conf, inputFilePath); conf.setMapperClass(RandIntPartSamplerMapper.class); // Compute number of map tasks. // XXX I hope this is correct =) fs = inputFilePath.getFileSystem(conf); FileStatus inputFileStatus = fs.getFileStatus(inputFilePath); long len = inputFileStatus.getLen(); long blockSize = inputFileStatus.getBlockSize(); conf.setInt("mapred.min.split.size", (int) blockSize); int mapTasksNum = ((int) (len / blockSize)) + 1; // TODO 2) Extract random integer partition of total sample // size into up to mapTasksNum partitions. // XXX I'm not sure this is a correct way to do // it. rand = new Random(); int sum = 0; int i = 0; IntWritable[] toSampleArr = new IntWritable[mapTasksNum]; for (i = 0; i < mapTasksNum -1; i++) { int size = rand.nextInt(numSamples * sampleSize - sum); toSampleArr[i]= new IntWritable(size); sum += size; if (sum >= numSamples * sampleSize) { break; } } if (i == mapTasksNum -1) { toSampleArr[i] = new IntWritable(numSamples * sampleSize - sum); } else { for (; i < mapTasksNum; i++) { toSampleArr[i] = new IntWritable(0); } } Collections.shuffle(Arrays.asList(toSampleArr)); DefaultStringifier.storeArray(conf, toSampleArr, "PARMM.toSampleArr"); break; default: System.err.println("Wrong Mapper ID. Can only be in [1,5]"); System.exit(1); break; } /* * We don't use the default hash partitioner because we want to * maximize the parallelism. That's why we also fix the number * of reducers. */ conf.setPartitionerClass(FIMPartitioner.class); conf.setReducerClass(FIMReducer.class); job_start_time = System.nanoTime(); JobClient.runJob(conf); job_end_time = System.nanoTime(); job_runtime = (job_end_time-job_start_time) / 1000000; System.out.println("local FIM runtime (milliseconds): " + job_runtime); /************************ Job 2 (aggregation) Configuration ************************/ JobConf confAggr = new JobConf(getConf()); confAggr.setInt("PARMM.reducersNum", numSamples); confAggr.setInt("PARMM.reqApproxNum", reqApproxNum); confAggr.setInt("PARMM.sampleSize", sampleSize); confAggr.setFloat("PARMM.epsilon", epsilon); // XXX: Why do we disable speculative execution? MR confAggr.setBoolean("mapred.reduce.tasks.speculative.execution", false); confAggr.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI); confAggr.setJarByClass(MRDriver.class); confAggr.setMapOutputKeyClass(Text.class); confAggr.setMapOutputValueClass(DoubleWritable.class); confAggr.setOutputKeyClass(Text.class); confAggr.setOutputValueClass(Text.class); confAggr.setMapperClass(IdentityMapper.class); confAggr.setReducerClass(AggregateReducer.class); confAggr.setInputFormat(SequenceFileInputFormat.class); SequenceFileInputFormat.addInputPath(confAggr, new Path(args[9])); FileOutputFormat.setOutputPath(confAggr, new Path(args[10])); job_start_time = System.nanoTime(); JobClient.runJob(confAggr); job_end_time = System.nanoTime(); job_runtime = (job_end_time-job_start_time) / 1000000; System.out.println("aggregation runtime (milliseconds): " + job_runtime); if (args[7].equals("4")) { // Remove samplesMap file fs.delete(samplesMapPath, false); } return 0; }
public int run(String args[]) throws Exception { FileSystem fs = null; Path samplesMapPath = null; long job_start_time, job_end_time; long job_runtime; float epsilon = Float.parseFloat(args[0]); double delta = Double.parseDouble(args[1]); int minFreqPercent = Integer.parseInt(args[2]); int d = Integer.parseInt(args[3]); int datasetSize = Integer.parseInt(args[4]); int numSamples = Integer.parseInt(args[5]); double phi = Double.parseDouble(args[6]); Random rand; /************************ Job 1 (local FIM) Configuration ************************/ JobConf conf = new JobConf(getConf()); /* * Compute the number of required "votes" for an itemsets to be * declared frequent */ int reqApproxNum = reqApproxNum = (int) Math.floor(numSamples*(1-phi)-Math.sqrt(numSamples*(1-phi)*2*Math.log(1/delta)) + 1); int sampleSize = (int) Math.ceil((2 / Math.pow(epsilon, 2))*(d + Math.log(1/ phi))); conf.setInt("PARMM.reducersNum", numSamples); conf.setInt("PARMM.datasetSize", datasetSize); conf.setInt("PARMM.minFreqPercent", minFreqPercent); conf.setInt("PARMM.sampleSize", sampleSize); conf.setFloat("PARMM.epsilon", epsilon); // Set the number of reducers equal to the number of samples, to // maximize parallelism. Required by our Partitioner. conf.setNumReduceTasks(numSamples); // XXX: why do we disable the speculative execution? MR conf.setBoolean("mapred.reduce.tasks.speculative.execution", false); conf.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI); /* * Enable compression of map output. * * We do it for this job and not for the aggregation one because * each mapper there only print out one record for each itemset, * so there isn't much to compress, I'd say. MR * * XXX: We should use LZO compression because it's faster. We * should check whether it is the default for Amazon MapReduce. * MR */ conf.setBoolean("mapred.compress.map.output", true); conf.setJarByClass(MRDriver.class); conf.setMapOutputKeyClass(IntWritable.class); conf.setMapOutputValueClass(Text.class); conf.setOutputKeyClass(Text.class); conf.setOutputValueClass(DoubleWritable.class); conf.setInputFormat(SequenceFileInputFormat.class); // We write the collections found in a reducers as a SequenceFile conf.setOutputFormat(SequenceFileOutputFormat.class); SequenceFileOutputFormat.setOutputPath(conf, new Path(args[9])); // set the mapper class based on command line option switch(Integer.parseInt(args[7])) { case 1: System.out.println("running partition mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(PartitionMapper.class); break; case 2: System.out.println("running binomial mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(BinomialSamplerMapper.class); break; case 3: System.out.println("running coin mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(CoinFlipSamplerMapper.class); case 4: System.out.println("running sampler mapper..."); SequenceFileInputFormat.addInputPath(conf, new Path(args[8])); conf.setMapperClass(InputSamplerMapper.class); // create a random sample of size T*m rand = new Random(); job_start_time = System.nanoTime(); int[] samples = new int[numSamples * sampleSize]; for (int i = 0; i < numSamples * sampleSize; i++) { samples[i] = rand.nextInt(datasetSize); } // for each key in the sample, create a list of all T samples to which this key belongs Hashtable<LongWritable, ArrayList<IntWritable>> hashTable = new Hashtable<LongWritable, ArrayList<IntWritable>>(); for (int i=0; i < numSamples * sampleSize; i++) { ArrayList<IntWritable> sampleIDs = null; LongWritable key = new LongWritable(samples[i]); if (hashTable.containsKey(key)) sampleIDs = hashTable.get(key); else sampleIDs = new ArrayList<IntWritable>(); sampleIDs.add(new IntWritable(i / sampleSize)); hashTable.put(key, sampleIDs); } /* * Convert the Hastable to a MapWritable which we will * write to HDFS and distribute to all Mappers using * DistributedCache */ MapWritable map = new MapWritable(); for (LongWritable key : hashTable.keySet()) { ArrayList<IntWritable> sampleIDs = hashTable.get(key); IntArrayWritable sampleIDsIAW = new IntArrayWritable(); sampleIDsIAW.set(sampleIDs.toArray(new IntWritable[sampleIDs.size()])); map.put(key, sampleIDsIAW); } fs = FileSystem.get(URI.create("samplesMap.ser"), conf); samplesMapPath = new Path("samplesMap.ser"); FSDataOutputStream out = fs.create(samplesMapPath, true); map.write(out); out.sync(); out.close(); DistributedCache.addCacheFile(new URI(fs.getWorkingDirectory() + "/samplesMap.ser#samplesMap.ser"), conf); // stop the sampling timer job_end_time = System.nanoTime(); job_runtime = (job_end_time-job_start_time) / 1000000; System.out.println("sampling runtime (milliseconds): " + job_runtime); break; // end switch case case 5: System.out.println("running random integer partition mapper..."); conf.setInputFormat(WholeSplitInputFormat.class); Path inputFilePath = new Path(args[8]); WholeSplitInputFormat.addInputPath(conf, inputFilePath); conf.setMapperClass(RandIntPartSamplerMapper.class); // Compute number of map tasks. // XXX I hope this is correct =) fs = inputFilePath.getFileSystem(conf); FileStatus inputFileStatus = fs.getFileStatus(inputFilePath); long len = inputFileStatus.getLen(); long blockSize = inputFileStatus.getBlockSize(); conf.setInt("mapred.min.split.size", (int) blockSize); int mapTasksNum = ((int) (len / blockSize)) + 1; // TODO 2) Extract random integer partition of total sample // size into up to mapTasksNum partitions. // XXX I'm not sure this is a correct way to do // it. rand = new Random(); int sum = 0; int i = 0; IntWritable[] toSampleArr = new IntWritable[mapTasksNum]; for (i = 0; i < mapTasksNum -1; i++) { int size = rand.nextInt(numSamples * sampleSize - sum); toSampleArr[i]= new IntWritable(size); sum += size; if (sum > numSamples * sampleSize) { System.out.println("Something went wrong generating the sample Sizes"); System.exit(1); } if (sum == numSamples * sampleSize) { break; } } if (i == mapTasksNum -1) { toSampleArr[i] = new IntWritable(numSamples * sampleSize - sum); } else { for (; i < mapTasksNum; i++) { toSampleArr[i] = new IntWritable(0); } } Collections.shuffle(Arrays.asList(toSampleArr)); DefaultStringifier.storeArray(conf, toSampleArr, "PARMM.toSampleArr"); break; default: System.err.println("Wrong Mapper ID. Can only be in [1,5]"); System.exit(1); break; } /* * We don't use the default hash partitioner because we want to * maximize the parallelism. That's why we also fix the number * of reducers. */ conf.setPartitionerClass(FIMPartitioner.class); conf.setReducerClass(FIMReducer.class); job_start_time = System.nanoTime(); JobClient.runJob(conf); job_end_time = System.nanoTime(); job_runtime = (job_end_time-job_start_time) / 1000000; System.out.println("local FIM runtime (milliseconds): " + job_runtime); /************************ Job 2 (aggregation) Configuration ************************/ JobConf confAggr = new JobConf(getConf()); confAggr.setInt("PARMM.reducersNum", numSamples); confAggr.setInt("PARMM.reqApproxNum", reqApproxNum); confAggr.setInt("PARMM.sampleSize", sampleSize); confAggr.setFloat("PARMM.epsilon", epsilon); // XXX: Why do we disable speculative execution? MR confAggr.setBoolean("mapred.reduce.tasks.speculative.execution", false); confAggr.setInt("mapred.task.timeout", MR_TIMEOUT_MILLI); confAggr.setJarByClass(MRDriver.class); confAggr.setMapOutputKeyClass(Text.class); confAggr.setMapOutputValueClass(DoubleWritable.class); confAggr.setOutputKeyClass(Text.class); confAggr.setOutputValueClass(Text.class); confAggr.setMapperClass(IdentityMapper.class); confAggr.setReducerClass(AggregateReducer.class); confAggr.setInputFormat(SequenceFileInputFormat.class); SequenceFileInputFormat.addInputPath(confAggr, new Path(args[9])); FileOutputFormat.setOutputPath(confAggr, new Path(args[10])); job_start_time = System.nanoTime(); JobClient.runJob(confAggr); job_end_time = System.nanoTime(); job_runtime = (job_end_time-job_start_time) / 1000000; System.out.println("aggregation runtime (milliseconds): " + job_runtime); if (args[7].equals("4")) { // Remove samplesMap file fs.delete(samplesMapPath, false); } return 0; }
diff --git a/java/modules/core/src/test/java/org/apache/synapse/mediators/transform/FaultMediatorTest.java b/java/modules/core/src/test/java/org/apache/synapse/mediators/transform/FaultMediatorTest.java index 26bd72b37..34982aaa7 100644 --- a/java/modules/core/src/test/java/org/apache/synapse/mediators/transform/FaultMediatorTest.java +++ b/java/modules/core/src/test/java/org/apache/synapse/mediators/transform/FaultMediatorTest.java @@ -1,58 +1,58 @@ /* * 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.synapse.mediators.transform; import junit.framework.TestCase; import org.apache.axiom.soap.SOAPEnvelope; import org.apache.axiom.soap.SOAPFault; import org.apache.synapse.MessageContext; import org.apache.synapse.mediators.TestUtils; import javax.xml.namespace.QName; import java.net.URI; public class FaultMediatorTest extends TestCase { private static final QName F_CODE = new QName("http://namespace", "somefaultcode"); private static final String F_STRING = "Some fault string"; private static final String F_ACTOR_URI = "http://actor"; private static final String F_DETAIL = "Some detail text"; public void testSOAP11Fault() throws Exception { FaultMediator faultMediator = new FaultMediator(); faultMediator.setSoapVersion(FaultMediator.SOAP11); faultMediator.setFaultCodeValue(F_CODE); faultMediator.setFaultReasonValue(F_STRING); faultMediator.setFaultRole(new URI(F_ACTOR_URI)); faultMediator.setFaultDetail(F_DETAIL); // invoke transformation, with static enveope MessageContext synCtx = TestUtils.getTestContext("<empty/>"); faultMediator.mediate(synCtx); SOAPEnvelope envelope = synCtx.getEnvelope(); SOAPFault fault = envelope.getBody().getFault(); - assertTrue(F_CODE.equals(fault.getCode().getValue().getTextAsQName())); - assertTrue(F_STRING.equals(fault.getReason().getFirstSOAPText().getText())); + assertTrue(F_CODE.equals(fault.getCode().getTextAsQName())); + assertTrue(F_STRING.equals(fault.getReason().getText())); assertTrue(F_ACTOR_URI.equals(fault.getRole().getRoleValue())); assertTrue(F_DETAIL.equals(fault.getDetail().getText())); } }
true
true
public void testSOAP11Fault() throws Exception { FaultMediator faultMediator = new FaultMediator(); faultMediator.setSoapVersion(FaultMediator.SOAP11); faultMediator.setFaultCodeValue(F_CODE); faultMediator.setFaultReasonValue(F_STRING); faultMediator.setFaultRole(new URI(F_ACTOR_URI)); faultMediator.setFaultDetail(F_DETAIL); // invoke transformation, with static enveope MessageContext synCtx = TestUtils.getTestContext("<empty/>"); faultMediator.mediate(synCtx); SOAPEnvelope envelope = synCtx.getEnvelope(); SOAPFault fault = envelope.getBody().getFault(); assertTrue(F_CODE.equals(fault.getCode().getValue().getTextAsQName())); assertTrue(F_STRING.equals(fault.getReason().getFirstSOAPText().getText())); assertTrue(F_ACTOR_URI.equals(fault.getRole().getRoleValue())); assertTrue(F_DETAIL.equals(fault.getDetail().getText())); }
public void testSOAP11Fault() throws Exception { FaultMediator faultMediator = new FaultMediator(); faultMediator.setSoapVersion(FaultMediator.SOAP11); faultMediator.setFaultCodeValue(F_CODE); faultMediator.setFaultReasonValue(F_STRING); faultMediator.setFaultRole(new URI(F_ACTOR_URI)); faultMediator.setFaultDetail(F_DETAIL); // invoke transformation, with static enveope MessageContext synCtx = TestUtils.getTestContext("<empty/>"); faultMediator.mediate(synCtx); SOAPEnvelope envelope = synCtx.getEnvelope(); SOAPFault fault = envelope.getBody().getFault(); assertTrue(F_CODE.equals(fault.getCode().getTextAsQName())); assertTrue(F_STRING.equals(fault.getReason().getText())); assertTrue(F_ACTOR_URI.equals(fault.getRole().getRoleValue())); assertTrue(F_DETAIL.equals(fault.getDetail().getText())); }
diff --git a/grails/src/commons/grails/util/GenerateUtils.java b/grails/src/commons/grails/util/GenerateUtils.java index c02a39ed0..920ab9aa4 100644 --- a/grails/src/commons/grails/util/GenerateUtils.java +++ b/grails/src/commons/grails/util/GenerateUtils.java @@ -1,99 +1,99 @@ /* Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package grails.util; import groovy.lang.GroovyClassLoader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.groovy.grails.commons.DefaultGrailsApplication; import org.codehaus.groovy.grails.commons.GrailsApplication; import org.codehaus.groovy.grails.commons.GrailsDomainClass; import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator; import org.codehaus.groovy.grails.scaffolding.GrailsTemplateGenerator; import org.springframework.binding.support.Assert; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.mock.web.MockServletContext; /** * Utility class for generating Grails artifacts likes views, controllers etc. * * @author Graeme Rocher * @since 10-Feb-2006 */ public class GenerateUtils { private static Log LOG = LogFactory.getLog(RunTests.class); private static final String VIEWS = "view"; private static final String CONTROLLER = "controller"; private static final String ALL = "all"; public static void main(String[] args) throws Exception { if(args.length < 2) return; String type = args[0]; String domainClassName = args[1]; ApplicationContext parent = new ClassPathXmlApplicationContext("applicationContext.xml"); GrailsApplication application = (DefaultGrailsApplication)parent.getBean("grailsApplication", DefaultGrailsApplication.class); GrailsDomainClass domainClass = getDomainCallFromApplication(application,domainClassName); // bootstrap application to try hibernate domain classes if(domainClass == null) { GrailsRuntimeConfigurator config = new GrailsRuntimeConfigurator(application,parent); ConfigurableApplicationContext appCtx = (ConfigurableApplicationContext)config.configure(new MockServletContext()); Assert.notNull(appCtx); } // retry domainClass = getDomainCallFromApplication(application,domainClassName); if(domainClass == null) { LOG.debug("Unable to generate ["+type+"] domain class not found for name ["+domainClassName+"]"); return; } GroovyClassLoader gcl = new GroovyClassLoader(Thread.currentThread().getContextClassLoader()); GrailsTemplateGenerator generator = (GrailsTemplateGenerator)gcl.parseClass(gcl.getResourceAsStream("org/codehaus/groovy/grails/scaffolding/DefaultGrailsTemplateGenerator.groovy")) .newInstance(); if(VIEWS.equals(type) || ALL.equals(type)) { LOG.info("Generating views for domain class ["+domainClass.getName()+"]"); generator.generateViews(domainClass,"."); } - else if(CONTROLLER.equals(type)|| ALL.equals(type)) { + if(CONTROLLER.equals(type)|| ALL.equals(type)) { LOG.info("Generating controller for domain class ["+domainClass.getName()+"]"); generator.generateController(domainClass,"."); } else { LOG.info("Grails was unable to generate templates for unsupported type ["+type+"]"); } System.exit(0); } private static GrailsDomainClass getDomainCallFromApplication(GrailsApplication application, String domainClassName) { GrailsDomainClass domainClass = application.getGrailsDomainClass(domainClassName); if(domainClass == null) { domainClass = application.getGrailsDomainClass(domainClassName.substring(0,1).toUpperCase() + domainClassName.substring(1)); } return domainClass; } }
true
true
public static void main(String[] args) throws Exception { if(args.length < 2) return; String type = args[0]; String domainClassName = args[1]; ApplicationContext parent = new ClassPathXmlApplicationContext("applicationContext.xml"); GrailsApplication application = (DefaultGrailsApplication)parent.getBean("grailsApplication", DefaultGrailsApplication.class); GrailsDomainClass domainClass = getDomainCallFromApplication(application,domainClassName); // bootstrap application to try hibernate domain classes if(domainClass == null) { GrailsRuntimeConfigurator config = new GrailsRuntimeConfigurator(application,parent); ConfigurableApplicationContext appCtx = (ConfigurableApplicationContext)config.configure(new MockServletContext()); Assert.notNull(appCtx); } // retry domainClass = getDomainCallFromApplication(application,domainClassName); if(domainClass == null) { LOG.debug("Unable to generate ["+type+"] domain class not found for name ["+domainClassName+"]"); return; } GroovyClassLoader gcl = new GroovyClassLoader(Thread.currentThread().getContextClassLoader()); GrailsTemplateGenerator generator = (GrailsTemplateGenerator)gcl.parseClass(gcl.getResourceAsStream("org/codehaus/groovy/grails/scaffolding/DefaultGrailsTemplateGenerator.groovy")) .newInstance(); if(VIEWS.equals(type) || ALL.equals(type)) { LOG.info("Generating views for domain class ["+domainClass.getName()+"]"); generator.generateViews(domainClass,"."); } else if(CONTROLLER.equals(type)|| ALL.equals(type)) { LOG.info("Generating controller for domain class ["+domainClass.getName()+"]"); generator.generateController(domainClass,"."); } else { LOG.info("Grails was unable to generate templates for unsupported type ["+type+"]"); } System.exit(0); }
public static void main(String[] args) throws Exception { if(args.length < 2) return; String type = args[0]; String domainClassName = args[1]; ApplicationContext parent = new ClassPathXmlApplicationContext("applicationContext.xml"); GrailsApplication application = (DefaultGrailsApplication)parent.getBean("grailsApplication", DefaultGrailsApplication.class); GrailsDomainClass domainClass = getDomainCallFromApplication(application,domainClassName); // bootstrap application to try hibernate domain classes if(domainClass == null) { GrailsRuntimeConfigurator config = new GrailsRuntimeConfigurator(application,parent); ConfigurableApplicationContext appCtx = (ConfigurableApplicationContext)config.configure(new MockServletContext()); Assert.notNull(appCtx); } // retry domainClass = getDomainCallFromApplication(application,domainClassName); if(domainClass == null) { LOG.debug("Unable to generate ["+type+"] domain class not found for name ["+domainClassName+"]"); return; } GroovyClassLoader gcl = new GroovyClassLoader(Thread.currentThread().getContextClassLoader()); GrailsTemplateGenerator generator = (GrailsTemplateGenerator)gcl.parseClass(gcl.getResourceAsStream("org/codehaus/groovy/grails/scaffolding/DefaultGrailsTemplateGenerator.groovy")) .newInstance(); if(VIEWS.equals(type) || ALL.equals(type)) { LOG.info("Generating views for domain class ["+domainClass.getName()+"]"); generator.generateViews(domainClass,"."); } if(CONTROLLER.equals(type)|| ALL.equals(type)) { LOG.info("Generating controller for domain class ["+domainClass.getName()+"]"); generator.generateController(domainClass,"."); } else { LOG.info("Grails was unable to generate templates for unsupported type ["+type+"]"); } System.exit(0); }
diff --git a/src/fr/iutvalence/java/projet/spaceinvaders/MonstersBehaviorThread.java b/src/fr/iutvalence/java/projet/spaceinvaders/MonstersBehaviorThread.java index 0b15e30..4cdbf70 100644 --- a/src/fr/iutvalence/java/projet/spaceinvaders/MonstersBehaviorThread.java +++ b/src/fr/iutvalence/java/projet/spaceinvaders/MonstersBehaviorThread.java @@ -1,493 +1,493 @@ /** * */ package fr.iutvalence.java.projet.spaceinvaders; import java.util.Arrays; /** * This thread loop until the game finish. * It make invaders move and test collision beetween us and the tank. * * @author Gallet Guyon */ public class MonstersBehaviorThread extends Thread { //***************** Constant ************************* /** * This constant defines the default sleep time between each move of Invaders */ private static final int DEFAULT_SLEEP_TIME = 100; /** * This constant is the default acceleration * (Not used for now) */ private static final int DEFAULT_ACCELERATION = 2; /** * This constant defines the step X on the grid of a move */ private static final int DEFAULT_X_MOVE = 10; /** * This constant defines the step Y on the grid of a move */ private static final int DEFAULT_Y_MOVE = 10; /** * This constant defines the size of shoot */ private static final Coordinates DEFAULT_SIZE_SHOOT = new Coordinates(5,10); //***************** Variable ************************* // FIXME (QUEST) is that right? /** * This enumerate the state of invaders */ private enum Etat {/** * This is the first state, and invaders are left side on the grid */ LEFT1, /** * This is the second state, and invaders are right side on the grid */ RIGHT2, /** * This is the third state, and invaders are right side on the grid */ RIGHT3, /** * This is the fourth state, and invaders are left side on the grid */ LEFT4}; /** * This variable is the state of invaders */ private Etat etat; /** * This variable is used to wait sleepTime millisecond between each loop */ private int sleepTime; /** * Not implemented yet * It uses to accelerate sleepTime when invaders are less numerous */ private int acceleration; /** * A reference to monsters' tab in space invaders. * Array containing all monsters */ private Movable monsters[]; /** * A reference to tanks' tab in space invaders. * Array containing all tanks */ private Movable tanks[]; /** * A reference to shoots' tab in space invaders. * Array containing all shoots. */ private Movable[] shoots; /** * Reference to work boolean in SpaceInvaders class * Boolean to know if the game is finished */ private Boolean work; /** * The maximum size of the area */ private final Coordinates max; //***************** Constructors ************************* /** * This constructors set the variable needed by the thread. * @param nom Name of the Thread * @param sleepTime Number of millisecond between each move * @param acceleration Acceleration of sleepTime when less Invaders * @param monsters The table of monsters to move * @param tanks The table of tank to check collision * @param shoots The table of shoots to create new one * @param work The stop loop value * @param max The max coordinates of the screen */ public MonstersBehaviorThread(String nom, int sleepTime, int acceleration, Movable monsters[], Movable tanks[], Movable[] shoots, Boolean work, Coordinates max) { super(nom); this.sleepTime = sleepTime; this.acceleration = acceleration; this.monsters = monsters; this.tanks = tanks; this.shoots = shoots; this.work = work; this.max = max; this.etat = Etat.LEFT1; } /** * This constructors set the variable needed by the thread. * @param nom Name of the Thread * @param sleepTime Number of millisecond between each move * @param monsters The table of monsters to move * @param tanks The table of tank to check collision * @param shoots The table of shoots to create new one * @param work The stop loop value * @param max The max coordinates of the screen */ public MonstersBehaviorThread(String nom, int sleepTime, Movable monsters[], Movable tanks[], Movable[] shoots, Boolean work, Coordinates max) { super(nom); this.sleepTime = sleepTime; this.monsters = monsters; this.tanks = tanks; this.shoots = shoots; this.work = work; this.max = max; this.acceleration = DEFAULT_ACCELERATION; this.etat = Etat.LEFT1; } /** * This constructors set the variable needed by the thread. * @param nom Name of the Thread * @param monsters The table of monsters to move * @param tanks The table of tank to check collision * @param shoots The table of shoots to create new one * @param work The stop loop value * @param max The max coordinates of the screen */ public MonstersBehaviorThread(String nom, Movable monsters[], Movable tanks[], Movable[] shoots, Boolean work, Coordinates max) { super(nom); this.monsters = monsters; this.tanks = tanks; this.shoots = shoots; this.work = work; this.max = max; this.acceleration = DEFAULT_ACCELERATION; this.sleepTime = DEFAULT_SLEEP_TIME; this.etat = Etat.LEFT1; } //******************** Main *********************** /** * Main of the thread. * It calls move() then testCollision() every sleepTime millisecond. */ public void run() { // TODO remove Debug msg System.out.println("\nBegin MoveMonstersThread"); testCollision(); while(this.work.booleanValue()) { // TODO remove Debug msg System.out.println(Arrays.toString(this.monsters)); try { move(); } catch (OutOfGridException e1) { // Stop Game ? // No ^^, Kill him hahaha >< x) e1.kill(); System.out.println("OutOfGrid : " + e1.getOutOfGridException()); } testCollision(); shoot(); waitMonsters(); //TODO Remove debug //kill(); } // TODO remove Debug msg System.out.println("End MoveMonstersThread\n"); } //******************** Method *********************** // methote de test // TODO think to remove /** * Test for acceleration */ private void kill() { int i = 0, nbMonsters= this.monsters.length; while(i < nbMonsters && (!this.monsters[i].isAlive())) i++; this.monsters[i].setAlive(false); } /** * This method tests if there is any collisions in all table declared.<br/> * Collision are tested between each table and not between elements of the same table.<br/> * If a Tank is touched by an enemy, work is set to false and the game is stopped by the main iteration. */ private void testCollision() { int nbMonsters, nbTanks, i, j; nbTanks = this.tanks.length; nbMonsters = this.monsters.length; for(i=0;i < nbTanks; i++) { for(j=0; j < nbMonsters; j++) { if(this.monsters[j].isAlive()) { if(this.tanks[i].overlapping(this.monsters[j]) != null) { this.tanks[i].setAlive(false); this.monsters[j].setAlive(false); this.work = false; // TODO remove Debug msg System.out.println("Collision : " + this.tanks[i].overlapping(this.monsters[j])); } } } } } // FIXME (QUEST) Useless? /** * This method allows to move Invaders table of delta coordinates. * @param delta The delta coordinates to move Invaders * @throws OutOfGridException This method can return OutOfgridException if monsters does'nt be anymore in the grid. */ private void moveTab(Coordinates delta) throws OutOfGridException { int i, nbMonsters; nbMonsters = this.monsters.length; for(i=0; i < nbMonsters; i++) { try { if(this.monsters[i].getArea().getPosition().getX() + this.monsters[i].getArea().getSize().getX() + delta.getX() > this.max.getX() || this.monsters[i].getArea().getPosition().getY() + this.monsters[i].getArea().getSize().getY() + delta.getY() > this.max.getY() || this.monsters[i].getArea().getPosition().getX() + delta.getX()< 0 || this.monsters[i].getArea().getPosition().getY() + delta.getY() < 0) { // Kill when Y coordinates is less than 0? throw new OutOfGridException(this.monsters[i]); } this.monsters[i].move(delta); } catch (NegativeSizeException e) { System.out.println(e.getNegativeCoordinatesException()); System.out.println(this.monsters[i] + " " + delta); e.printStackTrace(); } } } /** * This method allows to move Invaders table of delta dx, dy. * @param dx The delta dx coordinates to move Invaders * @param dy The delta dy coordinates to move Invaders * @throws OutOfGridException This method can return OutOfgridException if monsters does'nt be anymore in the grid. */ private void moveTab(int dx, int dy) throws OutOfGridException { int i, nbMonsters; nbMonsters = this.monsters.length; for(i=0; i < nbMonsters; i++) { try { if(this.monsters[i].getArea().getPosition().getX() + this.monsters[i].getArea().getSize().getX() + dx > this.max.getX() || this.monsters[i].getArea().getPosition().getY() + this.monsters[i].getArea().getSize().getY() + dy > this.max.getY() || this.monsters[i].getArea().getPosition().getX() + dx < 0 || this.monsters[i].getArea().getPosition().getY() + dy < 0) { // Kill when Y coordinates is less than 0? throw new OutOfGridException(this.monsters[i]); } this.monsters[i].move(dx, dy); } catch (NegativeSizeException e) { System.out.println(e.getNegativeCoordinatesException()); System.out.println(this.monsters[i] + " " + new Coordinates(dx,dx)); e.printStackTrace(); } } } /** * This method allows to move Invaders once that is to say to right, down, or left. * It follow scheme by itself : * <ul> * <li>right</li> * <li>down</li> * <li>left</li> * <li>down</li> * <li>right</li> * </ul> * @throws OutOfGridException If Invaders are OutOfGrid then ther's exception. */ private void move() throws OutOfGridException { switch(this.etat) { case LEFT1: try { moveTab(DEFAULT_X_MOVE, 0); } catch (OutOfGridException e) { this.etat = Etat.RIGHT2; move(); } break; case RIGHT2: moveTab(0, -DEFAULT_Y_MOVE); this.etat = Etat.RIGHT3; break; case RIGHT3: try { moveTab(-DEFAULT_X_MOVE, 0); } catch (OutOfGridException e) { this.etat = Etat.LEFT4; move(); } break; case LEFT4: moveTab(0, -DEFAULT_Y_MOVE); this.etat = Etat.LEFT1; break; } } /** * This method count the number of alive Invaders. * @return The number of alive Invaders. */ private int countMonsters() { int nbInvaders = this.monsters.length, nbAlive = 0, i; for(i = 0; i < nbInvaders; i++) { if(this.monsters[i].isAlive()) nbAlive++; } // TODO is this go here? if(nbAlive == 0) // we stop game if there's no Invaders this.work = false; return nbAlive; } /** * This method wait a time in function of sleepTime value and of monster alive's number */ private void waitMonsters() { try { // expression is a.x type. Add a.x + c with c playable. It have to don't affect sleepTime Thread.sleep((long) (Math.sqrt(((double) countMonsters()/this.monsters.length)) * this.sleepTime)); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Method for shoot on tanks. * It search the invaders above tanks and shoot. */ private void shoot() { int nbMonsters = this.monsters.length; int nbTanks = this.tanks.length; int nbShoots = this.shoots.length; int i,j,k = 0, l = -1; Movable invaderAbove = null; for(i = 0; i < nbTanks; i++) { if(this.tanks[i].isAlive()) { for(j = nbMonsters - 1; j > 0 ; j--) { if(this.monsters[j].isAlive()) { - if((((this.monsters[j].getArea().getPosition().getX() + this.monsters[j].getArea().getSize().getX()) / 2) - (DEFAULT_SIZE_SHOOT.getX() / 2) < (this.tanks[i].getArea().getPosition().getX() + this.tanks[i].getArea().getSize().getX()) - && ((this.monsters[j].getArea().getPosition().getX() + this.monsters[j].getArea().getSize().getX()) / 2) - (DEFAULT_SIZE_SHOOT.getX() / 2) > (this.tanks[i].getArea().getPosition().getX())) - || (((this.monsters[j].getArea().getPosition().getX() + this.monsters[j].getArea().getSize().getX()) / 2) + (DEFAULT_SIZE_SHOOT.getX() / 2) < (this.tanks[i].getArea().getPosition().getX() + this.tanks[i].getArea().getSize().getX()) - && ((this.monsters[j].getArea().getPosition().getX() + this.monsters[j].getArea().getSize().getX()) / 2) + (DEFAULT_SIZE_SHOOT.getX() / 2) > (this.tanks[i].getArea().getPosition().getX()))) + if(((this.monsters[j].getArea().getPosition().getX() + (this.monsters[j].getArea().getSize().getX()) / 2) - (DEFAULT_SIZE_SHOOT.getX() / 2) < (this.tanks[i].getArea().getPosition().getX() + this.tanks[i].getArea().getSize().getX()) + && (this.monsters[j].getArea().getPosition().getX() + (this.monsters[j].getArea().getSize().getX()) / 2) - (DEFAULT_SIZE_SHOOT.getX() / 2) > (this.tanks[i].getArea().getPosition().getX())) + || ((this.monsters[j].getArea().getPosition().getX() + (this.monsters[j].getArea().getSize().getX()) / 2) + (DEFAULT_SIZE_SHOOT.getX() / 2) < (this.tanks[i].getArea().getPosition().getX() + this.tanks[i].getArea().getSize().getX()) + && (this.monsters[j].getArea().getPosition().getX() + (this.monsters[j].getArea().getSize().getX()) / 2) + (DEFAULT_SIZE_SHOOT.getX() / 2) > (this.tanks[i].getArea().getPosition().getX()))) { if(invaderAbove != null) { if(invaderAbove.getArea().getPosition().getY() > this.monsters[j].getArea().getPosition().getY()) { invaderAbove = this.monsters[j]; } } else invaderAbove = this.monsters[j]; } } } } if(invaderAbove != null) { // TODO Remove debug //invaderAbove = this.monsters[0]; System.out.println("Shoot is from : " + invaderAbove); try { // Search dead shoot while(k < nbShoots) { if(this.shoots[k] != null) { if(!this.shoots[k].isAlive()) l = k; } else { l = k; } k++; } if(l != -1) // TODO Add acceleration to shoot this.shoots[l] = invaderAbove.fire(-1, DEFAULT_SIZE_SHOOT); } catch (NegativeSizeException e) { e.printStackTrace(); System.out.println(e.getNegativeCoordinatesException()); } } } } }
true
true
private void shoot() { int nbMonsters = this.monsters.length; int nbTanks = this.tanks.length; int nbShoots = this.shoots.length; int i,j,k = 0, l = -1; Movable invaderAbove = null; for(i = 0; i < nbTanks; i++) { if(this.tanks[i].isAlive()) { for(j = nbMonsters - 1; j > 0 ; j--) { if(this.monsters[j].isAlive()) { if((((this.monsters[j].getArea().getPosition().getX() + this.monsters[j].getArea().getSize().getX()) / 2) - (DEFAULT_SIZE_SHOOT.getX() / 2) < (this.tanks[i].getArea().getPosition().getX() + this.tanks[i].getArea().getSize().getX()) && ((this.monsters[j].getArea().getPosition().getX() + this.monsters[j].getArea().getSize().getX()) / 2) - (DEFAULT_SIZE_SHOOT.getX() / 2) > (this.tanks[i].getArea().getPosition().getX())) || (((this.monsters[j].getArea().getPosition().getX() + this.monsters[j].getArea().getSize().getX()) / 2) + (DEFAULT_SIZE_SHOOT.getX() / 2) < (this.tanks[i].getArea().getPosition().getX() + this.tanks[i].getArea().getSize().getX()) && ((this.monsters[j].getArea().getPosition().getX() + this.monsters[j].getArea().getSize().getX()) / 2) + (DEFAULT_SIZE_SHOOT.getX() / 2) > (this.tanks[i].getArea().getPosition().getX()))) { if(invaderAbove != null) { if(invaderAbove.getArea().getPosition().getY() > this.monsters[j].getArea().getPosition().getY()) { invaderAbove = this.monsters[j]; } } else invaderAbove = this.monsters[j]; } } } } if(invaderAbove != null) { // TODO Remove debug //invaderAbove = this.monsters[0]; System.out.println("Shoot is from : " + invaderAbove); try { // Search dead shoot while(k < nbShoots) { if(this.shoots[k] != null) { if(!this.shoots[k].isAlive()) l = k; } else { l = k; } k++; } if(l != -1) // TODO Add acceleration to shoot this.shoots[l] = invaderAbove.fire(-1, DEFAULT_SIZE_SHOOT); } catch (NegativeSizeException e) { e.printStackTrace(); System.out.println(e.getNegativeCoordinatesException()); } } } }
private void shoot() { int nbMonsters = this.monsters.length; int nbTanks = this.tanks.length; int nbShoots = this.shoots.length; int i,j,k = 0, l = -1; Movable invaderAbove = null; for(i = 0; i < nbTanks; i++) { if(this.tanks[i].isAlive()) { for(j = nbMonsters - 1; j > 0 ; j--) { if(this.monsters[j].isAlive()) { if(((this.monsters[j].getArea().getPosition().getX() + (this.monsters[j].getArea().getSize().getX()) / 2) - (DEFAULT_SIZE_SHOOT.getX() / 2) < (this.tanks[i].getArea().getPosition().getX() + this.tanks[i].getArea().getSize().getX()) && (this.monsters[j].getArea().getPosition().getX() + (this.monsters[j].getArea().getSize().getX()) / 2) - (DEFAULT_SIZE_SHOOT.getX() / 2) > (this.tanks[i].getArea().getPosition().getX())) || ((this.monsters[j].getArea().getPosition().getX() + (this.monsters[j].getArea().getSize().getX()) / 2) + (DEFAULT_SIZE_SHOOT.getX() / 2) < (this.tanks[i].getArea().getPosition().getX() + this.tanks[i].getArea().getSize().getX()) && (this.monsters[j].getArea().getPosition().getX() + (this.monsters[j].getArea().getSize().getX()) / 2) + (DEFAULT_SIZE_SHOOT.getX() / 2) > (this.tanks[i].getArea().getPosition().getX()))) { if(invaderAbove != null) { if(invaderAbove.getArea().getPosition().getY() > this.monsters[j].getArea().getPosition().getY()) { invaderAbove = this.monsters[j]; } } else invaderAbove = this.monsters[j]; } } } } if(invaderAbove != null) { // TODO Remove debug //invaderAbove = this.monsters[0]; System.out.println("Shoot is from : " + invaderAbove); try { // Search dead shoot while(k < nbShoots) { if(this.shoots[k] != null) { if(!this.shoots[k].isAlive()) l = k; } else { l = k; } k++; } if(l != -1) // TODO Add acceleration to shoot this.shoots[l] = invaderAbove.fire(-1, DEFAULT_SIZE_SHOOT); } catch (NegativeSizeException e) { e.printStackTrace(); System.out.println(e.getNegativeCoordinatesException()); } } } }
diff --git a/src/info/ata4/unity/extract/handler/TextAssetHandler.java b/src/info/ata4/unity/extract/handler/TextAssetHandler.java index b74b7bc..cc80e11 100644 --- a/src/info/ata4/unity/extract/handler/TextAssetHandler.java +++ b/src/info/ata4/unity/extract/handler/TextAssetHandler.java @@ -1,38 +1,38 @@ /* ** 2013 July 01 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.unity.extract.handler; import info.ata4.unity.serdes.UnityObject; import info.ata4.unity.struct.ObjectPath; import java.io.IOException; /** * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class TextAssetHandler extends ExtractHandler { @Override public String getClassName() { return "TextAsset"; } @Override public String getFileExtension() { return "txt"; } @Override public void extract(ObjectPath path, UnityObject obj) throws IOException { String name = obj.getValue("m_Name"); String script = obj.getValue("m_Script"); - writeFile(script.getBytes(), path.pathID, name); + writeFile(script.getBytes("UTF8"), path.pathID, name); } }
true
true
public void extract(ObjectPath path, UnityObject obj) throws IOException { String name = obj.getValue("m_Name"); String script = obj.getValue("m_Script"); writeFile(script.getBytes(), path.pathID, name); }
public void extract(ObjectPath path, UnityObject obj) throws IOException { String name = obj.getValue("m_Name"); String script = obj.getValue("m_Script"); writeFile(script.getBytes("UTF8"), path.pathID, name); }
diff --git a/NoItem/src/net/worldoftomorrow/nala/ni/ArmourListener.java b/NoItem/src/net/worldoftomorrow/nala/ni/ArmourListener.java index 267d0ea..6fdd49d 100644 --- a/NoItem/src/net/worldoftomorrow/nala/ni/ArmourListener.java +++ b/NoItem/src/net/worldoftomorrow/nala/ni/ArmourListener.java @@ -1,52 +1,52 @@ package net.worldoftomorrow.nala.ni; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.inventory.InventoryType.SlotType; public class ArmourListener implements Listener { @EventHandler public void onArmourEquip(InventoryClickEvent event){ if(event.getInventory().getType().equals(InventoryType.CRAFTING)){ Player p = Bukkit.getPlayer(event.getWhoClicked().getName()); if(event.isShiftClick() ){ if (event.getCurrentItem() != null) { int iid = event.getCurrentItem().getTypeId(); if (Perms.NOWEAR.has(p, iid)) { event.setCancelled(true); - if (Configuration.notifyNoHold()) { + if (Configuration.notfiyNoWear()) { StringHelper.notifyPlayer(p, Configuration.noWearMessage(), iid); } if (Configuration.notifyAdmins()) { StringHelper.notifyAdmin(p, EventTypes.WEAR, event.getCurrentItem()); } } } } else { if (event.getSlotType().equals(SlotType.ARMOR)) { if (event.getCursor() != null) { int iid = event.getCursor().getTypeId(); if (Perms.NOWEAR.has(p, iid)) { - if (Configuration.notifyNoHold()) { + if (Configuration.notfiyNoWear()) { StringHelper.notifyPlayer(p, Configuration.noWearMessage(), iid); } if (Configuration.notifyAdmins()) { StringHelper.notifyAdmin(p, EventTypes.WEAR, event.getCursor()); } event.setCancelled(true); } } } } } } }
false
true
public void onArmourEquip(InventoryClickEvent event){ if(event.getInventory().getType().equals(InventoryType.CRAFTING)){ Player p = Bukkit.getPlayer(event.getWhoClicked().getName()); if(event.isShiftClick() ){ if (event.getCurrentItem() != null) { int iid = event.getCurrentItem().getTypeId(); if (Perms.NOWEAR.has(p, iid)) { event.setCancelled(true); if (Configuration.notifyNoHold()) { StringHelper.notifyPlayer(p, Configuration.noWearMessage(), iid); } if (Configuration.notifyAdmins()) { StringHelper.notifyAdmin(p, EventTypes.WEAR, event.getCurrentItem()); } } } } else { if (event.getSlotType().equals(SlotType.ARMOR)) { if (event.getCursor() != null) { int iid = event.getCursor().getTypeId(); if (Perms.NOWEAR.has(p, iid)) { if (Configuration.notifyNoHold()) { StringHelper.notifyPlayer(p, Configuration.noWearMessage(), iid); } if (Configuration.notifyAdmins()) { StringHelper.notifyAdmin(p, EventTypes.WEAR, event.getCursor()); } event.setCancelled(true); } } } } } }
public void onArmourEquip(InventoryClickEvent event){ if(event.getInventory().getType().equals(InventoryType.CRAFTING)){ Player p = Bukkit.getPlayer(event.getWhoClicked().getName()); if(event.isShiftClick() ){ if (event.getCurrentItem() != null) { int iid = event.getCurrentItem().getTypeId(); if (Perms.NOWEAR.has(p, iid)) { event.setCancelled(true); if (Configuration.notfiyNoWear()) { StringHelper.notifyPlayer(p, Configuration.noWearMessage(), iid); } if (Configuration.notifyAdmins()) { StringHelper.notifyAdmin(p, EventTypes.WEAR, event.getCurrentItem()); } } } } else { if (event.getSlotType().equals(SlotType.ARMOR)) { if (event.getCursor() != null) { int iid = event.getCursor().getTypeId(); if (Perms.NOWEAR.has(p, iid)) { if (Configuration.notfiyNoWear()) { StringHelper.notifyPlayer(p, Configuration.noWearMessage(), iid); } if (Configuration.notifyAdmins()) { StringHelper.notifyAdmin(p, EventTypes.WEAR, event.getCursor()); } event.setCancelled(true); } } } } } }
diff --git a/src/main/java/org/jinglenodes/credit/ChargeServiceProcessor.java b/src/main/java/org/jinglenodes/credit/ChargeServiceProcessor.java index aa1bcb4..b3180bb 100644 --- a/src/main/java/org/jinglenodes/credit/ChargeServiceProcessor.java +++ b/src/main/java/org/jinglenodes/credit/ChargeServiceProcessor.java @@ -1,165 +1,165 @@ /* * Copyright (C) 2011 - Jingle Nodes - Yuilop - Neppo * * This file is part of Switji (http://jinglenodes.org) * * Switji 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. * * Switji 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 MjSip; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author(s): * Benhur Langoni ([email protected]) * Thiago Camargo ([email protected]) */ package org.jinglenodes.credit; import org.apache.log4j.Logger; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Namespace; import org.dom4j.QName; import org.jinglenodes.prepare.NodeFormat; import org.jinglenodes.session.CallSession; import org.jinglenodes.session.CallSessionMapper; import org.xmpp.component.AbstractServiceProcessor; import org.xmpp.component.IqRequest; import org.xmpp.component.ServiceException; import org.xmpp.packet.IQ; import org.xmpp.packet.JID; import org.xmpp.tinder.JingleIQ; import org.zoolu.sip.message.JIDFactory; /** * Created by IntelliJ IDEA. * User: thiago * Date: 3/26/12 * Time: 1:54 PM */ public class ChargeServiceProcessor extends AbstractServiceProcessor { private final Logger log = Logger.getLogger(ChargeServiceProcessor.class); private final Element requestElement; private final String xmlns; private CallSessionMapper sessionMapper; private String chargeService; private NodeFormat nodeFormat; public ChargeServiceProcessor(final String elementName, final String xmlns) { this.xmlns = xmlns; this.requestElement = DocumentHelper.createElement(new QName(elementName, new Namespace("", xmlns))); } @Override public IQ createServiceRequest(Object object, String fromNode, String toNode) { if (object instanceof JingleIQ) { final JingleIQ jingleIQ = (JingleIQ) object; final CallSession session = sessionMapper.getSession(jingleIQ); if (session != null) { final SessionCredit credit = session.getSessionCredit(); if (credit != null && !credit.isCharged()) { toNode = nodeFormat.formatNode(toNode, fromNode); fromNode = nodeFormat.formatNode(fromNode, null); final JID to = JIDFactory.getInstance().getJID(null, chargeService, null); final JID from = JIDFactory.getInstance().getJID(fromNode, this.getComponentJID().getDomain(), null); final IQ request = new IQ(IQ.Type.set); request.setTo(to); request.setFrom(from); log.debug("SID: " + session.getId() + " Start: " + session.getStartTime() + "ms Finish: " + session.getFinishTime() + "ms"); final int callTime = session.getStartTime() == 0 ? 0 : (int) Math.ceil((session.getFinishTime() - session.getStartTime()) / 1000); final String toBareJid = JIDFactory.getInstance().getJID(toNode, chargeService, null).toBareJID(); final Element e = requestElement.createCopy(); e.addAttribute("initiator", from.toBareJID()); e.addAttribute("responder", toBareJid); e.addAttribute("seconds", String.valueOf(callTime)); - e.addAttribute("sid", session.getId()); + e.addAttribute("sid", jingleIQ.getJingle().getSid()); request.setChildElement(e); log.debug("createdCreditRequest: " + request.toXML()); credit.setCharged(true); return request; } else { log.error("No credit found for creating Charge"); } } else { log.error("No session found for creating Charge"); } } return null; } @Override protected String getRequestId(Object obj) { if (obj instanceof JingleIQ) { final JingleIQ iq = (JingleIQ) obj; return iq.getJingle().getSid(); } return null; } @Override protected void handleResult(IqRequest iq) { if (iq.getOriginalPacket() instanceof JingleIQ) { final CallSession session = sessionMapper.getSession((JingleIQ) iq.getOriginalPacket()); if (session != null) { final SessionCredit credit = session.getSessionCredit(); if (credit != null) { credit.setCharged(true); } } } } @Override protected void handleError(IqRequest iq) { log.error("Failed to Charge Account: " + iq.getResult().toXML()); } @Override protected void handleTimeout(IqRequest request) { try { queryService(request); } catch (ServiceException e) { log.error("Could NOT Retry Request: " + request.getRequest().toString(), e); } } @Override public String getNamespace() { return xmlns; } public String getChargeService() { return chargeService; } public void setChargeService(String chargeService) { this.chargeService = chargeService; } public CallSessionMapper getSessionMapper() { return sessionMapper; } public void setSessionMapper(CallSessionMapper sessionMapper) { this.sessionMapper = sessionMapper; } public NodeFormat getNodeFormat() { return nodeFormat; } public void setNodeFormat(NodeFormat nodeFormat) { this.nodeFormat = nodeFormat; } }
true
true
public IQ createServiceRequest(Object object, String fromNode, String toNode) { if (object instanceof JingleIQ) { final JingleIQ jingleIQ = (JingleIQ) object; final CallSession session = sessionMapper.getSession(jingleIQ); if (session != null) { final SessionCredit credit = session.getSessionCredit(); if (credit != null && !credit.isCharged()) { toNode = nodeFormat.formatNode(toNode, fromNode); fromNode = nodeFormat.formatNode(fromNode, null); final JID to = JIDFactory.getInstance().getJID(null, chargeService, null); final JID from = JIDFactory.getInstance().getJID(fromNode, this.getComponentJID().getDomain(), null); final IQ request = new IQ(IQ.Type.set); request.setTo(to); request.setFrom(from); log.debug("SID: " + session.getId() + " Start: " + session.getStartTime() + "ms Finish: " + session.getFinishTime() + "ms"); final int callTime = session.getStartTime() == 0 ? 0 : (int) Math.ceil((session.getFinishTime() - session.getStartTime()) / 1000); final String toBareJid = JIDFactory.getInstance().getJID(toNode, chargeService, null).toBareJID(); final Element e = requestElement.createCopy(); e.addAttribute("initiator", from.toBareJID()); e.addAttribute("responder", toBareJid); e.addAttribute("seconds", String.valueOf(callTime)); e.addAttribute("sid", session.getId()); request.setChildElement(e); log.debug("createdCreditRequest: " + request.toXML()); credit.setCharged(true); return request; } else { log.error("No credit found for creating Charge"); } } else { log.error("No session found for creating Charge"); } } return null; }
public IQ createServiceRequest(Object object, String fromNode, String toNode) { if (object instanceof JingleIQ) { final JingleIQ jingleIQ = (JingleIQ) object; final CallSession session = sessionMapper.getSession(jingleIQ); if (session != null) { final SessionCredit credit = session.getSessionCredit(); if (credit != null && !credit.isCharged()) { toNode = nodeFormat.formatNode(toNode, fromNode); fromNode = nodeFormat.formatNode(fromNode, null); final JID to = JIDFactory.getInstance().getJID(null, chargeService, null); final JID from = JIDFactory.getInstance().getJID(fromNode, this.getComponentJID().getDomain(), null); final IQ request = new IQ(IQ.Type.set); request.setTo(to); request.setFrom(from); log.debug("SID: " + session.getId() + " Start: " + session.getStartTime() + "ms Finish: " + session.getFinishTime() + "ms"); final int callTime = session.getStartTime() == 0 ? 0 : (int) Math.ceil((session.getFinishTime() - session.getStartTime()) / 1000); final String toBareJid = JIDFactory.getInstance().getJID(toNode, chargeService, null).toBareJID(); final Element e = requestElement.createCopy(); e.addAttribute("initiator", from.toBareJID()); e.addAttribute("responder", toBareJid); e.addAttribute("seconds", String.valueOf(callTime)); e.addAttribute("sid", jingleIQ.getJingle().getSid()); request.setChildElement(e); log.debug("createdCreditRequest: " + request.toXML()); credit.setCharged(true); return request; } else { log.error("No credit found for creating Charge"); } } else { log.error("No session found for creating Charge"); } } return null; }
diff --git a/metaobj-api/api/src/java/org/sakaiproject/metaobj/shared/mgt/HttpAccessBase.java b/metaobj-api/api/src/java/org/sakaiproject/metaobj/shared/mgt/HttpAccessBase.java index 6a09bb3..bcba933 100644 --- a/metaobj-api/api/src/java/org/sakaiproject/metaobj/shared/mgt/HttpAccessBase.java +++ b/metaobj-api/api/src/java/org/sakaiproject/metaobj/shared/mgt/HttpAccessBase.java @@ -1,65 +1,70 @@ /********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2005, 2006 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.metaobj.shared.mgt; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.sakaiproject.entity.api.EntityAccessOverloadException; import org.sakaiproject.entity.api.EntityCopyrightException; import org.sakaiproject.entity.api.EntityNotDefinedException; import org.sakaiproject.entity.api.EntityPermissionException; import org.sakaiproject.entity.api.EntityProducer; import org.sakaiproject.entity.api.HttpAccess; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.entity.cover.EntityManager; /** * Created by IntelliJ IDEA. * User: John Ellis * Date: Nov 7, 2005 * Time: 3:14:16 PM * To change this template use File | Settings | File Templates. */ public abstract class HttpAccessBase implements HttpAccess { public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref, Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException, EntityAccessOverloadException, EntityCopyrightException { ReferenceParser parser = createParser(ref); checkSource(ref, parser); ContentEntityWrapper wrapper = (ContentEntityWrapper) ref.getEntity(); - Reference realRef = EntityManager.newReference(wrapper.getBase().getReference()); - EntityProducer producer = realRef.getEntityProducer(); - producer.getHttpAccess().handleAccess(req, res, realRef, copyrightAcceptedRefs); + if (wrapper == null || wrapper.getBase() == null) { + throw new EntityNotDefinedException(ref.getReference()); + } + else { + Reference realRef = EntityManager.newReference(wrapper.getBase().getReference()); + EntityProducer producer = realRef.getEntityProducer(); + producer.getHttpAccess().handleAccess(req, res, realRef, copyrightAcceptedRefs); + } } protected ReferenceParser createParser(Reference ref) { return new ReferenceParser(ref.getReference(), ref.getEntityProducer()); } protected abstract void checkSource(Reference ref, ReferenceParser parser) throws EntityPermissionException, EntityNotDefinedException, EntityAccessOverloadException, EntityCopyrightException; }
true
true
public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref, Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException, EntityAccessOverloadException, EntityCopyrightException { ReferenceParser parser = createParser(ref); checkSource(ref, parser); ContentEntityWrapper wrapper = (ContentEntityWrapper) ref.getEntity(); Reference realRef = EntityManager.newReference(wrapper.getBase().getReference()); EntityProducer producer = realRef.getEntityProducer(); producer.getHttpAccess().handleAccess(req, res, realRef, copyrightAcceptedRefs); }
public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref, Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException, EntityAccessOverloadException, EntityCopyrightException { ReferenceParser parser = createParser(ref); checkSource(ref, parser); ContentEntityWrapper wrapper = (ContentEntityWrapper) ref.getEntity(); if (wrapper == null || wrapper.getBase() == null) { throw new EntityNotDefinedException(ref.getReference()); } else { Reference realRef = EntityManager.newReference(wrapper.getBase().getReference()); EntityProducer producer = realRef.getEntityProducer(); producer.getHttpAccess().handleAccess(req, res, realRef, copyrightAcceptedRefs); } }
diff --git a/obdalib/reformulation-core/src/main/java/it/unibz/krdb/obda/owlrefplatform/core/QuestOWL.java b/obdalib/reformulation-core/src/main/java/it/unibz/krdb/obda/owlrefplatform/core/QuestOWL.java index 48a5eca23..3c033ccb1 100644 --- a/obdalib/reformulation-core/src/main/java/it/unibz/krdb/obda/owlrefplatform/core/QuestOWL.java +++ b/obdalib/reformulation-core/src/main/java/it/unibz/krdb/obda/owlrefplatform/core/QuestOWL.java @@ -1,779 +1,779 @@ package it.unibz.krdb.obda.owlrefplatform.core; import it.unibz.krdb.obda.model.OBDADataFactory; import it.unibz.krdb.obda.model.OBDADataSource; import it.unibz.krdb.obda.model.OBDAMappingAxiom; import it.unibz.krdb.obda.model.OBDAModel; import it.unibz.krdb.obda.model.OBDAQueryReasoner; import it.unibz.krdb.obda.model.OBDAStatement; import it.unibz.krdb.obda.model.Predicate; import it.unibz.krdb.obda.model.impl.OBDADataFactoryImpl; import it.unibz.krdb.obda.model.impl.RDBMSourceParameterConstants; import it.unibz.krdb.obda.owlapi.OBDAOWLReasoner; import it.unibz.krdb.obda.owlapi.ReformulationPlatformPreferences; import it.unibz.krdb.obda.owlrefplatform.core.abox.RDBMSDataRepositoryManager; import it.unibz.krdb.obda.owlrefplatform.core.abox.RDBMSDirectDataRepositoryManager; import it.unibz.krdb.obda.owlrefplatform.core.abox.RDBMSSIRepositoryManager; import it.unibz.krdb.obda.owlrefplatform.core.abox.VirtualABoxMaterializer; import it.unibz.krdb.obda.owlrefplatform.core.abox.VirtualABoxMaterializer.VirtualTriplePredicateIterator; import it.unibz.krdb.obda.owlrefplatform.core.mappingprocessing.MappingVocabularyTranslator; import it.unibz.krdb.obda.owlrefplatform.core.ontology.Assertion; import it.unibz.krdb.obda.owlrefplatform.core.ontology.Axiom; import it.unibz.krdb.obda.owlrefplatform.core.ontology.Description; import it.unibz.krdb.obda.owlrefplatform.core.ontology.Ontology; import it.unibz.krdb.obda.owlrefplatform.core.ontology.OntologyFactory; import it.unibz.krdb.obda.owlrefplatform.core.ontology.imp.OntologyFactoryImpl; import it.unibz.krdb.obda.owlrefplatform.core.queryevaluation.EvaluationEngine; import it.unibz.krdb.obda.owlrefplatform.core.queryevaluation.JDBCEngine; import it.unibz.krdb.obda.owlrefplatform.core.queryevaluation.JDBCUtility; import it.unibz.krdb.obda.owlrefplatform.core.reformulation.DLRPerfectReformulator; import it.unibz.krdb.obda.owlrefplatform.core.reformulation.QueryRewriter; import it.unibz.krdb.obda.owlrefplatform.core.reformulation.QueryVocabularyValidator; import it.unibz.krdb.obda.owlrefplatform.core.reformulation.TreeRedReformulator; import it.unibz.krdb.obda.owlrefplatform.core.srcquerygeneration.ComplexMappingSQLGenerator; import it.unibz.krdb.obda.owlrefplatform.core.srcquerygeneration.SourceQueryGenerator; import it.unibz.krdb.obda.owlrefplatform.core.tboxprocessing.EquivalenceTBoxOptimizer; import it.unibz.krdb.obda.owlrefplatform.core.tboxprocessing.SigmaTBoxOptimizer; import it.unibz.krdb.obda.owlrefplatform.core.translator.OWLAPI2ABoxIterator; import it.unibz.krdb.obda.owlrefplatform.core.translator.OWLAPI2Translator; import it.unibz.krdb.obda.owlrefplatform.core.translator.OWLAPI2VocabularyExtractor; import it.unibz.krdb.obda.owlrefplatform.core.unfolding.ComplexMappingUnfolder; import it.unibz.krdb.obda.owlrefplatform.core.unfolding.UnfoldingMechanism; import it.unibz.krdb.obda.owlrefplatform.core.viewmanager.MappingViewManager; import java.net.URI; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.semanticweb.owl.inference.MonitorableOWLReasoner; import org.semanticweb.owl.inference.OWLReasonerException; import org.semanticweb.owl.model.OWLClass; import org.semanticweb.owl.model.OWLConstant; import org.semanticweb.owl.model.OWLDataProperty; import org.semanticweb.owl.model.OWLDataPropertyExpression; import org.semanticweb.owl.model.OWLDataRange; import org.semanticweb.owl.model.OWLDescription; import org.semanticweb.owl.model.OWLEntity; import org.semanticweb.owl.model.OWLIndividual; import org.semanticweb.owl.model.OWLObjectProperty; import org.semanticweb.owl.model.OWLObjectPropertyExpression; import org.semanticweb.owl.model.OWLOntology; import org.semanticweb.owl.model.OWLOntologyManager; import org.semanticweb.owl.util.NullProgressMonitor; import org.semanticweb.owl.util.ProgressMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The OBDAOWLReformulationPlatform implements the OWL reasoner interface and is * the implementation of the reasoning method in the reformulation project. */ public class QuestOWL implements OBDAOWLReasoner, OBDAQueryReasoner, MonitorableOWLReasoner { private static final String NOT_IMPLEMENTED_STR = "Service not available."; private OWLOntologyManager ontoManager = null; /* The merge and tranlsation of all loaded ontologies */ private Ontology translatedOntologyMerge = null; private TechniqueWrapper techwrapper = null; private HashSet<OWLOntology> loadedOntologies = null; private ProgressMonitor progressMonitor = new NullProgressMonitor(); private OBDAModel obdaModel = null; private Logger log = LoggerFactory.getLogger(QuestOWL.class); private boolean isClassified = false; private ReformulationPlatformPreferences preferences = null; private QueryVocabularyValidator validator = null; // private Ontology aboxDependencies = null; private Ontology reducedOntology = null; OWLAPI2VocabularyExtractor vext = new OWLAPI2VocabularyExtractor(); private OntologyFactory ofac = OntologyFactoryImpl.getInstance(); /*** * Optimization flags */ // private boolean optimizeEquivalences = true; private boolean optimizeSigma = true; public QuestOWL(OWLOntologyManager manager) { ontoManager = manager; } public Ontology getReducedOntology() { return reducedOntology; } public Ontology getABoxDependencies() { return null; } @Override public void loadOBDAModel(OBDAModel model) { isClassified = false; obdaModel = model; } public void loadDependencies(Ontology sigma) { techwrapper.loadDependencies(sigma); } /** * Set the technique wrapper which specifies which rewriting, unfolding and * evaluation techniques are used. * * @param newTechnique * the technique wrapper */ public void setTechniqueWrapper(TechniqueWrapper newTechnique) { techwrapper = newTechnique; } public TechniqueWrapper getTechniqueWrapper() { return techwrapper; } public void setPreferences(ReformulationPlatformPreferences preferences) { this.preferences = preferences; } @Override public OBDAStatement getStatement() throws Exception { if (techwrapper != null && isClassified == true) { return techwrapper.getStatement(); } else { throw new Exception( "Error, the technique wrapper has not been setup up yet. Make sure you have loaded the OWL Ontologies and the OBDA model, and classified before calling this method."); } } public boolean isConsistent(OWLOntology ontology) throws OWLReasonerException { return true; } public Ontology getOntology() { return this.translatedOntologyMerge; } public void classify() throws OWLReasonerException { getProgressMonitor().setIndeterminate(true); getProgressMonitor().setMessage("Classifying..."); getProgressMonitor().setStarted(); if (obdaModel == null) { throw new NullPointerException("APIController not set"); } if (preferences == null) { throw new NullPointerException("ReformulationPlatformPreferences not set"); } OBDADataFactory fac = OBDADataFactoryImpl.getInstance(); /*** * Duplicating the OBDA model to avoid strange behavior. */ String reformulationTechnique = (String) preferences.getCurrentValue(ReformulationPlatformPreferences.REFORMULATION_TECHNIQUE); boolean bOptimizeEquivalences = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.OPTIMIZE_EQUIVALENCES); boolean bUseInMemoryDB = preferences.getCurrentValue(ReformulationPlatformPreferences.DATA_LOCATION).equals(QuestConstants.INMEMORY); boolean bObtainFromOntology = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.OBTAIN_FROM_ONTOLOGY); boolean bObtainFromMappings = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.OBTAIN_FROM_MAPPINGS); String unfoldingMode = (String) preferences.getCurrentValue(ReformulationPlatformPreferences.ABOX_MODE); String dbType = (String) preferences.getCurrentValue(ReformulationPlatformPreferences.DBTYPE); // For testing purposes. boolean createMappings = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.CREATE_TEST_MAPPINGS); log.debug("Initializing Quest query answering engine..."); log.debug("Active preferences:"); log.debug("{} = {}", ReformulationPlatformPreferences.REFORMULATION_TECHNIQUE, reformulationTechnique); log.debug("{} = {}", ReformulationPlatformPreferences.OPTIMIZE_EQUIVALENCES, bOptimizeEquivalences); log.debug("{} = {}", ReformulationPlatformPreferences.DATA_LOCATION, bUseInMemoryDB); log.debug("{} = {}", ReformulationPlatformPreferences.OBTAIN_FROM_ONTOLOGY, bObtainFromOntology); log.debug("{} = {}", ReformulationPlatformPreferences.OBTAIN_FROM_MAPPINGS, bObtainFromMappings); log.debug("{} = {}", ReformulationPlatformPreferences.ABOX_MODE, unfoldingMode); log.debug("{} = {}", ReformulationPlatformPreferences.DBTYPE, dbType); log.debug("{} = {}", ReformulationPlatformPreferences.CREATE_TEST_MAPPINGS, createMappings); QueryRewriter rewriter = null; UnfoldingMechanism unfMech = null; SourceQueryGenerator gen = null; EvaluationEngine eval_engine; Ontology sigma = ofac.createOntology(URI.create("sigmaontology")); Ontology reformulationOntology = null; OBDAModel unfoldingOBDAModel = fac.getOBDAModel(); Map<Predicate, Description> equivalenceMaps = null; /* * PART 0: Simplifying the vocabulary of the ontology */ if (bOptimizeEquivalences) { log.debug("Equivalence optimization. Input ontology: {}", translatedOntologyMerge.toString()); EquivalenceTBoxOptimizer equiOptimizer = new EquivalenceTBoxOptimizer(translatedOntologyMerge); equiOptimizer.optimize(); /* This generates a new TBox with a simpler vocabulary */ reformulationOntology = equiOptimizer.getOptimalTBox(); /* * This is used to simplify the vocabulary of ABox assertions and * mappings */ equivalenceMaps = equiOptimizer.getEquivalenceMap(); - log.debug("Equivalence optimization. Output ontology: {}", translatedOntologyMerge.toString()); + log.debug("Equivalence optimization. Output ontology: {}", reformulationOntology.toString()); } else { reformulationOntology = translatedOntologyMerge; equivalenceMaps = new HashMap<Predicate, Description>(); } try { /* * Preparing the data source */ if (unfoldingMode.equals(QuestConstants.CLASSIC)) { log.debug("Working in classic mode"); if (bUseInMemoryDB || createMappings) { log.debug("Using in an memory database"); String driver = "org.h2.Driver"; String url = "jdbc:h2:mem:aboxdump" + System.currentTimeMillis(); String username = "sa"; String password = ""; OBDADataSource newsource = fac.getDataSource(URI.create("http://www.obda.org/ABOXDUMP" + System.currentTimeMillis())); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_DRIVER, driver); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_PASSWORD, password); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_URL, url); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_USERNAME, username); newsource.setParameter(RDBMSourceParameterConstants.IS_IN_MEMORY, "true"); newsource.setParameter(RDBMSourceParameterConstants.USE_DATASOURCE_FOR_ABOXDUMP, "true"); // this.translatedOntologyMerge.saturate(); RDBMSDataRepositoryManager dataRepository; // VocabularyExtractor extractor = new VocabularyExtractor(); // Set<Predicate> vocabulary = // extractor.getVocabulary(reformulationOntology); if (dbType.equals(QuestConstants.SEMANTIC)) { dataRepository = new RDBMSSIRepositoryManager(newsource, reformulationOntology.getVocabulary()); } else if (dbType.equals(QuestConstants.DIRECT)) { dataRepository = new RDBMSDirectDataRepositoryManager(newsource, reformulationOntology.getVocabulary()); } else { throw new Exception(dbType + " is unknown or not yet supported Data Base type. Currently only the direct db type is supported"); } dataRepository.setTBox(reformulationOntology); /* Creating the ABox repository */ getProgressMonitor().setMessage("Creating database schema..."); dataRepository.createDBSchema(true); dataRepository.insertMetadata(); if (bObtainFromOntology) { log.debug("Loading data from Ontology into the database"); OWLAPI2ABoxIterator aBoxIter = new OWLAPI2ABoxIterator(loadedOntologies, equivalenceMaps); dataRepository.insertData(aBoxIter); } if (bObtainFromMappings) { log.debug("Loading data from Mappings into the database"); VirtualABoxMaterializer materializer = new VirtualABoxMaterializer(obdaModel); Iterator<Assertion> assertionIter = materializer.getAssertionIterator(); dataRepository.insertData(assertionIter); } dataRepository.createIndexes(); /* Setting up the OBDA model */ unfoldingOBDAModel.addSource(newsource); unfoldingOBDAModel.addMappings(newsource.getSourceID(), dataRepository.getMappings()); for (Axiom axiom : dataRepository.getABoxDependencies().getAssertions()) { sigma.addEntities(axiom.getReferencedEntities()); sigma.addAssertion(axiom); } } } else if (unfoldingMode.equals(QuestConstants.VIRTUAL)) { log.debug("Working in virtual mode"); Collection<OBDADataSource> sources = this.obdaModel.getSources(); if (sources == null || sources.size() == 0) { throw new Exception("No datasource has been defined"); } else if (sources.size() > 1) { throw new Exception("Currently the reasoner can only handle one datasource"); } else { /* Setting up the OBDA model */ OBDADataSource ds = sources.iterator().next(); unfoldingOBDAModel.addSource(ds); /* * Processing mappings with respect to the vocabulary * simplification */ MappingVocabularyTranslator mtrans = new MappingVocabularyTranslator(); Collection<OBDAMappingAxiom> newMappings = mtrans.translateMappings(this.obdaModel.getMappings(ds.getSourceID()), equivalenceMaps); unfoldingOBDAModel.addMappings(ds.getSourceID(), newMappings); } } /* * Setting up the unfolder and SQL generation */ OBDADataSource datasource = unfoldingOBDAModel.getSources().get(0); // MappingValidator mappingValidator = new // MappingValidator(loadedOntologies); // boolean validmappings = // mappingValidator.validate(unfoldingOBDAModel.getMappings(datasource.getSourceID())); MappingViewManager viewMan = new MappingViewManager(unfoldingOBDAModel.getMappings(datasource.getSourceID())); unfMech = new ComplexMappingUnfolder(unfoldingOBDAModel.getMappings(datasource.getSourceID()), viewMan); JDBCUtility util = new JDBCUtility(datasource.getParameter(RDBMSourceParameterConstants.DATABASE_DRIVER)); gen = new ComplexMappingSQLGenerator(viewMan, util); log.debug("Setting up the connection;"); eval_engine = new JDBCEngine(unfoldingOBDAModel.getSources().get(0)); /* * Setting up the ontology we will use for the reformulation */ if (optimizeSigma) { SigmaTBoxOptimizer reducer = new SigmaTBoxOptimizer(reformulationOntology, sigma); reformulationOntology = reducer.getReducedOntology(); } /* * Setting up the reformulation engine */ if (QuestConstants.PERFECTREFORMULATION.equals(reformulationTechnique)) { rewriter = new DLRPerfectReformulator(); } else if (QuestConstants.UCQBASED.equals(reformulationTechnique)) { rewriter = new TreeRedReformulator(); } else { throw new IllegalArgumentException("Invalid value for argument: " + ReformulationPlatformPreferences.REFORMULATION_TECHNIQUE); } rewriter.setTBox(reformulationOntology); rewriter.setCBox(sigma); /* * Done, sending a new reasoner with the modules we just configured */ QueryVocabularyValidator validator = new QueryVocabularyValidator(reformulationOntology, equivalenceMaps); this.techwrapper = new QuestTechniqueWrapper(unfMech, rewriter, gen, validator, eval_engine, unfoldingOBDAModel); log.debug("... Quest has been setup and is ready for querying"); isClassified = true; } catch (Exception e) { log.error(e.getMessage(), e); OWLReasonerException ex = new OWLReasonerException(e.getMessage(), e) { }; e.fillInStackTrace(); throw ex; } finally { getProgressMonitor().setFinished(); } } public void clearOntologies() throws OWLReasonerException { if (loadedOntologies != null) { loadedOntologies.clear(); } translatedOntologyMerge = null; isClassified = false; } public void dispose() throws OWLReasonerException { techwrapper.dispose(); } public Set<OWLOntology> getLoadedOntologies() { return loadedOntologies; } public boolean isClassified() throws OWLReasonerException { return isClassified; } public boolean isDefined(OWLClass cls) throws OWLReasonerException { // TODO implement return true; } public boolean isDefined(OWLObjectProperty prop) throws OWLReasonerException { // TODO implement return true; } public boolean isDefined(OWLDataProperty prop) throws OWLReasonerException { // TODO implement return true; } public boolean isDefined(OWLIndividual ind) throws OWLReasonerException { return true; } public boolean isRealised() throws OWLReasonerException { return isClassified; } /*** * This method loads the given ontologies in the system. This will merge * these new ontologies with the existing ones in a set. Then it will * translate the assertions in all the ontologies into a single one, in our * internal representation. * * The translation is done using our OWLAPITranslator that gets the TBox * part of the ontologies and filters all the DL-Lite axioms (RDFS/OWL2QL * and DL-Lite). * * The original ontologies and the merged/translated ontology are kept and * are used later when classify() is called. * */ public void loadOntologies(Set<OWLOntology> ontologies) throws OWLReasonerException { /* * We will keep track of the loaded ontologies and tranlsate the TBox * part of them into our internal represntation */ URI uri = URI.create("http://it.unibz.krdb.obda/Quest/auxiliaryontology"); if (translatedOntologyMerge == null) { translatedOntologyMerge = ofac.createOntology(uri); } if (loadedOntologies == null) { loadedOntologies = new HashSet<OWLOntology>(); } log.debug("Load ontologies called. Translating ontologies."); OWLAPI2Translator translator = new OWLAPI2Translator(); Set<URI> uris = new HashSet<URI>(); Ontology translation = ofac.createOntology(uri); for (OWLOntology onto : ontologies) { uris.add(onto.getURI()); Ontology aux; try { aux = translator.translate(onto); } catch (Exception e) { throw new OWLReasonerException("Error translating ontology: " + onto.toString(), e) { }; } translation.addConcepts(aux.getConcepts()); translation.addRoles(aux.getRoles()); translation.addAssertions(aux.getAssertions()); } /* we translated successfully, now we append the new assertions */ this.loadedOntologies.addAll(ontologies); translatedOntologyMerge = translation; // translatedOntologyMerge.addAssertions(translation.getAssertions()); // translatedOntologyMerge.addConcepts(new // ArrayList<ClassDescription>(translation.getConcepts())); // translatedOntologyMerge.addRoles(new // ArrayList<Property>(translation.getRoles())); // translatedOntologyMerge.saturate(); log.debug("Ontology loaded: {}", translatedOntologyMerge); isClassified = false; } public void realise() throws OWLReasonerException { classify(); } public void unloadOntologies(Set<OWLOntology> ontologies) throws OWLReasonerException { boolean result = loadedOntologies.removeAll(ontologies); // if no ontologies where removed if (!result) return; // otherwise clear everything and update Set<OWLOntology> resultSet = new HashSet<OWLOntology>(); resultSet.addAll(loadedOntologies); clearOntologies(); loadOntologies(resultSet); } public Set<Set<OWLClass>> getAncestorClasses(OWLDescription clsC) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLClass>>(); } public Set<Set<OWLClass>> getDescendantClasses(OWLDescription clsC) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLClass>>(); } public Set<OWLClass> getEquivalentClasses(OWLDescription clsC) throws OWLReasonerException { // TODO implement owl return new HashSet<OWLClass>(); } public Set<OWLClass> getInconsistentClasses() throws OWLReasonerException { // TODO implement owl return new HashSet<OWLClass>(); } public Set<Set<OWLClass>> getSubClasses(OWLDescription clsC) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLClass>>(); } public Set<Set<OWLClass>> getSuperClasses(OWLDescription clsC) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLClass>>(); } public boolean isEquivalentClass(OWLDescription clsC, OWLDescription clsD) throws OWLReasonerException { // TODO implement owl return true; } public boolean isSubClassOf(OWLDescription clsC, OWLDescription clsD) throws OWLReasonerException { // TODO implement owl return true; } public boolean isSatisfiable(OWLDescription description) throws OWLReasonerException { // TODO implement owl return true; } public Map<OWLDataProperty, Set<OWLConstant>> getDataPropertyRelationships(OWLIndividual individual) throws OWLReasonerException { // TODO implement owl return new HashMap<OWLDataProperty, Set<OWLConstant>>(); } public Set<OWLIndividual> getIndividuals(OWLDescription clsC, boolean direct) throws OWLReasonerException { // TODO implement owl return new HashSet<OWLIndividual>(); } public Map<OWLObjectProperty, Set<OWLIndividual>> getObjectPropertyRelationships(OWLIndividual individual) throws OWLReasonerException { // TODO implement owl return new HashMap<OWLObjectProperty, Set<OWLIndividual>>(); } public Set<OWLIndividual> getRelatedIndividuals(OWLIndividual subject, OWLObjectPropertyExpression property) throws OWLReasonerException { // TODO implement owl return new HashSet<OWLIndividual>(); } public Set<OWLConstant> getRelatedValues(OWLIndividual subject, OWLDataPropertyExpression property) throws OWLReasonerException { // TODO implement owl return new HashSet<OWLConstant>(); } public Set<Set<OWLClass>> getTypes(OWLIndividual individual, boolean direct) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLClass>>(); } public boolean hasDataPropertyRelationship(OWLIndividual subject, OWLDataPropertyExpression property, OWLConstant object) throws OWLReasonerException { // TODO implement return false; } public boolean hasObjectPropertyRelationship(OWLIndividual subject, OWLObjectPropertyExpression property, OWLIndividual object) throws OWLReasonerException { // TODO implement return false; } public boolean hasType(OWLIndividual individual, OWLDescription type, boolean direct) throws OWLReasonerException { // TODO implement return false; } public Set<Set<OWLObjectProperty>> getAncestorProperties(OWLObjectProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLObjectProperty>>(); } public Set<Set<OWLDataProperty>> getAncestorProperties(OWLDataProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLDataProperty>>(); } public Set<Set<OWLObjectProperty>> getDescendantProperties(OWLObjectProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLObjectProperty>>(); } public Set<Set<OWLDataProperty>> getDescendantProperties(OWLDataProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLDataProperty>>(); } public Set<Set<OWLDescription>> getDomains(OWLObjectProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLDescription>>(); } public Set<Set<OWLDescription>> getDomains(OWLDataProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLDescription>>(); } public Set<OWLObjectProperty> getEquivalentProperties(OWLObjectProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<OWLObjectProperty>(); } public Set<OWLDataProperty> getEquivalentProperties(OWLDataProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<OWLDataProperty>(); } public Set<Set<OWLObjectProperty>> getInverseProperties(OWLObjectProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLObjectProperty>>(); } public Set<OWLDescription> getRanges(OWLObjectProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<OWLDescription>(); } public Set<OWLDataRange> getRanges(OWLDataProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<OWLDataRange>(); } public Set<Set<OWLObjectProperty>> getSubProperties(OWLObjectProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLObjectProperty>>(); } public Set<Set<OWLDataProperty>> getSubProperties(OWLDataProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLDataProperty>>(); } public Set<Set<OWLObjectProperty>> getSuperProperties(OWLObjectProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLObjectProperty>>(); } public Set<Set<OWLDataProperty>> getSuperProperties(OWLDataProperty property) throws OWLReasonerException { // TODO implement owl return new HashSet<Set<OWLDataProperty>>(); } public boolean isAntiSymmetric(OWLObjectProperty property) throws OWLReasonerException { // TODO implement owl return false; } public boolean isFunctional(OWLObjectProperty property) throws OWLReasonerException { return false; } public boolean isFunctional(OWLDataProperty property) throws OWLReasonerException { return false; } public boolean isInverseFunctional(OWLObjectProperty property) throws OWLReasonerException { return false; } public boolean isIrreflexive(OWLObjectProperty property) throws OWLReasonerException { return false; } public boolean isReflexive(OWLObjectProperty property) throws OWLReasonerException { return false; } public boolean isSymmetric(OWLObjectProperty property) throws OWLReasonerException { return false; } public boolean isTransitive(OWLObjectProperty property) throws OWLReasonerException { return false; } public OWLEntity getCurrentEntity() { return null; // return ontoManager.getOWLDataFactory().getOWLThing(); } /* The following methods need revision */ @Override public void setProgressMonitor(ProgressMonitor progressMonitor) { this.progressMonitor = progressMonitor; } private ProgressMonitor getProgressMonitor() { if (progressMonitor == null) { progressMonitor = new NullProgressMonitor(); } return progressMonitor; } @Override public void finishProgressMonitor() { getProgressMonitor().setFinished(); } @Override public void startProgressMonitor(String msg) { getProgressMonitor().setMessage(msg); getProgressMonitor().setIndeterminate(true); getProgressMonitor().setStarted(); } }
true
true
public void classify() throws OWLReasonerException { getProgressMonitor().setIndeterminate(true); getProgressMonitor().setMessage("Classifying..."); getProgressMonitor().setStarted(); if (obdaModel == null) { throw new NullPointerException("APIController not set"); } if (preferences == null) { throw new NullPointerException("ReformulationPlatformPreferences not set"); } OBDADataFactory fac = OBDADataFactoryImpl.getInstance(); /*** * Duplicating the OBDA model to avoid strange behavior. */ String reformulationTechnique = (String) preferences.getCurrentValue(ReformulationPlatformPreferences.REFORMULATION_TECHNIQUE); boolean bOptimizeEquivalences = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.OPTIMIZE_EQUIVALENCES); boolean bUseInMemoryDB = preferences.getCurrentValue(ReformulationPlatformPreferences.DATA_LOCATION).equals(QuestConstants.INMEMORY); boolean bObtainFromOntology = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.OBTAIN_FROM_ONTOLOGY); boolean bObtainFromMappings = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.OBTAIN_FROM_MAPPINGS); String unfoldingMode = (String) preferences.getCurrentValue(ReformulationPlatformPreferences.ABOX_MODE); String dbType = (String) preferences.getCurrentValue(ReformulationPlatformPreferences.DBTYPE); // For testing purposes. boolean createMappings = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.CREATE_TEST_MAPPINGS); log.debug("Initializing Quest query answering engine..."); log.debug("Active preferences:"); log.debug("{} = {}", ReformulationPlatformPreferences.REFORMULATION_TECHNIQUE, reformulationTechnique); log.debug("{} = {}", ReformulationPlatformPreferences.OPTIMIZE_EQUIVALENCES, bOptimizeEquivalences); log.debug("{} = {}", ReformulationPlatformPreferences.DATA_LOCATION, bUseInMemoryDB); log.debug("{} = {}", ReformulationPlatformPreferences.OBTAIN_FROM_ONTOLOGY, bObtainFromOntology); log.debug("{} = {}", ReformulationPlatformPreferences.OBTAIN_FROM_MAPPINGS, bObtainFromMappings); log.debug("{} = {}", ReformulationPlatformPreferences.ABOX_MODE, unfoldingMode); log.debug("{} = {}", ReformulationPlatformPreferences.DBTYPE, dbType); log.debug("{} = {}", ReformulationPlatformPreferences.CREATE_TEST_MAPPINGS, createMappings); QueryRewriter rewriter = null; UnfoldingMechanism unfMech = null; SourceQueryGenerator gen = null; EvaluationEngine eval_engine; Ontology sigma = ofac.createOntology(URI.create("sigmaontology")); Ontology reformulationOntology = null; OBDAModel unfoldingOBDAModel = fac.getOBDAModel(); Map<Predicate, Description> equivalenceMaps = null; /* * PART 0: Simplifying the vocabulary of the ontology */ if (bOptimizeEquivalences) { log.debug("Equivalence optimization. Input ontology: {}", translatedOntologyMerge.toString()); EquivalenceTBoxOptimizer equiOptimizer = new EquivalenceTBoxOptimizer(translatedOntologyMerge); equiOptimizer.optimize(); /* This generates a new TBox with a simpler vocabulary */ reformulationOntology = equiOptimizer.getOptimalTBox(); /* * This is used to simplify the vocabulary of ABox assertions and * mappings */ equivalenceMaps = equiOptimizer.getEquivalenceMap(); log.debug("Equivalence optimization. Output ontology: {}", translatedOntologyMerge.toString()); } else { reformulationOntology = translatedOntologyMerge; equivalenceMaps = new HashMap<Predicate, Description>(); } try { /* * Preparing the data source */ if (unfoldingMode.equals(QuestConstants.CLASSIC)) { log.debug("Working in classic mode"); if (bUseInMemoryDB || createMappings) { log.debug("Using in an memory database"); String driver = "org.h2.Driver"; String url = "jdbc:h2:mem:aboxdump" + System.currentTimeMillis(); String username = "sa"; String password = ""; OBDADataSource newsource = fac.getDataSource(URI.create("http://www.obda.org/ABOXDUMP" + System.currentTimeMillis())); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_DRIVER, driver); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_PASSWORD, password); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_URL, url); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_USERNAME, username); newsource.setParameter(RDBMSourceParameterConstants.IS_IN_MEMORY, "true"); newsource.setParameter(RDBMSourceParameterConstants.USE_DATASOURCE_FOR_ABOXDUMP, "true"); // this.translatedOntologyMerge.saturate(); RDBMSDataRepositoryManager dataRepository; // VocabularyExtractor extractor = new VocabularyExtractor(); // Set<Predicate> vocabulary = // extractor.getVocabulary(reformulationOntology); if (dbType.equals(QuestConstants.SEMANTIC)) { dataRepository = new RDBMSSIRepositoryManager(newsource, reformulationOntology.getVocabulary()); } else if (dbType.equals(QuestConstants.DIRECT)) { dataRepository = new RDBMSDirectDataRepositoryManager(newsource, reformulationOntology.getVocabulary()); } else { throw new Exception(dbType + " is unknown or not yet supported Data Base type. Currently only the direct db type is supported"); } dataRepository.setTBox(reformulationOntology); /* Creating the ABox repository */ getProgressMonitor().setMessage("Creating database schema..."); dataRepository.createDBSchema(true); dataRepository.insertMetadata(); if (bObtainFromOntology) { log.debug("Loading data from Ontology into the database"); OWLAPI2ABoxIterator aBoxIter = new OWLAPI2ABoxIterator(loadedOntologies, equivalenceMaps); dataRepository.insertData(aBoxIter); } if (bObtainFromMappings) { log.debug("Loading data from Mappings into the database"); VirtualABoxMaterializer materializer = new VirtualABoxMaterializer(obdaModel); Iterator<Assertion> assertionIter = materializer.getAssertionIterator(); dataRepository.insertData(assertionIter); } dataRepository.createIndexes(); /* Setting up the OBDA model */ unfoldingOBDAModel.addSource(newsource); unfoldingOBDAModel.addMappings(newsource.getSourceID(), dataRepository.getMappings()); for (Axiom axiom : dataRepository.getABoxDependencies().getAssertions()) { sigma.addEntities(axiom.getReferencedEntities()); sigma.addAssertion(axiom); } } } else if (unfoldingMode.equals(QuestConstants.VIRTUAL)) { log.debug("Working in virtual mode"); Collection<OBDADataSource> sources = this.obdaModel.getSources(); if (sources == null || sources.size() == 0) { throw new Exception("No datasource has been defined"); } else if (sources.size() > 1) { throw new Exception("Currently the reasoner can only handle one datasource"); } else { /* Setting up the OBDA model */ OBDADataSource ds = sources.iterator().next(); unfoldingOBDAModel.addSource(ds); /* * Processing mappings with respect to the vocabulary * simplification */ MappingVocabularyTranslator mtrans = new MappingVocabularyTranslator(); Collection<OBDAMappingAxiom> newMappings = mtrans.translateMappings(this.obdaModel.getMappings(ds.getSourceID()), equivalenceMaps); unfoldingOBDAModel.addMappings(ds.getSourceID(), newMappings); } } /* * Setting up the unfolder and SQL generation */ OBDADataSource datasource = unfoldingOBDAModel.getSources().get(0); // MappingValidator mappingValidator = new // MappingValidator(loadedOntologies); // boolean validmappings = // mappingValidator.validate(unfoldingOBDAModel.getMappings(datasource.getSourceID())); MappingViewManager viewMan = new MappingViewManager(unfoldingOBDAModel.getMappings(datasource.getSourceID())); unfMech = new ComplexMappingUnfolder(unfoldingOBDAModel.getMappings(datasource.getSourceID()), viewMan); JDBCUtility util = new JDBCUtility(datasource.getParameter(RDBMSourceParameterConstants.DATABASE_DRIVER)); gen = new ComplexMappingSQLGenerator(viewMan, util); log.debug("Setting up the connection;"); eval_engine = new JDBCEngine(unfoldingOBDAModel.getSources().get(0)); /* * Setting up the ontology we will use for the reformulation */ if (optimizeSigma) { SigmaTBoxOptimizer reducer = new SigmaTBoxOptimizer(reformulationOntology, sigma); reformulationOntology = reducer.getReducedOntology(); } /* * Setting up the reformulation engine */ if (QuestConstants.PERFECTREFORMULATION.equals(reformulationTechnique)) { rewriter = new DLRPerfectReformulator(); } else if (QuestConstants.UCQBASED.equals(reformulationTechnique)) { rewriter = new TreeRedReformulator(); } else { throw new IllegalArgumentException("Invalid value for argument: " + ReformulationPlatformPreferences.REFORMULATION_TECHNIQUE); } rewriter.setTBox(reformulationOntology); rewriter.setCBox(sigma); /* * Done, sending a new reasoner with the modules we just configured */ QueryVocabularyValidator validator = new QueryVocabularyValidator(reformulationOntology, equivalenceMaps); this.techwrapper = new QuestTechniqueWrapper(unfMech, rewriter, gen, validator, eval_engine, unfoldingOBDAModel); log.debug("... Quest has been setup and is ready for querying"); isClassified = true; } catch (Exception e) { log.error(e.getMessage(), e); OWLReasonerException ex = new OWLReasonerException(e.getMessage(), e) { }; e.fillInStackTrace(); throw ex; } finally { getProgressMonitor().setFinished(); } }
public void classify() throws OWLReasonerException { getProgressMonitor().setIndeterminate(true); getProgressMonitor().setMessage("Classifying..."); getProgressMonitor().setStarted(); if (obdaModel == null) { throw new NullPointerException("APIController not set"); } if (preferences == null) { throw new NullPointerException("ReformulationPlatformPreferences not set"); } OBDADataFactory fac = OBDADataFactoryImpl.getInstance(); /*** * Duplicating the OBDA model to avoid strange behavior. */ String reformulationTechnique = (String) preferences.getCurrentValue(ReformulationPlatformPreferences.REFORMULATION_TECHNIQUE); boolean bOptimizeEquivalences = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.OPTIMIZE_EQUIVALENCES); boolean bUseInMemoryDB = preferences.getCurrentValue(ReformulationPlatformPreferences.DATA_LOCATION).equals(QuestConstants.INMEMORY); boolean bObtainFromOntology = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.OBTAIN_FROM_ONTOLOGY); boolean bObtainFromMappings = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.OBTAIN_FROM_MAPPINGS); String unfoldingMode = (String) preferences.getCurrentValue(ReformulationPlatformPreferences.ABOX_MODE); String dbType = (String) preferences.getCurrentValue(ReformulationPlatformPreferences.DBTYPE); // For testing purposes. boolean createMappings = preferences.getCurrentBooleanValueFor(ReformulationPlatformPreferences.CREATE_TEST_MAPPINGS); log.debug("Initializing Quest query answering engine..."); log.debug("Active preferences:"); log.debug("{} = {}", ReformulationPlatformPreferences.REFORMULATION_TECHNIQUE, reformulationTechnique); log.debug("{} = {}", ReformulationPlatformPreferences.OPTIMIZE_EQUIVALENCES, bOptimizeEquivalences); log.debug("{} = {}", ReformulationPlatformPreferences.DATA_LOCATION, bUseInMemoryDB); log.debug("{} = {}", ReformulationPlatformPreferences.OBTAIN_FROM_ONTOLOGY, bObtainFromOntology); log.debug("{} = {}", ReformulationPlatformPreferences.OBTAIN_FROM_MAPPINGS, bObtainFromMappings); log.debug("{} = {}", ReformulationPlatformPreferences.ABOX_MODE, unfoldingMode); log.debug("{} = {}", ReformulationPlatformPreferences.DBTYPE, dbType); log.debug("{} = {}", ReformulationPlatformPreferences.CREATE_TEST_MAPPINGS, createMappings); QueryRewriter rewriter = null; UnfoldingMechanism unfMech = null; SourceQueryGenerator gen = null; EvaluationEngine eval_engine; Ontology sigma = ofac.createOntology(URI.create("sigmaontology")); Ontology reformulationOntology = null; OBDAModel unfoldingOBDAModel = fac.getOBDAModel(); Map<Predicate, Description> equivalenceMaps = null; /* * PART 0: Simplifying the vocabulary of the ontology */ if (bOptimizeEquivalences) { log.debug("Equivalence optimization. Input ontology: {}", translatedOntologyMerge.toString()); EquivalenceTBoxOptimizer equiOptimizer = new EquivalenceTBoxOptimizer(translatedOntologyMerge); equiOptimizer.optimize(); /* This generates a new TBox with a simpler vocabulary */ reformulationOntology = equiOptimizer.getOptimalTBox(); /* * This is used to simplify the vocabulary of ABox assertions and * mappings */ equivalenceMaps = equiOptimizer.getEquivalenceMap(); log.debug("Equivalence optimization. Output ontology: {}", reformulationOntology.toString()); } else { reformulationOntology = translatedOntologyMerge; equivalenceMaps = new HashMap<Predicate, Description>(); } try { /* * Preparing the data source */ if (unfoldingMode.equals(QuestConstants.CLASSIC)) { log.debug("Working in classic mode"); if (bUseInMemoryDB || createMappings) { log.debug("Using in an memory database"); String driver = "org.h2.Driver"; String url = "jdbc:h2:mem:aboxdump" + System.currentTimeMillis(); String username = "sa"; String password = ""; OBDADataSource newsource = fac.getDataSource(URI.create("http://www.obda.org/ABOXDUMP" + System.currentTimeMillis())); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_DRIVER, driver); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_PASSWORD, password); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_URL, url); newsource.setParameter(RDBMSourceParameterConstants.DATABASE_USERNAME, username); newsource.setParameter(RDBMSourceParameterConstants.IS_IN_MEMORY, "true"); newsource.setParameter(RDBMSourceParameterConstants.USE_DATASOURCE_FOR_ABOXDUMP, "true"); // this.translatedOntologyMerge.saturate(); RDBMSDataRepositoryManager dataRepository; // VocabularyExtractor extractor = new VocabularyExtractor(); // Set<Predicate> vocabulary = // extractor.getVocabulary(reformulationOntology); if (dbType.equals(QuestConstants.SEMANTIC)) { dataRepository = new RDBMSSIRepositoryManager(newsource, reformulationOntology.getVocabulary()); } else if (dbType.equals(QuestConstants.DIRECT)) { dataRepository = new RDBMSDirectDataRepositoryManager(newsource, reformulationOntology.getVocabulary()); } else { throw new Exception(dbType + " is unknown or not yet supported Data Base type. Currently only the direct db type is supported"); } dataRepository.setTBox(reformulationOntology); /* Creating the ABox repository */ getProgressMonitor().setMessage("Creating database schema..."); dataRepository.createDBSchema(true); dataRepository.insertMetadata(); if (bObtainFromOntology) { log.debug("Loading data from Ontology into the database"); OWLAPI2ABoxIterator aBoxIter = new OWLAPI2ABoxIterator(loadedOntologies, equivalenceMaps); dataRepository.insertData(aBoxIter); } if (bObtainFromMappings) { log.debug("Loading data from Mappings into the database"); VirtualABoxMaterializer materializer = new VirtualABoxMaterializer(obdaModel); Iterator<Assertion> assertionIter = materializer.getAssertionIterator(); dataRepository.insertData(assertionIter); } dataRepository.createIndexes(); /* Setting up the OBDA model */ unfoldingOBDAModel.addSource(newsource); unfoldingOBDAModel.addMappings(newsource.getSourceID(), dataRepository.getMappings()); for (Axiom axiom : dataRepository.getABoxDependencies().getAssertions()) { sigma.addEntities(axiom.getReferencedEntities()); sigma.addAssertion(axiom); } } } else if (unfoldingMode.equals(QuestConstants.VIRTUAL)) { log.debug("Working in virtual mode"); Collection<OBDADataSource> sources = this.obdaModel.getSources(); if (sources == null || sources.size() == 0) { throw new Exception("No datasource has been defined"); } else if (sources.size() > 1) { throw new Exception("Currently the reasoner can only handle one datasource"); } else { /* Setting up the OBDA model */ OBDADataSource ds = sources.iterator().next(); unfoldingOBDAModel.addSource(ds); /* * Processing mappings with respect to the vocabulary * simplification */ MappingVocabularyTranslator mtrans = new MappingVocabularyTranslator(); Collection<OBDAMappingAxiom> newMappings = mtrans.translateMappings(this.obdaModel.getMappings(ds.getSourceID()), equivalenceMaps); unfoldingOBDAModel.addMappings(ds.getSourceID(), newMappings); } } /* * Setting up the unfolder and SQL generation */ OBDADataSource datasource = unfoldingOBDAModel.getSources().get(0); // MappingValidator mappingValidator = new // MappingValidator(loadedOntologies); // boolean validmappings = // mappingValidator.validate(unfoldingOBDAModel.getMappings(datasource.getSourceID())); MappingViewManager viewMan = new MappingViewManager(unfoldingOBDAModel.getMappings(datasource.getSourceID())); unfMech = new ComplexMappingUnfolder(unfoldingOBDAModel.getMappings(datasource.getSourceID()), viewMan); JDBCUtility util = new JDBCUtility(datasource.getParameter(RDBMSourceParameterConstants.DATABASE_DRIVER)); gen = new ComplexMappingSQLGenerator(viewMan, util); log.debug("Setting up the connection;"); eval_engine = new JDBCEngine(unfoldingOBDAModel.getSources().get(0)); /* * Setting up the ontology we will use for the reformulation */ if (optimizeSigma) { SigmaTBoxOptimizer reducer = new SigmaTBoxOptimizer(reformulationOntology, sigma); reformulationOntology = reducer.getReducedOntology(); } /* * Setting up the reformulation engine */ if (QuestConstants.PERFECTREFORMULATION.equals(reformulationTechnique)) { rewriter = new DLRPerfectReformulator(); } else if (QuestConstants.UCQBASED.equals(reformulationTechnique)) { rewriter = new TreeRedReformulator(); } else { throw new IllegalArgumentException("Invalid value for argument: " + ReformulationPlatformPreferences.REFORMULATION_TECHNIQUE); } rewriter.setTBox(reformulationOntology); rewriter.setCBox(sigma); /* * Done, sending a new reasoner with the modules we just configured */ QueryVocabularyValidator validator = new QueryVocabularyValidator(reformulationOntology, equivalenceMaps); this.techwrapper = new QuestTechniqueWrapper(unfMech, rewriter, gen, validator, eval_engine, unfoldingOBDAModel); log.debug("... Quest has been setup and is ready for querying"); isClassified = true; } catch (Exception e) { log.error(e.getMessage(), e); OWLReasonerException ex = new OWLReasonerException(e.getMessage(), e) { }; e.fillInStackTrace(); throw ex; } finally { getProgressMonitor().setFinished(); } }
diff --git a/src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/JIRAClient.java b/src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/JIRAClient.java index b371bca..c0d6ace 100644 --- a/src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/JIRAClient.java +++ b/src/test/java/it/org/agilos/zendesk_jira_plugin/integrationtest/JIRAClient.java @@ -1,145 +1,148 @@ package it.org.agilos.zendesk_jira_plugin.integrationtest; import java.net.URL; import javax.xml.ws.WebServiceException; import net.sourceforge.jwebunit.WebTester; import org.agilos.jira.soapclient.JiraSoapService; import org.agilos.jira.soapclient.JiraSoapServiceService; import org.agilos.jira.soapclient.JiraSoapServiceServiceLocator; import org.apache.log4j.Logger; import com.atlassian.jira.functest.framework.FuncTestHelperFactory; import com.atlassian.jira.functest.framework.navigation.IssueNavigation; import com.atlassian.jira.webtests.util.JIRAEnvironmentData; import com.atlassian.jira.webtests.util.LocalTestEnvironmentData; import com.meterware.httpunit.HttpUnitOptions; /** * Wraps the implementation details of how to connect to JIRA and login. * * This is a Singleton, so use the {@link #instance} method to get an instance to the concrete instance. * * The following system properties define the behavior of the <code>JIRAClient</code>: * <ul> * <li> zendesk.jira.url The url of the JIRA instance the client should connect to * <li> zendesk.jira.login.name The Username to login with * <li> zendesk.jira.login.password The password to login to jira with * </ul> */ public class JIRAClient { private static JIRAClient instance = new JIRAClient(); protected JiraSoapService jiraSoapService; protected String jiraSoapToken; public static String jiraUrl; public static String loginName = System.getProperty("zendesk.jira.login.name", "bamboo"); public static String loginPassword = System.getProperty("zendesk.jira.login.password","bamboo2997"); private Logger log = Logger.getLogger(JIRAClient.class.getName()); private FuncTestHelperFactory fthFatory; public FuncTestHelperFactory getFuncTestHelperFactory() { return fthFatory; } public IssueEditor getIssueEditor(String issuekey) { return new IssueEditor(issuekey, fthFatory); } private JIRAClient() { + // Override default loading of localtest.properties by LocalTestEnvironment as this is autogenerated by the Atlassian PDK + if (System.getProperty("test.server.properties").equals("")) + System.setProperty("test.server.properties", "test-jira-4.0.properties"); WebTester tester = new WebTester(); LocalTestEnvironmentData environmentData = new LocalTestEnvironmentData(); initWebTester(tester, environmentData); fthFatory = new FuncTestHelperFactory(tester, environmentData); jiraUrl = environmentData.getBaseUrl().toString(); } public void login() throws Exception { login(loginName, loginPassword); } public void login(String user, String password) throws Exception { URL jiraSOAPServiceUrl = new URL(jiraUrl+"/rpc/soap/jirasoapservice-v2"); JiraSoapServiceService jiraSoapServiceGetter = new JiraSoapServiceServiceLocator(); log.debug("Retriving jira soap service from "+jiraSOAPServiceUrl); jiraSoapService = jiraSoapServiceGetter.getJirasoapserviceV2(jiraSOAPServiceUrl); log.debug("Logging in with user: "+user+" and password: "+password); jiraSoapToken = jiraSoapService.login(user, password); //Soap login fthFatory.getNavigation().login(user, password);// GUI login } public static JIRAClient instance() throws WebServiceException { return instance; } /** * Returns the JIRA service instance the client uses to connect to JIRA. */ public JiraSoapService getService() { if (jiraSoapService == null) throw new WebServiceException("Haven't been able to connect to the JIRA server, see log for further details"); return jiraSoapService; } /** * The login token needed in all SOAP calls to JIRA */ public String getToken() { if (jiraSoapToken == null) throw new WebServiceException("Haven't been able to login to the JIRA server, see log for further details"); return jiraSoapToken; } private void initWebTester(WebTester tester, JIRAEnvironmentData environmentData) { tester.getTestContext().setBaseUrl(environmentData.getBaseUrl().toExternalForm()); HttpUnitOptions.setExceptionsThrownOnScriptError(false); tester.beginAt("/"); HttpUnitOptions.setScriptingEnabled(true); } public void setZendeskUrl(String zendeskURL) { gotoListenerConfiguration(); log.info("Updating Zendesk URL to "+zendeskURL); fthFatory.getTester().setFormElement("ZendeskUrl", zendeskURL); fthFatory.getTester().clickButton("Update"); fthFatory.getTester().assertTextPresent(zendeskURL); } public void setZendeskCredentials(String zendeskLogin, String zendeskPW) { gotoListenerConfiguration(); log.info("Updating Zendesk log to "+zendeskLogin+" and zendesk PW to "+zendeskPW); fthFatory.getTester().setFormElement("LoginName", zendeskLogin); fthFatory.getTester().setFormElement("LoginPassword", zendeskPW); fthFatory.getTester().clickButton("Update"); fthFatory.getTester().assertTextPresent(zendeskLogin); fthFatory.getTester().assertTextPresent(zendeskPW); } public void setCommentsPublic(String publicComments) { gotoListenerConfiguration(); log.info("Setting public comment value to "+publicComments); fthFatory.getTester().setFormElement("Public comments", publicComments); fthFatory.getTester().clickButton("Update"); fthFatory.getTester().assertTextPresent(publicComments); } private void gotoListenerConfiguration() { fthFatory.getNavigation().gotoAdminSection("listeners"); fthFatory.getTester().clickLinkWithText("Edit"); fthFatory.getTester().assertTextPresent("ZendeskUrl"); } public void setUploadAttachments(String uploadAttachments) { gotoListenerConfiguration(); log.info("Updating updateAttachments to "+uploadAttachments); fthFatory.getTester().setFormElement("Upload attachments", uploadAttachments); fthFatory.getTester().clickButton("Update"); fthFatory.getTester().assertTextPresent(uploadAttachments); } }
true
true
private JIRAClient() { WebTester tester = new WebTester(); LocalTestEnvironmentData environmentData = new LocalTestEnvironmentData(); initWebTester(tester, environmentData); fthFatory = new FuncTestHelperFactory(tester, environmentData); jiraUrl = environmentData.getBaseUrl().toString(); }
private JIRAClient() { // Override default loading of localtest.properties by LocalTestEnvironment as this is autogenerated by the Atlassian PDK if (System.getProperty("test.server.properties").equals("")) System.setProperty("test.server.properties", "test-jira-4.0.properties"); WebTester tester = new WebTester(); LocalTestEnvironmentData environmentData = new LocalTestEnvironmentData(); initWebTester(tester, environmentData); fthFatory = new FuncTestHelperFactory(tester, environmentData); jiraUrl = environmentData.getBaseUrl().toString(); }
diff --git a/gdx/src/com/badlogic/gdx/graphics/g3d/shaders/GLES10Shader.java b/gdx/src/com/badlogic/gdx/graphics/g3d/shaders/GLES10Shader.java index 26d90c45c..4f1634fd6 100644 --- a/gdx/src/com/badlogic/gdx/graphics/g3d/shaders/GLES10Shader.java +++ b/gdx/src/com/badlogic/gdx/graphics/g3d/shaders/GLES10Shader.java @@ -1,201 +1,201 @@ package com.badlogic.gdx.graphics.g3d.shaders; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Camera; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.lights.DirectionalLight; import com.badlogic.gdx.graphics.g3d.lights.Lights; import com.badlogic.gdx.graphics.g3d.lights.PointLight; import com.badlogic.gdx.graphics.g3d.materials.BlendingAttribute; import com.badlogic.gdx.graphics.g3d.materials.ColorAttribute; import com.badlogic.gdx.graphics.g3d.materials.IntAttribute; import com.badlogic.gdx.graphics.g3d.materials.Material; import com.badlogic.gdx.graphics.g3d.materials.TextureAttribute; import com.badlogic.gdx.graphics.g3d.utils.RenderContext; import com.badlogic.gdx.graphics.g3d.utils.TextureDescriptor; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.GdxRuntimeException; public class GLES10Shader implements Shader{ private Camera camera; private RenderContext context; private Matrix4 currentTransform; private Material currentMaterial; private Texture currentTexture0; private Mesh currentMesh; /** Set to 0 to disable culling */ public static int defaultCullFace = GL10.GL_BACK; public GLES10Shader() { if (Gdx.gl10 == null) throw new GdxRuntimeException("This shader requires OpenGL ES 1.x"); } @Override public void init () { } @Override public boolean canRender(final Renderable renderable) { return true; } @Override public int compareTo(Shader other) { // TODO Auto-generated method stub return 0; } @Override public boolean equals (Object obj) { return (obj instanceof GLES10Shader) ? equals((GLES10Shader)obj) : false; } public boolean equals (GLES10Shader obj) { return (obj == this); } @Override public void begin (final Camera camera, final RenderContext context) { this.context = context; this.camera = camera; context.setDepthTest(GL10.GL_LEQUAL, 0, 1, true); Gdx.gl10.glMatrixMode(GL10.GL_PROJECTION); Gdx.gl10.glLoadMatrixf(camera.combined.val, 0); Gdx.gl10.glMatrixMode(GL10.GL_MODELVIEW); } private final float[] lightVal = {0,0,0,0}; private final float[] zeroVal4 = {0,0,0,0}; private final float[] oneVal4 = {1,1,1,1}; private void bindLights(Lights lights) { if (lights == null) { Gdx.gl10.glDisable(GL10.GL_LIGHTING); return; } Gdx.gl10.glEnable(GL10.GL_LIGHTING); Gdx.gl10.glLightModelfv(GL10.GL_LIGHT_MODEL_AMBIENT, getValues(lightVal, lights.ambientLight), 0); Gdx.gl10.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, zeroVal4, 0); int idx=0; Gdx.gl10.glPushMatrix(); Gdx.gl10.glLoadIdentity(); for (int i = 0; i < lights.directionalLights.size && idx < 8; i++) { final DirectionalLight light = lights.directionalLights.get(i); Gdx.gl10.glEnable(GL10.GL_LIGHT0+idx); Gdx.gl10.glLightfv(GL10.GL_LIGHT0+idx, GL10.GL_DIFFUSE, getValues(lightVal, light.color), 0); Gdx.gl10.glLightfv(GL10.GL_LIGHT0+idx, GL10.GL_POSITION, getValues(lightVal, -light.direction.x, -light.direction.y, -light.direction.z, 0f), 0); Gdx.gl10.glLightf(GL10.GL_LIGHT0+idx, GL10.GL_SPOT_CUTOFF, 180f); Gdx.gl10.glLightf(GL10.GL_LIGHT0+idx, GL10.GL_CONSTANT_ATTENUATION, 1f); Gdx.gl10.glLightf(GL10.GL_LIGHT0+idx, GL10.GL_LINEAR_ATTENUATION, 0f); Gdx.gl10.glLightf(GL10.GL_LIGHT0+idx, GL10.GL_QUADRATIC_ATTENUATION, 0f); idx++; } for (int i = 0; i < lights.pointLights.size && idx < 8; i++) { Gdx.gl10.glEnable(GL10.GL_LIGHT0+idx); final PointLight light = lights.pointLights.get(i); Gdx.gl10.glLightfv(GL10.GL_LIGHT0+idx, GL10.GL_DIFFUSE, getValues(lightVal, light.color), 0); Gdx.gl10.glLightfv(GL10.GL_LIGHT0+idx, GL10.GL_POSITION, getValues(lightVal, light.position.x, light.position.y, light.position.z, 1f), 0); Gdx.gl10.glLightf(GL10.GL_LIGHT0+idx, GL10.GL_SPOT_CUTOFF, 180f); Gdx.gl10.glLightf(GL10.GL_LIGHT0+idx, GL10.GL_CONSTANT_ATTENUATION, 0f); Gdx.gl10.glLightf(GL10.GL_LIGHT0+idx, GL10.GL_LINEAR_ATTENUATION, 0f); Gdx.gl10.glLightf(GL10.GL_LIGHT0+idx, GL10.GL_QUADRATIC_ATTENUATION, 1f/light.intensity); idx++; } while(idx < 8) Gdx.gl10.glDisable(GL10.GL_LIGHT0+(idx++)); Gdx.gl10.glPopMatrix(); } private final static float[] getValues(final float out[], final float v0, final float v1, final float v2, final float v3) { out[0] = v0; out[1] = v1; out[2] = v2; out[3] = v3; return out; } private final static float[] getValues(final float out[], final Color color) { return getValues(out, color.r, color.g, color.b, color.a); } @Override public void render (final Renderable renderable) { if (currentMaterial != renderable.material) { currentMaterial = renderable.material; if (!currentMaterial.has(BlendingAttribute.Type)) context.setBlending(false, GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); if (!currentMaterial.has(ColorAttribute.Diffuse)) { Gdx.gl10.glColor4f(1,1,1,1); if (renderable.lights != null) Gdx.gl10.glDisable(GL10.GL_COLOR_MATERIAL); } if (!currentMaterial.has(TextureAttribute.Diffuse)) Gdx.gl10.glDisable(GL10.GL_TEXTURE_2D); int cullFace = defaultCullFace; for (final Material.Attribute attribute : currentMaterial) { if (attribute.type == BlendingAttribute.Type) context.setBlending(true, ((BlendingAttribute)attribute).sourceFunction, ((BlendingAttribute)attribute).destFunction); else if (attribute.type == ColorAttribute.Diffuse) { Gdx.gl10.glColor4f(((ColorAttribute)attribute).color.r, ((ColorAttribute)attribute).color.g, ((ColorAttribute)attribute).color.b, ((ColorAttribute)attribute).color.a); if (renderable.lights != null) { Gdx.gl10.glEnable(GL10.GL_COLOR_MATERIAL); - Gdx.gl10.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, zeroVal4, 0); + Gdx.gl10.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, getValues(lightVal, ((ColorAttribute)attribute).color), 0); Gdx.gl10.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_DIFFUSE, getValues(lightVal, ((ColorAttribute)attribute).color), 0); } } else if (attribute.type == TextureAttribute.Diffuse) { TextureDescriptor textureDesc = ((TextureAttribute)attribute).textureDescription; if (currentTexture0 != textureDesc.texture) (currentTexture0 = textureDesc.texture).bind(0); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, textureDesc.minFilter); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, textureDesc.magFilter); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, textureDesc.uWrap); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, textureDesc.vWrap); Gdx.gl10.glEnable(GL10.GL_TEXTURE_2D); } else if ((attribute.type & IntAttribute.CullFace) == IntAttribute.CullFace) cullFace = ((IntAttribute)attribute).value; } context.setCullFace(cullFace); } if (currentTransform != renderable.worldTransform) { // FIXME mul localtransform if (currentTransform != null) Gdx.gl10.glPopMatrix(); currentTransform = renderable.worldTransform; Gdx.gl10.glPushMatrix(); Gdx.gl10.glLoadMatrixf(currentTransform.val, 0); } bindLights(renderable.lights); if (currentMesh != renderable.mesh) { if (currentMesh != null) currentMesh.unbind(); (currentMesh = renderable.mesh).bind(); } renderable.mesh.render(renderable.primitiveType, renderable.meshPartOffset, renderable.meshPartSize); } @Override public void end () { if (currentMesh != null) currentMesh.unbind(); currentMesh = null; if (currentTransform != null) Gdx.gl10.glPopMatrix(); currentTransform = null; currentTexture0 = null; currentMaterial = null; Gdx.gl10.glDisable(GL10.GL_LIGHTING); } @Override public void dispose () { // TODO Auto-generated method stub } }
true
true
public void render (final Renderable renderable) { if (currentMaterial != renderable.material) { currentMaterial = renderable.material; if (!currentMaterial.has(BlendingAttribute.Type)) context.setBlending(false, GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); if (!currentMaterial.has(ColorAttribute.Diffuse)) { Gdx.gl10.glColor4f(1,1,1,1); if (renderable.lights != null) Gdx.gl10.glDisable(GL10.GL_COLOR_MATERIAL); } if (!currentMaterial.has(TextureAttribute.Diffuse)) Gdx.gl10.glDisable(GL10.GL_TEXTURE_2D); int cullFace = defaultCullFace; for (final Material.Attribute attribute : currentMaterial) { if (attribute.type == BlendingAttribute.Type) context.setBlending(true, ((BlendingAttribute)attribute).sourceFunction, ((BlendingAttribute)attribute).destFunction); else if (attribute.type == ColorAttribute.Diffuse) { Gdx.gl10.glColor4f(((ColorAttribute)attribute).color.r, ((ColorAttribute)attribute).color.g, ((ColorAttribute)attribute).color.b, ((ColorAttribute)attribute).color.a); if (renderable.lights != null) { Gdx.gl10.glEnable(GL10.GL_COLOR_MATERIAL); Gdx.gl10.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, zeroVal4, 0); Gdx.gl10.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_DIFFUSE, getValues(lightVal, ((ColorAttribute)attribute).color), 0); } } else if (attribute.type == TextureAttribute.Diffuse) { TextureDescriptor textureDesc = ((TextureAttribute)attribute).textureDescription; if (currentTexture0 != textureDesc.texture) (currentTexture0 = textureDesc.texture).bind(0); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, textureDesc.minFilter); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, textureDesc.magFilter); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, textureDesc.uWrap); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, textureDesc.vWrap); Gdx.gl10.glEnable(GL10.GL_TEXTURE_2D); } else if ((attribute.type & IntAttribute.CullFace) == IntAttribute.CullFace) cullFace = ((IntAttribute)attribute).value; } context.setCullFace(cullFace); } if (currentTransform != renderable.worldTransform) { // FIXME mul localtransform if (currentTransform != null) Gdx.gl10.glPopMatrix(); currentTransform = renderable.worldTransform; Gdx.gl10.glPushMatrix(); Gdx.gl10.glLoadMatrixf(currentTransform.val, 0); } bindLights(renderable.lights); if (currentMesh != renderable.mesh) { if (currentMesh != null) currentMesh.unbind(); (currentMesh = renderable.mesh).bind(); } renderable.mesh.render(renderable.primitiveType, renderable.meshPartOffset, renderable.meshPartSize); }
public void render (final Renderable renderable) { if (currentMaterial != renderable.material) { currentMaterial = renderable.material; if (!currentMaterial.has(BlendingAttribute.Type)) context.setBlending(false, GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); if (!currentMaterial.has(ColorAttribute.Diffuse)) { Gdx.gl10.glColor4f(1,1,1,1); if (renderable.lights != null) Gdx.gl10.glDisable(GL10.GL_COLOR_MATERIAL); } if (!currentMaterial.has(TextureAttribute.Diffuse)) Gdx.gl10.glDisable(GL10.GL_TEXTURE_2D); int cullFace = defaultCullFace; for (final Material.Attribute attribute : currentMaterial) { if (attribute.type == BlendingAttribute.Type) context.setBlending(true, ((BlendingAttribute)attribute).sourceFunction, ((BlendingAttribute)attribute).destFunction); else if (attribute.type == ColorAttribute.Diffuse) { Gdx.gl10.glColor4f(((ColorAttribute)attribute).color.r, ((ColorAttribute)attribute).color.g, ((ColorAttribute)attribute).color.b, ((ColorAttribute)attribute).color.a); if (renderable.lights != null) { Gdx.gl10.glEnable(GL10.GL_COLOR_MATERIAL); Gdx.gl10.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, getValues(lightVal, ((ColorAttribute)attribute).color), 0); Gdx.gl10.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_DIFFUSE, getValues(lightVal, ((ColorAttribute)attribute).color), 0); } } else if (attribute.type == TextureAttribute.Diffuse) { TextureDescriptor textureDesc = ((TextureAttribute)attribute).textureDescription; if (currentTexture0 != textureDesc.texture) (currentTexture0 = textureDesc.texture).bind(0); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, textureDesc.minFilter); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, textureDesc.magFilter); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, textureDesc.uWrap); Gdx.gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, textureDesc.vWrap); Gdx.gl10.glEnable(GL10.GL_TEXTURE_2D); } else if ((attribute.type & IntAttribute.CullFace) == IntAttribute.CullFace) cullFace = ((IntAttribute)attribute).value; } context.setCullFace(cullFace); } if (currentTransform != renderable.worldTransform) { // FIXME mul localtransform if (currentTransform != null) Gdx.gl10.glPopMatrix(); currentTransform = renderable.worldTransform; Gdx.gl10.glPushMatrix(); Gdx.gl10.glLoadMatrixf(currentTransform.val, 0); } bindLights(renderable.lights); if (currentMesh != renderable.mesh) { if (currentMesh != null) currentMesh.unbind(); (currentMesh = renderable.mesh).bind(); } renderable.mesh.render(renderable.primitiveType, renderable.meshPartOffset, renderable.meshPartSize); }
diff --git a/Jama/src/main/java/presentationLayer/InstallmentDataPresentationBean.java b/Jama/src/main/java/presentationLayer/InstallmentDataPresentationBean.java index b5b5069..9dde23c 100644 --- a/Jama/src/main/java/presentationLayer/InstallmentDataPresentationBean.java +++ b/Jama/src/main/java/presentationLayer/InstallmentDataPresentationBean.java @@ -1,74 +1,73 @@ package presentationLayer; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.enterprise.context.ConversationScoped; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.ValidatorException; import javax.inject.Inject; import javax.inject.Named; import org.joda.money.Money; import util.Config; import util.Messages; import annotations.TransferObj; import businessLayer.Contract; import businessLayer.Installment; @Named("instDataPB") @ConversationScoped public class InstallmentDataPresentationBean implements Serializable { private static final long serialVersionUID = 1L; @Inject @TransferObj private Installment installment; public InstallmentDataPresentationBean() {} public void validateAmount(FacesContext context, UIComponent component, Object value) { _validateAmount(installment.getWholeAmount()); } public void editingValidateAmount(FacesContext context, UIComponent component, Object value) { _validateAmount(Money.zero(Config.currency)); } private void _validateAmount(Money startingValue) { Contract c = installment.getContract(); List<Installment> installments = c.getInstallments(); Money sum = startingValue; for (Installment i : installments) { if (!i.equals(installment)) { sum = sum.plus(i.getWholeAmount()); } } if (sum.isGreaterThan(c.getWholeAmount())) { throw new ValidatorException(Messages.getErrorMessage("err_installmentAmount")); } } public void validateDeadlineDate(FacesContext context, UIComponent component, Object value) { try { Date deadline = (Date) value; Date begin = installment.getContract().getBeginDate(); - Date end = installment.getContract().getDeadlineDate(); - if (deadline.before(begin) || deadline.after(end)) { + if (deadline.before(begin)) { throw new ValidatorException(Messages.getErrorMessage("err_instInvalidDeadline")); } } catch (ClassCastException e) { String[] params = { (String) component.getAttributes().get("label") }; throw new ValidatorException(Messages.getErrorMessage("err_invalidValue", params)); } } }
false
true
public void validateDeadlineDate(FacesContext context, UIComponent component, Object value) { try { Date deadline = (Date) value; Date begin = installment.getContract().getBeginDate(); Date end = installment.getContract().getDeadlineDate(); if (deadline.before(begin) || deadline.after(end)) { throw new ValidatorException(Messages.getErrorMessage("err_instInvalidDeadline")); } } catch (ClassCastException e) { String[] params = { (String) component.getAttributes().get("label") }; throw new ValidatorException(Messages.getErrorMessage("err_invalidValue", params)); } }
public void validateDeadlineDate(FacesContext context, UIComponent component, Object value) { try { Date deadline = (Date) value; Date begin = installment.getContract().getBeginDate(); if (deadline.before(begin)) { throw new ValidatorException(Messages.getErrorMessage("err_instInvalidDeadline")); } } catch (ClassCastException e) { String[] params = { (String) component.getAttributes().get("label") }; throw new ValidatorException(Messages.getErrorMessage("err_invalidValue", params)); } }
diff --git a/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/DiscoveredServerView.java b/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/DiscoveredServerView.java index fdb4c53c..8516d1db 100644 --- a/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/DiscoveredServerView.java +++ b/src/com.gluster.storage.management.gui/src/com/gluster/storage/management/gui/views/DiscoveredServerView.java @@ -1,90 +1,90 @@ /** * DiscoveredServerView.java * * Copyright (c) 2011 Gluster, Inc. <http://www.gluster.com> * This file is part of Gluster Management Console. * * Gluster Management Console is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Gluster Management Console is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.gluster.storage.management.gui.views; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.part.ViewPart; import com.gluster.storage.management.core.model.Server; import com.gluster.storage.management.core.utils.NumberUtil; import com.gluster.storage.management.gui.utils.GUIHelper; /** * @author root * */ public class DiscoveredServerView extends ViewPart { public static final String ID = DiscoveredServerView.class.getName(); private static final GUIHelper guiHelper = GUIHelper.getInstance(); private final FormToolkit toolkit = new FormToolkit(Display.getCurrent()); private ScrolledForm form; private Server server; /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ @Override public void createPartControl(Composite parent) { if (server == null) { server = (Server) guiHelper.getSelectedEntity(getSite(), Server.class); } createSections(parent); } private void createServerSummarySection() { Composite section = guiHelper.createSection(form, toolkit, "Summary", null, 2, false); toolkit.createLabel(section, "Number of CPUs: ", SWT.NONE); toolkit.createLabel(section, "" + server.getNumOfCPUs(), SWT.NONE); toolkit.createLabel(section, "Total Memory (GB): ", SWT.NONE); - toolkit.createLabel(section, "" + (server.getTotalMemory() / 1024), SWT.NONE); + toolkit.createLabel(section, "" + NumberUtil.formatNumber((server.getTotalMemory() / 1024)), SWT.NONE); toolkit.createLabel(section, "Total Disk Space (GB): ", SWT.NONE); toolkit.createLabel(section, "" + NumberUtil.formatNumber((server.getTotalDiskSpace() / 1024)), SWT.NONE); } private void createSections(Composite parent) { String serverName = server.getName(); form = guiHelper.setupForm(parent, toolkit, "Discovered Server Summary [" + serverName + "]"); createServerSummarySection(); parent.layout(); // IMP: lays out the form properly } /* * (non-Javadoc) * * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ @Override public void setFocus() { if (form != null) { form.setFocus(); } } }
true
true
private void createServerSummarySection() { Composite section = guiHelper.createSection(form, toolkit, "Summary", null, 2, false); toolkit.createLabel(section, "Number of CPUs: ", SWT.NONE); toolkit.createLabel(section, "" + server.getNumOfCPUs(), SWT.NONE); toolkit.createLabel(section, "Total Memory (GB): ", SWT.NONE); toolkit.createLabel(section, "" + (server.getTotalMemory() / 1024), SWT.NONE); toolkit.createLabel(section, "Total Disk Space (GB): ", SWT.NONE); toolkit.createLabel(section, "" + NumberUtil.formatNumber((server.getTotalDiskSpace() / 1024)), SWT.NONE); }
private void createServerSummarySection() { Composite section = guiHelper.createSection(form, toolkit, "Summary", null, 2, false); toolkit.createLabel(section, "Number of CPUs: ", SWT.NONE); toolkit.createLabel(section, "" + server.getNumOfCPUs(), SWT.NONE); toolkit.createLabel(section, "Total Memory (GB): ", SWT.NONE); toolkit.createLabel(section, "" + NumberUtil.formatNumber((server.getTotalMemory() / 1024)), SWT.NONE); toolkit.createLabel(section, "Total Disk Space (GB): ", SWT.NONE); toolkit.createLabel(section, "" + NumberUtil.formatNumber((server.getTotalDiskSpace() / 1024)), SWT.NONE); }
diff --git a/src/main/java/org/basex/BaseX.java b/src/main/java/org/basex/BaseX.java index a33053253..2381fccd4 100644 --- a/src/main/java/org/basex/BaseX.java +++ b/src/main/java/org/basex/BaseX.java @@ -1,246 +1,248 @@ package org.basex; import static org.basex.core.Text.*; import java.io.*; import org.basex.core.*; import org.basex.core.cmd.*; import org.basex.io.*; import org.basex.io.out.*; import org.basex.io.serial.*; import org.basex.server.*; import org.basex.util.*; import org.basex.util.list.*; /** * This is the starter class for the stand-alone console mode. * It executes all commands locally. * * @author BaseX Team 2005-12, BSD License * @author Christian Gruen */ public class BaseX extends Main { /** Commands to be executed. */ private IntList ops; /** Command arguments. */ private StringList vals; /** Flag for writing properties to disk. */ private boolean writeProps; /** * Main method, launching the standalone mode. * Command-line arguments are listed with the {@code -h} argument. * @param args command-line arguments */ public static void main(final String... args) { try { new BaseX(args); } catch(final IOException ex) { Util.errln(ex); System.exit(1); } } /** * Constructor. * @param args command-line arguments * @throws IOException I/O exception */ public BaseX(final String... args) throws IOException { super(args); // create session to show optional login request session(); final StringBuilder serial = new StringBuilder(); final StringBuilder bind = new StringBuilder(); boolean v = false, qi = false, qp = false; console = true; try { // loop through all commands for(int i = 0; i < ops.size(); i++) { final int c = ops.get(i); String val = vals.get(i); Object[] prop = null; if(c == 'b') { // set/add variable binding if(bind.length() != 0) bind.append(','); // commas are escaped by a second comma val = bind.append(val.replaceAll(",", ",,")).toString(); prop = Prop.BINDINGS; } else if(c == 'c') { // evaluate commands final IO io = IO.get(val); if(io.exists() && !io.isDir()) { execute(io.string()); } else { execute(val); } console = false; } else if(c == 'd') { // toggle debug mode Prop.debug ^= true; } else if(c == 'D') { // hidden option: show/hide dot query graph prop = Prop.DOTPLAN; } else if(c == 'i') { // open database or create main memory representation execute(new Set(Prop.MAINMEM, true), false); execute(new Check(val), verbose); execute(new Set(Prop.MAINMEM, false), false); } else if(c == 'L') { // toggle newline separators newline ^= true; - execute(new Set(Prop.SERIALIZER, newline ? - SerializerProp.S_ITEM_SEPARATOR[0] + "=\\n" : ""), false); + if(serial.length() != 0) serial.append(','); + val = serial.append(SerializerProp.S_ITEM_SEPARATOR[0]).append("=\\n"). + toString(); + prop = Prop.SERIALIZER; } else if(c == 'o') { // change output stream if(out != System.out) out.close(); out = new PrintOutput(val); session().setOutputStream(out); } else if(c == 'q') { // evaluate query execute(new XQuery(val), verbose); console = false; } else if(c == 'Q') { // evaluate file contents or string as query final IO io = IO.get(val); if(io.exists() && !io.isDir()) { query(io); } else { execute(new XQuery(val), verbose); } console = false; } else if(c == 'r') { // hidden option: parse number of runs prop = Prop.RUNS; } else if(c == 's') { // set/add serialization parameter if(serial.length() != 0) serial.append(','); val = serial.append(val).toString(); prop = Prop.SERIALIZER; } else if(c == 'u') { // (de)activate write-back for updates prop = Prop.WRITEBACK; } else if(c == 'v') { // show/hide verbose mode v ^= true; } else if(c == 'V') { // show/hide query info qi ^= true; prop = Prop.QUERYINFO; } else if(c == 'w') { // toggle chopping of whitespaces prop = Prop.CHOP; } else if(c == 'W') { // hidden option: toggle writing of properties before exit writeProps ^= true; } else if(c == 'x') { // show/hide xml query plan prop = Prop.XMLPLAN; qp ^= true; } else if(c == 'X') { // hidden option: show query plan before/after query compilation prop = Prop.COMPPLAN; } else if(c == 'z') { // toggle result serialization prop = Prop.SERIALIZE; } if(prop != null) execute(new Set(prop, val), false); verbose = qi || qp || v; } if(console) { verbose = true; // enter interactive mode Util.outln(CONSOLE + TRY_MORE_X, sa() ? LOCALMODE : CLIENTMODE); console(); } if(writeProps) context.mprop.write(); } finally { quit(); } } /** * Runs a query file. * @param io input file * @throws IOException I/O exception */ private void query(final IO io) throws IOException { execute(new Set(Prop.QUERYPATH, io.path()), false); execute(new XQuery(io.string()), verbose); } /** * Tests if this client is stand-alone. * @return stand-alone flag */ boolean sa() { return true; } @Override protected Session session() throws IOException { if(session == null) session = new LocalSession(context, out); session.setOutputStream(out); return session; } @Override protected final void parseArguments(final String... args) throws IOException { ops = new IntList(); vals = new StringList(); final Args arg = new Args(args, this, sa() ? LOCALINFO : CLIENTINFO, Util.info(CONSOLE, sa() ? LOCALMODE : CLIENTMODE)); while(arg.more()) { final char c; String v = null; if(arg.dash()) { c = arg.next(); if(c == 'b' || c == 'c' || c == 'C' || c == 'i' || c == 'o' || c == 'q' || c == 'r' || c == 's') { // options followed by a string v = arg.string(); } else if(c == 'd' || c == 'D' && sa() || c == 'L' || c == 'u' || c == 'v' || c == 'V' || c == 'w' || c == 'W' || c == 'x' || c == 'X' || c == 'z') { // options to be toggled v = ""; } else if(!sa()) { // client options: need to be set before other options if(c == 'n') { // set server name context.mprop.set(MainProp.HOST, arg.string()); } else if(c == 'p') { // set server port context.mprop.set(MainProp.PORT, arg.number()); } else if(c == 'P') { // specify password context.mprop.set(MainProp.PASSWORD, arg.string()); } else if(c == 'U') { // specify user name context.mprop.set(MainProp.USER, arg.string()); } else { arg.usage(); } } else { arg.usage(); } } else { v = arg.string().trim(); // interpret at commands if input starts with < or ends with command script suffix c = v.startsWith("<") || v.endsWith(IO.BXSSUFFIX) ? 'c' : 'Q'; } if(v != null) { ops.add(c); vals.add(v); } } } }
true
true
public BaseX(final String... args) throws IOException { super(args); // create session to show optional login request session(); final StringBuilder serial = new StringBuilder(); final StringBuilder bind = new StringBuilder(); boolean v = false, qi = false, qp = false; console = true; try { // loop through all commands for(int i = 0; i < ops.size(); i++) { final int c = ops.get(i); String val = vals.get(i); Object[] prop = null; if(c == 'b') { // set/add variable binding if(bind.length() != 0) bind.append(','); // commas are escaped by a second comma val = bind.append(val.replaceAll(",", ",,")).toString(); prop = Prop.BINDINGS; } else if(c == 'c') { // evaluate commands final IO io = IO.get(val); if(io.exists() && !io.isDir()) { execute(io.string()); } else { execute(val); } console = false; } else if(c == 'd') { // toggle debug mode Prop.debug ^= true; } else if(c == 'D') { // hidden option: show/hide dot query graph prop = Prop.DOTPLAN; } else if(c == 'i') { // open database or create main memory representation execute(new Set(Prop.MAINMEM, true), false); execute(new Check(val), verbose); execute(new Set(Prop.MAINMEM, false), false); } else if(c == 'L') { // toggle newline separators newline ^= true; execute(new Set(Prop.SERIALIZER, newline ? SerializerProp.S_ITEM_SEPARATOR[0] + "=\\n" : ""), false); } else if(c == 'o') { // change output stream if(out != System.out) out.close(); out = new PrintOutput(val); session().setOutputStream(out); } else if(c == 'q') { // evaluate query execute(new XQuery(val), verbose); console = false; } else if(c == 'Q') { // evaluate file contents or string as query final IO io = IO.get(val); if(io.exists() && !io.isDir()) { query(io); } else { execute(new XQuery(val), verbose); } console = false; } else if(c == 'r') { // hidden option: parse number of runs prop = Prop.RUNS; } else if(c == 's') { // set/add serialization parameter if(serial.length() != 0) serial.append(','); val = serial.append(val).toString(); prop = Prop.SERIALIZER; } else if(c == 'u') { // (de)activate write-back for updates prop = Prop.WRITEBACK; } else if(c == 'v') { // show/hide verbose mode v ^= true; } else if(c == 'V') { // show/hide query info qi ^= true; prop = Prop.QUERYINFO; } else if(c == 'w') { // toggle chopping of whitespaces prop = Prop.CHOP; } else if(c == 'W') { // hidden option: toggle writing of properties before exit writeProps ^= true; } else if(c == 'x') { // show/hide xml query plan prop = Prop.XMLPLAN; qp ^= true; } else if(c == 'X') { // hidden option: show query plan before/after query compilation prop = Prop.COMPPLAN; } else if(c == 'z') { // toggle result serialization prop = Prop.SERIALIZE; } if(prop != null) execute(new Set(prop, val), false); verbose = qi || qp || v; } if(console) { verbose = true; // enter interactive mode Util.outln(CONSOLE + TRY_MORE_X, sa() ? LOCALMODE : CLIENTMODE); console(); } if(writeProps) context.mprop.write(); } finally { quit(); } }
public BaseX(final String... args) throws IOException { super(args); // create session to show optional login request session(); final StringBuilder serial = new StringBuilder(); final StringBuilder bind = new StringBuilder(); boolean v = false, qi = false, qp = false; console = true; try { // loop through all commands for(int i = 0; i < ops.size(); i++) { final int c = ops.get(i); String val = vals.get(i); Object[] prop = null; if(c == 'b') { // set/add variable binding if(bind.length() != 0) bind.append(','); // commas are escaped by a second comma val = bind.append(val.replaceAll(",", ",,")).toString(); prop = Prop.BINDINGS; } else if(c == 'c') { // evaluate commands final IO io = IO.get(val); if(io.exists() && !io.isDir()) { execute(io.string()); } else { execute(val); } console = false; } else if(c == 'd') { // toggle debug mode Prop.debug ^= true; } else if(c == 'D') { // hidden option: show/hide dot query graph prop = Prop.DOTPLAN; } else if(c == 'i') { // open database or create main memory representation execute(new Set(Prop.MAINMEM, true), false); execute(new Check(val), verbose); execute(new Set(Prop.MAINMEM, false), false); } else if(c == 'L') { // toggle newline separators newline ^= true; if(serial.length() != 0) serial.append(','); val = serial.append(SerializerProp.S_ITEM_SEPARATOR[0]).append("=\\n"). toString(); prop = Prop.SERIALIZER; } else if(c == 'o') { // change output stream if(out != System.out) out.close(); out = new PrintOutput(val); session().setOutputStream(out); } else if(c == 'q') { // evaluate query execute(new XQuery(val), verbose); console = false; } else if(c == 'Q') { // evaluate file contents or string as query final IO io = IO.get(val); if(io.exists() && !io.isDir()) { query(io); } else { execute(new XQuery(val), verbose); } console = false; } else if(c == 'r') { // hidden option: parse number of runs prop = Prop.RUNS; } else if(c == 's') { // set/add serialization parameter if(serial.length() != 0) serial.append(','); val = serial.append(val).toString(); prop = Prop.SERIALIZER; } else if(c == 'u') { // (de)activate write-back for updates prop = Prop.WRITEBACK; } else if(c == 'v') { // show/hide verbose mode v ^= true; } else if(c == 'V') { // show/hide query info qi ^= true; prop = Prop.QUERYINFO; } else if(c == 'w') { // toggle chopping of whitespaces prop = Prop.CHOP; } else if(c == 'W') { // hidden option: toggle writing of properties before exit writeProps ^= true; } else if(c == 'x') { // show/hide xml query plan prop = Prop.XMLPLAN; qp ^= true; } else if(c == 'X') { // hidden option: show query plan before/after query compilation prop = Prop.COMPPLAN; } else if(c == 'z') { // toggle result serialization prop = Prop.SERIALIZE; } if(prop != null) execute(new Set(prop, val), false); verbose = qi || qp || v; } if(console) { verbose = true; // enter interactive mode Util.outln(CONSOLE + TRY_MORE_X, sa() ? LOCALMODE : CLIENTMODE); console(); } if(writeProps) context.mprop.write(); } finally { quit(); } }
diff --git a/connectors/jdbc/connector/src/main/java/org/apache/manifoldcf/authorities/authorities/jdbc/JDBCAuthority.java b/connectors/jdbc/connector/src/main/java/org/apache/manifoldcf/authorities/authorities/jdbc/JDBCAuthority.java index 0e5d1a1ad..78e8f3ff5 100644 --- a/connectors/jdbc/connector/src/main/java/org/apache/manifoldcf/authorities/authorities/jdbc/JDBCAuthority.java +++ b/connectors/jdbc/connector/src/main/java/org/apache/manifoldcf/authorities/authorities/jdbc/JDBCAuthority.java @@ -1,804 +1,804 @@ /* * Copyright 2012 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.manifoldcf.authorities.authorities.jdbc; import java.io.IOException; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.manifoldcf.agents.interfaces.ServiceInterruption; import org.apache.manifoldcf.authorities.authorities.BaseAuthorityConnector; import org.apache.manifoldcf.authorities.interfaces.AuthorizationResponse; import org.apache.manifoldcf.core.cachemanager.BaseDescription; import org.apache.manifoldcf.core.interfaces.BinaryInput; import org.apache.manifoldcf.core.interfaces.CacheManagerFactory; import org.apache.manifoldcf.core.interfaces.ConfigParams; import org.apache.manifoldcf.core.interfaces.ICacheCreateHandle; import org.apache.manifoldcf.core.interfaces.ICacheDescription; import org.apache.manifoldcf.core.interfaces.ICacheHandle; import org.apache.manifoldcf.core.interfaces.ICacheManager; import org.apache.manifoldcf.core.interfaces.IHTTPOutput; import org.apache.manifoldcf.core.interfaces.IKeystoreManager; import org.apache.manifoldcf.core.interfaces.IPostParameters; import org.apache.manifoldcf.core.interfaces.IThreadContext; import org.apache.manifoldcf.core.interfaces.KeystoreManagerFactory; import org.apache.manifoldcf.core.interfaces.ManifoldCFException; import org.apache.manifoldcf.core.interfaces.StringSet; import org.apache.manifoldcf.core.interfaces.TimeMarker; import org.apache.manifoldcf.core.jdbcpool.WrappedConnection; import org.apache.manifoldcf.crawler.connectors.jdbc.JDBCConnectionFactory; import org.apache.manifoldcf.crawler.connectors.jdbc.JDBCConstants; import org.apache.manifoldcf.crawler.connectors.jdbc.Messages; import org.apache.manifoldcf.crawler.system.Logging; /** * * @author krycek */ public class JDBCAuthority extends BaseAuthorityConnector { public static final String _rcsid = "@(#)$Id: JDBCAuthority.java $"; protected WrappedConnection connection = null; protected String jdbcProvider = null; protected String host = null; protected String databaseName = null; protected String userName = null; protected String password = null; protected String idQuery = null; protected String tokenQuery = null; private long responseLifetime = 60000L; //60sec private int LRUsize = 1000; /** * Cache manager. */ private ICacheManager cacheManager = null; /** * Set thread context. */ @Override public void setThreadContext(IThreadContext tc) throws ManifoldCFException { super.setThreadContext(tc); cacheManager = CacheManagerFactory.make(tc); } /** * Connect. The configuration parameters are included. * * @param configParams are the configuration parameters for this connection. */ @Override public void connect(ConfigParams configParams) { super.connect(configParams); jdbcProvider = configParams.getParameter(JDBCConstants.providerParameter); host = configParams.getParameter(JDBCConstants.hostParameter); databaseName = configParams.getParameter(JDBCConstants.databaseNameParameter); userName = configParams.getParameter(JDBCConstants.databaseUserName); password = configParams.getObfuscatedParameter(JDBCConstants.databasePassword); idQuery = configParams.getParameter(JDBCConstants.databaseUserIdQuery); tokenQuery = configParams.getParameter(JDBCConstants.databaseTokensQuery); } /** * Check status of connection. */ @Override public String check() throws ManifoldCFException { try { WrappedConnection tempConnection = JDBCConnectionFactory.getConnection(jdbcProvider, host, databaseName, userName, password); JDBCConnectionFactory.releaseConnection(tempConnection); return super.check(); } catch (Throwable e) { if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Service interruption in check(): " + e.getMessage(), e); } return "Transient error: " + e.getMessage(); } } /** * Close the connection. Call this before discarding the repository connector. */ @Override public void disconnect() throws ManifoldCFException { if (connection != null) { JDBCConnectionFactory.releaseConnection(connection); connection = null; } host = null; jdbcProvider = null; databaseName = null; userName = null; password = null; super.disconnect(); } /** * Set up a session */ protected void getSession() throws ManifoldCFException, ServiceInterruption { if (connection == null) { if (jdbcProvider == null || jdbcProvider.length() == 0) { throw new ManifoldCFException("Missing parameter '" + JDBCConstants.providerParameter + "'"); } if (host == null || host.length() == 0) { throw new ManifoldCFException("Missing parameter '" + JDBCConstants.hostParameter + "'"); } connection = JDBCConnectionFactory.getConnection(jdbcProvider, host, databaseName, userName, password); } } private String createCacheConnectionString() { StringBuilder sb = new StringBuilder(); sb.append(jdbcProvider).append("|") .append(host).append("|") .append(databaseName).append("|") .append(userName); return sb.toString(); } /** * Obtain the access tokens for a given user name. * * @param userName is the user name or identifier. * @return the response tokens (according to the current authority). (Should * throws an exception only when a condition cannot be properly described * within the authorization response object.) */ @Override public AuthorizationResponse getAuthorizationResponse(String userName) throws ManifoldCFException { // Construct a cache description object ICacheDescription objectDescription = new JdbcAuthorizationResponseDescription(userName, createCacheConnectionString(), this.responseLifetime, this.LRUsize); // Enter the cache ICacheHandle ch = cacheManager.enterCache(new ICacheDescription[]{objectDescription}, null, null); try { ICacheCreateHandle createHandle = cacheManager.enterCreateSection(ch); try { // Lookup the object AuthorizationResponse response = (AuthorizationResponse) cacheManager.lookupObject(createHandle, objectDescription); if (response != null) { return response; } // Create the object. response = getAuthorizationResponseUncached(userName); // Save it in the cache cacheManager.saveObject(createHandle, objectDescription, response); // And return it... return response; } finally { cacheManager.leaveCreateSection(createHandle); } } finally { cacheManager.leaveCache(ch); } } public AuthorizationResponse getAuthorizationResponseUncached(String userName) throws ManifoldCFException { try { getSession(); VariableMap vm = new VariableMap(); addVariable(vm, JDBCConstants.userNameVariable, userName); // Find user id ArrayList paramList = new ArrayList(); StringBuilder sb = new StringBuilder(); substituteQuery(idQuery, vm, sb, paramList); PreparedStatement ps = connection.getConnection().prepareStatement(sb.toString()); loadPS(ps, paramList); ResultSet rs = ps.executeQuery(); if (rs == null) { return RESPONSE_UNREACHABLE; } String uid; if (rs.next()) { uid = rs.getString(1); } else { return RESPONSE_USERNOTFOUND; } if (uid == null || uid.isEmpty()) { return RESPONSE_UNREACHABLE; } // now check tokens vm = new VariableMap(); addVariable(vm, JDBCConstants.userNameVariable, userName); addVariable(vm, JDBCConstants.userIDVariable, uid); sb = new StringBuilder(); paramList = new ArrayList(); substituteQuery(tokenQuery, vm, sb, paramList); ps = connection.getConnection().prepareStatement(sb.toString()); loadPS(ps, paramList); rs = ps.executeQuery(); if (rs == null) { return RESPONSE_UNREACHABLE; } ArrayList<String> tokenArray = new ArrayList<String>(); while (rs.next()) { String token = rs.getString(1); if (token != null && !token.isEmpty()) { tokenArray.add(token); } } String[] tokens = new String[tokenArray.size()]; int k = 0; while (k < tokens.length) { tokens[k] = tokenArray.get(k); k++; } return new AuthorizationResponse(tokens, AuthorizationResponse.RESPONSE_OK); } catch (Exception e) { // Unreachable return RESPONSE_UNREACHABLE; } } // UI support methods. // // These support methods come in two varieties. The first bunch is involved in setting up connection configuration information. The second bunch // is involved in presenting and editing document specification information for a job. The two kinds of methods are accordingly treated differently, // in that the first bunch cannot assume that the current connector object is connected, while the second bunch can. That is why the first bunch // receives a thread context argument for all UI methods, while the second bunch does not need one (since it has already been applied via the connect() // method, above). /** * Output the configuration header section. This method is called in the head * section of the connector's configuration page. Its purpose is to add the * required tabs to the list, and to output any javascript methods that might * be needed by the configuration editing HTML. * * @param threadContext is the local thread context. * @param out is the output to which any HTML should be sent. * @param parameters are the configuration parameters, as they currently * exist, for this connection being configured. * @param tabsArray is an array of tab names. Add to this array any tab names * that are specific to the connector. */ @Override public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, List<String> tabsArray) throws ManifoldCFException, IOException { tabsArray.add(Messages.getString(locale, "JDBCAuthority.DatabaseType")); tabsArray.add(Messages.getString(locale, "JDBCAuthority.Server")); tabsArray.add(Messages.getString(locale, "JDBCAuthority.Credentials")); tabsArray.add(Messages.getString(locale, "JDBCAuthority.Queries")); out.print( "<script type=\"text/javascript\">\n" + "<!--\n" + "function checkConfigForSave()\n" + "{\n" + " if (editconnection.databasehost.value == \"\")\n" + " {\n" + " alert(\"" + Messages.getBodyJavascriptString(locale, "JDBCAuthority.PleaseFillInADatabaseServerName") + "\");\n" + " SelectTab(\"" + Messages.getBodyJavascriptString(locale, "JDBCAuthority.Server") + "\");\n" + " editconnection.databasehost.focus();\n" + " return false;\n" + " }\n" + " if (editconnection.databasename.value == \"\")\n" + " {\n" + " alert(\"" + Messages.getBodyJavascriptString(locale, "JDBCAuthority.PleaseFillInTheNameOfTheDatabase") + "\");\n" + " SelectTab(\"" + Messages.getBodyJavascriptString(locale, "JDBCAuthority.Server") + "\");\n" + " editconnection.databasename.focus();\n" + " return false;\n" + " }\n" + " if (editconnection.username.value == \"\")\n" + " {\n" + " alert(\"" + Messages.getBodyJavascriptString(locale, "JDBCAuthority.PleaseSupplyTheDatabaseUsernameForThisConnection") + "\");\n" + " SelectTab(\"" + Messages.getBodyJavascriptString(locale, "JDBCAuthority.Credentials") + "\");\n" + " editconnection.username.focus();\n" + " return false;\n" + " }\n" + " return true;\n" + "}\n" + "\n" + "//-->\n" + "</script>\n"); } /** * Output the configuration body section. This method is called in the body * section of the connector's configuration page. Its purpose is to present * the required form elements for editing. The coder can presume that the HTML * that is output from this configuration will be within appropriate <html>, * <body>, and <form> tags. The name of the form is "editconnection". * * @param threadContext is the local thread context. * @param out is the output to which any HTML should be sent. * @param parameters are the configuration parameters, as they currently * exist, for this connection being configured. * @param tabName is the current tab name. */ @Override public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, String tabName) throws ManifoldCFException, IOException { String lJdbcProvider = parameters.getParameter(JDBCConstants.providerParameter); if (lJdbcProvider == null) { lJdbcProvider = "oracle:thin:@"; } String lHost = parameters.getParameter(JDBCConstants.hostParameter); if (lHost == null) { lHost = "localhost"; } String lDatabaseName = parameters.getParameter(JDBCConstants.databaseNameParameter); if (lDatabaseName == null) { lDatabaseName = "database"; } String databaseUser = parameters.getParameter(JDBCConstants.databaseUserName); if (databaseUser == null) { databaseUser = ""; } String databasePassword = parameters.getObfuscatedParameter(JDBCConstants.databasePassword); if (databasePassword == null) { databasePassword = ""; } else { - databasePassword = out.mapPasswordToKey(password); + databasePassword = out.mapPasswordToKey(databasePassword); } String lIdQuery = parameters.getParameter(JDBCConstants.databaseUserIdQuery); if (lIdQuery == null) { lIdQuery = "SELECT idfield FROM usertable WHERE login = $(USERNAME)"; } String lTokenQuery = parameters.getParameter(JDBCConstants.databaseTokensQuery); if (lTokenQuery == null) { lTokenQuery = "SELECT groupnamefield FROM grouptable WHERE user_id = $(UID) or login = $(USERNAME)"; } // "Database Type" tab if (tabName.equals(Messages.getString(locale, "JDBCAuthority.DatabaseType"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.DatabaseType2") + "</nobr></td><td class=\"value\">\n" + " <select multiple=\"false\" name=\"databasetype\" size=\"2\">\n" + " <option value=\"oracle:thin:@\" " + (lJdbcProvider.equals("oracle:thin:@") ? "selected=\"selected\"" : "") + ">Oracle</option>\n" + " <option value=\"postgresql:\" " + (lJdbcProvider.equals("postgresql:") ? "selected=\"selected\"" : "") + ">Postgres SQL</option>\n" + " <option value=\"jtds:sqlserver:\" " + (lJdbcProvider.equals("jtds:sqlserver:") ? "selected=\"selected\"" : "") + ">MS SQL Server (&gt; V6.5)</option>\n" + " <option value=\"jtds:sybase:\" " + (lJdbcProvider.equals("jtds:sybase:") ? "selected=\"selected\"" : "") + ">Sybase (&gt;= V10)</option>\n" + " <option value=\"mysql:\" " + (lJdbcProvider.equals("mysql:") ? "selected=\"selected\"" : "") + ">MySQL (&gt;= V5)</option>\n" + " </select>\n" + " </td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"databasetype\" value=\"" + lJdbcProvider + "\"/>\n"); } // "Server" tab if (tabName.equals(Messages.getString(locale, "JDBCAuthority.Server"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.DatabaseHostAndPort") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"64\" name=\"databasehost\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lHost) + "\"/></td>\n" + " </tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.DatabaseServiceNameOrInstanceDatabase") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"32\" name=\"databasename\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lDatabaseName) + "\"/></td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"databasehost\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lHost) + "\"/>\n" + "<input type=\"hidden\" name=\"databasename\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lDatabaseName) + "\"/>\n"); } // "Credentials" tab if (tabName.equals(Messages.getString(locale, "JDBCAuthority.Credentials"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.UserName") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"32\" name=\"username\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseUser) + "\"/></td>\n" + " </tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.Password") + "</nobr></td><td class=\"value\"><input type=\"password\" size=\"32\" name=\"password\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databasePassword) + "\"/></td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"username\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseUser) + "\"/>\n" + "<input type=\"hidden\" name=\"password\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databasePassword) + "\"/>\n"); } if (tabName.equals(Messages.getString(locale, "JDBCAuthority.Queries"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.UserIdQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.returnUserIdOrEmptyResultset") + "</nobr></td>\n" + " <td class=\"value\"><textarea name=\"idquery\" cols=\"64\" rows=\"6\">" + org.apache.manifoldcf.ui.util.Encoder.bodyEscape(lIdQuery) + "</textarea></td>\n" + " </tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.TokenQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.returnTokensForUser") + "</nobr></td>\n" + " <td class=\"value\"><textarea name=\"tokenquery\" cols=\"64\" rows=\"6\">" + org.apache.manifoldcf.ui.util.Encoder.bodyEscape(lTokenQuery) + "</textarea></td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"idquery\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lIdQuery) + "\"/>\n" + "<input type=\"hidden\" name=\"tokenquery\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lTokenQuery) + "\"/>\n"); } } /** * Process a configuration post. This method is called at the start of the * connector's configuration page, whenever there is a possibility that form * data for a connection has been posted. Its purpose is to gather form * information and modify the configuration parameters accordingly. The name * of the posted form is "editconnection". * * @param threadContext is the local thread context. * @param variableContext is the set of variables available from the post, * including binary file post information. * @param parameters are the configuration parameters, as they currently * exist, for this connection being configured. * @return null if all is well, or a string error message if there is an error * that should prevent saving of the connection (and cause a redirection to an * error page). */ @Override public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext, Locale locale, ConfigParams parameters) throws ManifoldCFException { String type = variableContext.getParameter("databasetype"); if (type != null) { parameters.setParameter(JDBCConstants.providerParameter, type); } String lHost = variableContext.getParameter("databasehost"); if (lHost != null) { parameters.setParameter(JDBCConstants.hostParameter, lHost); } String lDatabaseName = variableContext.getParameter("databasename"); if (lDatabaseName != null) { parameters.setParameter(JDBCConstants.databaseNameParameter, lDatabaseName); } String lUserName = variableContext.getParameter("username"); if (lUserName != null) { parameters.setParameter(JDBCConstants.databaseUserName, lUserName); } String lPassword = variableContext.getParameter("password"); if (lPassword != null) { parameters.setObfuscatedParameter(JDBCConstants.databasePassword, variableContext.mapKeyToPassword(lPassword)); } String lIdQuery = variableContext.getParameter("idquery"); if (lIdQuery != null) { parameters.setParameter(JDBCConstants.databaseUserIdQuery, lIdQuery); } String lTokenQuery = variableContext.getParameter("tokenquery"); if (lTokenQuery != null) { parameters.setParameter(JDBCConstants.databaseTokensQuery, lTokenQuery); } return null; } /** * View configuration. This method is called in the body section of the * connector's view configuration page. Its purpose is to present the * connection information to the user. The coder can presume that the HTML * that is output from this configuration will be within appropriate <html> * and <body> tags. * * @param threadContext is the local thread context. * @param out is the output to which any HTML should be sent. * @param parameters are the configuration parameters, as they currently * exist, for this connection being configured. */ @Override public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters) throws ManifoldCFException, IOException { out.print( "<table class=\"displaytable\">\n" + " <tr>\n" + " <td class=\"description\" colspan=\"1\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.Parameters") + "</nobr></td>\n" + " <td class=\"value\" colspan=\"3\">\n"); Iterator iter = parameters.listParameters(); while (iter.hasNext()) { String param = (String) iter.next(); String value = parameters.getParameter(param); if (param.length() >= "password".length() && param.substring(param.length() - "password".length()).equalsIgnoreCase("password")) { out.print( " <nobr>" + org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param) + "=********</nobr><br/>\n"); } else if (param.length() >= "keystore".length() && param.substring(param.length() - "keystore".length()).equalsIgnoreCase("keystore")) { IKeystoreManager kmanager = KeystoreManagerFactory.make("", value); out.print( " <nobr>" + org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param) + "=&lt;" + Integer.toString(kmanager.getContents().length) + " certificate(s)&gt;</nobr><br/>\n"); } else { out.print( " <nobr>" + org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param) + "=" + org.apache.manifoldcf.ui.util.Encoder.bodyEscape(value) + "</nobr><br/>\n"); } } out.print( " </td>\n" + " </tr>\n" + "</table>\n"); } /** * Given a query, and a parameter map, substitute it. Each variable * substitutes the string, and it also substitutes zero or more query * parameters. */ protected static void substituteQuery(String inputString, VariableMap inputMap, StringBuilder outputQuery, ArrayList outputParams) throws ManifoldCFException { // We are looking for strings that look like this: $(something) // Right at the moment we don't care even about quotes, so we just want to look for $(. int startIndex = 0; while (true) { int nextIndex = inputString.indexOf("$(", startIndex); if (nextIndex == -1) { outputQuery.append(inputString.substring(startIndex)); break; } int endIndex = inputString.indexOf(")", nextIndex); if (endIndex == -1) { outputQuery.append(inputString.substring(startIndex)); break; } String variableName = inputString.substring(nextIndex + 2, endIndex); VariableMapItem item = inputMap.getVariable(variableName); if (item == null) { throw new ManifoldCFException("No such substitution variable: $(" + variableName + ")"); } outputQuery.append(inputString.substring(startIndex, nextIndex)); outputQuery.append(item.getValue()); ArrayList inputParams = item.getParameters(); if (inputParams != null) { int i = 0; while (i < inputParams.size()) { Object x = inputParams.get(i++); outputParams.add(x); } } startIndex = endIndex + 1; } } /** * Add string query variables */ protected static void addVariable(VariableMap map, String varName, String variable) { ArrayList params = new ArrayList(); params.add(variable); map.addVariable(varName, "?", params); } /** * Add string query constants */ protected static void addConstant(VariableMap map, String varName, String value) { map.addVariable(varName, value, null); } // pass params to preparedStatement protected static void loadPS(PreparedStatement ps, ArrayList data) throws java.sql.SQLException, ManifoldCFException { if (data != null) { for (int i = 0; i < data.size(); i++) { // If the input type is a string, then set it as such. // Otherwise, if it's an input stream, we make a blob out of it. Object x = data.get(i); if (x instanceof String) { String value = (String) x; // letting database do lame conversion! ps.setString(i + 1, value); } if (x instanceof BinaryInput) { BinaryInput value = (BinaryInput) x; // System.out.println("Blob length on write = "+Long.toString(value.getLength())); // The oracle driver does a binary conversion to base 64 when writing data // into a clob column using a binary stream operator. Since at this // point there is no way to distinguish the two, and since our tests use CLOB, // this code doesn't work for them. // So, for now, use the ascii stream method. //ps.setBinaryStream(i+1,value.getStream(),(int)value.getLength()); ps.setAsciiStream(i + 1, value.getStream(), (int) value.getLength()); } if (x instanceof java.util.Date) { ps.setDate(i + 1, new java.sql.Date(((java.util.Date) x).getTime())); } if (x instanceof Long) { ps.setLong(i + 1, ((Long) x).longValue()); } if (x instanceof TimeMarker) { ps.setTimestamp(i + 1, new java.sql.Timestamp(((Long) x).longValue())); } if (x instanceof Double) { ps.setDouble(i + 1, ((Double) x).doubleValue()); } if (x instanceof Integer) { ps.setInt(i + 1, ((Integer) x).intValue()); } if (x instanceof Float) { ps.setFloat(i + 1, ((Float) x).floatValue()); } } } } /** * Variable map entry. */ protected static class VariableMapItem { protected String value; protected ArrayList params; /** * Constructor. */ public VariableMapItem(String value, ArrayList params) { this.value = value; this.params = params; } /** * Get value. */ public String getValue() { return value; } /** * Get parameters. */ public ArrayList getParameters() { return params; } } /** * Variable map. */ protected static class VariableMap { protected Map variableMap = new HashMap(); /** * Constructor */ public VariableMap() { } /** * Add a variable map entry */ public void addVariable(String variableName, String value, ArrayList parameters) { VariableMapItem e = new VariableMapItem(value, parameters); variableMap.put(variableName, e); } /** * Get a variable map entry */ public VariableMapItem getVariable(String variableName) { return (VariableMapItem) variableMap.get(variableName); } } protected static StringSet emptyStringSet = new StringSet(); /** * This is the cache object descriptor for cached access tokens from this * connector. */ protected class JdbcAuthorizationResponseDescription extends BaseDescription { /** * The user name */ protected String userName; /** * LDAP connection string with server name and base DN */ protected String connectionString; /** * The response lifetime */ protected long responseLifetime; /** * The expiration time */ protected long expirationTime = -1; /** * Constructor. */ public JdbcAuthorizationResponseDescription(String userName, String connectionString, long responseLifetime, int LRUsize) { super("JDBCAuthority", LRUsize); this.userName = userName; this.connectionString = connectionString; this.responseLifetime = responseLifetime; } /** * Return the invalidation keys for this object. */ public StringSet getObjectKeys() { return emptyStringSet; } /** * Get the critical section name, used for synchronizing the creation of the * object */ public String getCriticalSectionName() { StringBuilder sb = new StringBuilder(getClass().getName()); sb.append("-").append(userName).append("-").append(connectionString); return sb.toString(); } /** * Return the object expiration interval */ @Override public long getObjectExpirationTime(long currentTime) { if (expirationTime == -1) { expirationTime = currentTime + responseLifetime; } return expirationTime; } @Override public int hashCode() { return userName.hashCode() + connectionString.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof JdbcAuthorizationResponseDescription)) { return false; } JdbcAuthorizationResponseDescription ard = (JdbcAuthorizationResponseDescription) o; if (!ard.userName.equals(userName)) { return false; } if (!ard.connectionString.equals(connectionString)) { return false; } return true; } } }
true
true
public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, String tabName) throws ManifoldCFException, IOException { String lJdbcProvider = parameters.getParameter(JDBCConstants.providerParameter); if (lJdbcProvider == null) { lJdbcProvider = "oracle:thin:@"; } String lHost = parameters.getParameter(JDBCConstants.hostParameter); if (lHost == null) { lHost = "localhost"; } String lDatabaseName = parameters.getParameter(JDBCConstants.databaseNameParameter); if (lDatabaseName == null) { lDatabaseName = "database"; } String databaseUser = parameters.getParameter(JDBCConstants.databaseUserName); if (databaseUser == null) { databaseUser = ""; } String databasePassword = parameters.getObfuscatedParameter(JDBCConstants.databasePassword); if (databasePassword == null) { databasePassword = ""; } else { databasePassword = out.mapPasswordToKey(password); } String lIdQuery = parameters.getParameter(JDBCConstants.databaseUserIdQuery); if (lIdQuery == null) { lIdQuery = "SELECT idfield FROM usertable WHERE login = $(USERNAME)"; } String lTokenQuery = parameters.getParameter(JDBCConstants.databaseTokensQuery); if (lTokenQuery == null) { lTokenQuery = "SELECT groupnamefield FROM grouptable WHERE user_id = $(UID) or login = $(USERNAME)"; } // "Database Type" tab if (tabName.equals(Messages.getString(locale, "JDBCAuthority.DatabaseType"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.DatabaseType2") + "</nobr></td><td class=\"value\">\n" + " <select multiple=\"false\" name=\"databasetype\" size=\"2\">\n" + " <option value=\"oracle:thin:@\" " + (lJdbcProvider.equals("oracle:thin:@") ? "selected=\"selected\"" : "") + ">Oracle</option>\n" + " <option value=\"postgresql:\" " + (lJdbcProvider.equals("postgresql:") ? "selected=\"selected\"" : "") + ">Postgres SQL</option>\n" + " <option value=\"jtds:sqlserver:\" " + (lJdbcProvider.equals("jtds:sqlserver:") ? "selected=\"selected\"" : "") + ">MS SQL Server (&gt; V6.5)</option>\n" + " <option value=\"jtds:sybase:\" " + (lJdbcProvider.equals("jtds:sybase:") ? "selected=\"selected\"" : "") + ">Sybase (&gt;= V10)</option>\n" + " <option value=\"mysql:\" " + (lJdbcProvider.equals("mysql:") ? "selected=\"selected\"" : "") + ">MySQL (&gt;= V5)</option>\n" + " </select>\n" + " </td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"databasetype\" value=\"" + lJdbcProvider + "\"/>\n"); } // "Server" tab if (tabName.equals(Messages.getString(locale, "JDBCAuthority.Server"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.DatabaseHostAndPort") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"64\" name=\"databasehost\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lHost) + "\"/></td>\n" + " </tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.DatabaseServiceNameOrInstanceDatabase") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"32\" name=\"databasename\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lDatabaseName) + "\"/></td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"databasehost\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lHost) + "\"/>\n" + "<input type=\"hidden\" name=\"databasename\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lDatabaseName) + "\"/>\n"); } // "Credentials" tab if (tabName.equals(Messages.getString(locale, "JDBCAuthority.Credentials"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.UserName") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"32\" name=\"username\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseUser) + "\"/></td>\n" + " </tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.Password") + "</nobr></td><td class=\"value\"><input type=\"password\" size=\"32\" name=\"password\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databasePassword) + "\"/></td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"username\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseUser) + "\"/>\n" + "<input type=\"hidden\" name=\"password\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databasePassword) + "\"/>\n"); } if (tabName.equals(Messages.getString(locale, "JDBCAuthority.Queries"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.UserIdQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.returnUserIdOrEmptyResultset") + "</nobr></td>\n" + " <td class=\"value\"><textarea name=\"idquery\" cols=\"64\" rows=\"6\">" + org.apache.manifoldcf.ui.util.Encoder.bodyEscape(lIdQuery) + "</textarea></td>\n" + " </tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.TokenQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.returnTokensForUser") + "</nobr></td>\n" + " <td class=\"value\"><textarea name=\"tokenquery\" cols=\"64\" rows=\"6\">" + org.apache.manifoldcf.ui.util.Encoder.bodyEscape(lTokenQuery) + "</textarea></td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"idquery\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lIdQuery) + "\"/>\n" + "<input type=\"hidden\" name=\"tokenquery\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lTokenQuery) + "\"/>\n"); } }
public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, String tabName) throws ManifoldCFException, IOException { String lJdbcProvider = parameters.getParameter(JDBCConstants.providerParameter); if (lJdbcProvider == null) { lJdbcProvider = "oracle:thin:@"; } String lHost = parameters.getParameter(JDBCConstants.hostParameter); if (lHost == null) { lHost = "localhost"; } String lDatabaseName = parameters.getParameter(JDBCConstants.databaseNameParameter); if (lDatabaseName == null) { lDatabaseName = "database"; } String databaseUser = parameters.getParameter(JDBCConstants.databaseUserName); if (databaseUser == null) { databaseUser = ""; } String databasePassword = parameters.getObfuscatedParameter(JDBCConstants.databasePassword); if (databasePassword == null) { databasePassword = ""; } else { databasePassword = out.mapPasswordToKey(databasePassword); } String lIdQuery = parameters.getParameter(JDBCConstants.databaseUserIdQuery); if (lIdQuery == null) { lIdQuery = "SELECT idfield FROM usertable WHERE login = $(USERNAME)"; } String lTokenQuery = parameters.getParameter(JDBCConstants.databaseTokensQuery); if (lTokenQuery == null) { lTokenQuery = "SELECT groupnamefield FROM grouptable WHERE user_id = $(UID) or login = $(USERNAME)"; } // "Database Type" tab if (tabName.equals(Messages.getString(locale, "JDBCAuthority.DatabaseType"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.DatabaseType2") + "</nobr></td><td class=\"value\">\n" + " <select multiple=\"false\" name=\"databasetype\" size=\"2\">\n" + " <option value=\"oracle:thin:@\" " + (lJdbcProvider.equals("oracle:thin:@") ? "selected=\"selected\"" : "") + ">Oracle</option>\n" + " <option value=\"postgresql:\" " + (lJdbcProvider.equals("postgresql:") ? "selected=\"selected\"" : "") + ">Postgres SQL</option>\n" + " <option value=\"jtds:sqlserver:\" " + (lJdbcProvider.equals("jtds:sqlserver:") ? "selected=\"selected\"" : "") + ">MS SQL Server (&gt; V6.5)</option>\n" + " <option value=\"jtds:sybase:\" " + (lJdbcProvider.equals("jtds:sybase:") ? "selected=\"selected\"" : "") + ">Sybase (&gt;= V10)</option>\n" + " <option value=\"mysql:\" " + (lJdbcProvider.equals("mysql:") ? "selected=\"selected\"" : "") + ">MySQL (&gt;= V5)</option>\n" + " </select>\n" + " </td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"databasetype\" value=\"" + lJdbcProvider + "\"/>\n"); } // "Server" tab if (tabName.equals(Messages.getString(locale, "JDBCAuthority.Server"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.DatabaseHostAndPort") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"64\" name=\"databasehost\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lHost) + "\"/></td>\n" + " </tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.DatabaseServiceNameOrInstanceDatabase") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"32\" name=\"databasename\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lDatabaseName) + "\"/></td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"databasehost\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lHost) + "\"/>\n" + "<input type=\"hidden\" name=\"databasename\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lDatabaseName) + "\"/>\n"); } // "Credentials" tab if (tabName.equals(Messages.getString(locale, "JDBCAuthority.Credentials"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.UserName") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"32\" name=\"username\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseUser) + "\"/></td>\n" + " </tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.Password") + "</nobr></td><td class=\"value\"><input type=\"password\" size=\"32\" name=\"password\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databasePassword) + "\"/></td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"username\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseUser) + "\"/>\n" + "<input type=\"hidden\" name=\"password\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databasePassword) + "\"/>\n"); } if (tabName.equals(Messages.getString(locale, "JDBCAuthority.Queries"))) { out.print( "<table class=\"displaytable\">\n" + " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.UserIdQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.returnUserIdOrEmptyResultset") + "</nobr></td>\n" + " <td class=\"value\"><textarea name=\"idquery\" cols=\"64\" rows=\"6\">" + org.apache.manifoldcf.ui.util.Encoder.bodyEscape(lIdQuery) + "</textarea></td>\n" + " </tr>\n" + " <tr>\n" + " <td class=\"description\"><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.TokenQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale, "JDBCAuthority.returnTokensForUser") + "</nobr></td>\n" + " <td class=\"value\"><textarea name=\"tokenquery\" cols=\"64\" rows=\"6\">" + org.apache.manifoldcf.ui.util.Encoder.bodyEscape(lTokenQuery) + "</textarea></td>\n" + " </tr>\n" + "</table>\n"); } else { out.print( "<input type=\"hidden\" name=\"idquery\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lIdQuery) + "\"/>\n" + "<input type=\"hidden\" name=\"tokenquery\" value=\"" + org.apache.manifoldcf.ui.util.Encoder.attributeEscape(lTokenQuery) + "\"/>\n"); } }
diff --git a/src/de/unifr/acp/trafo/TransClass.java b/src/de/unifr/acp/trafo/TransClass.java index 23b4572..d4c78c5 100644 --- a/src/de/unifr/acp/trafo/TransClass.java +++ b/src/de/unifr/acp/trafo/TransClass.java @@ -1,998 +1,997 @@ package de.unifr.acp.trafo; import java.io.IOException; import java.lang.reflect.Modifier; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtBehavior; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtField; import javassist.CtMethod; import javassist.CtNewMethod; import javassist.NotFoundException; import javassist.bytecode.AnnotationsAttribute; import javassist.bytecode.AttributeInfo; import javassist.bytecode.ClassFile; import javassist.bytecode.ConstPool; import javassist.bytecode.ParameterAnnotationsAttribute; import javassist.bytecode.SyntheticAttribute; import javassist.bytecode.annotation.Annotation; import javassist.bytecode.annotation.ClassMemberValue; import javassist.bytecode.annotation.IntegerMemberValue; import javassist.bytecode.annotation.StringMemberValue; import javassist.expr.Cast; import javassist.expr.ConstructorCall; import javassist.expr.ExprEditor; import javassist.expr.FieldAccess; import javassist.expr.Handler; import javassist.expr.Instanceof; import javassist.expr.MethodCall; import javassist.expr.NewArray; import javassist.expr.NewExpr; import de.unifr.acp.annot.Grant; import de.unifr.acp.templates.TraversalTarget__; // TODO: consider fully qualified field names public class TransClass { static { try { logger = Logger.getLogger("de.unifr.acp.trafo.TransClass"); fh = new FileHandler("mylog.txt"); TransClass.logger.addHandler(TransClass.fh); TransClass.logger.setLevel(Level.ALL); } catch (SecurityException | IOException e) { throw new RuntimeException(e); } } private static Logger logger; private static FileHandler fh; private static final String TRAVERSAL_TARGET = "de.unifr.acp.templates.TraversalTarget__"; private static final String FST_CACHE_FIELD_NAME = "$fstMap"; //private final CtClass objectClass = ClassPool.getDefault().get(Object.class.getName()); public final String FILTER_TRANSFORM_REGEX_DEFAULT = "java\\..*"; private String filterTransformRegex = FILTER_TRANSFORM_REGEX_DEFAULT; public final String FILTER_VISIT_REGEX_DEFAULT = "java\\..*"; private String filterVisitRegex = FILTER_VISIT_REGEX_DEFAULT; //private final Map<CtClass, Boolean> visited = new HashMap<CtClass, Boolean>(); //private final HashSet<CtClass> visited = new HashSet<CtClass>(); //private final HashSet<CtClass> transformed = new HashSet<CtClass>(); //private final Queue<CtClass> pending; // protected Set<CtClass> getVisited() { // return Collections.unmodifiableSet(visited); // } // protected Collection<CtClass> getPending() { // return Collections.unmodifiableCollection(pending); // } /** * Transformer class capable of statically adding heap traversal code to a * set of reachable classes. * * @param classname * the name of the class forming the starting point for the * reachable classes * @throws NotFoundException */ protected TransClass() throws NotFoundException { } /** * Transforms all classes that are reachable from the class corresponding * to the specified class name. * @param className the class name of the class spanning a reachable classes tree * @throws ClassNotFoundException */ public static Set<CtClass> transformHierarchy(String className) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { TransClass tc = new TransClass(); Set<CtClass> reachable = tc.computeReachableClasses(ClassPool.getDefault().get(className)); Set<CtClass> transformed = tc.performTransformation(reachable); return transformed; } public static Set<CtClass> defaultAnnotateHierarchy(String className) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { TransClass tc = new TransClass(); Set<CtClass> reachable = tc.computeReachableClasses(ClassPool.getDefault().get(className)); Set<CtClass> transformed = tc.performDefaultAnnotatation(reachable); return transformed; } /** * Transforms all classes that are reachable from the class corresponding * to the specified class name and flushes the resulting classes to the * specified output directory. * @param className the class name of the class spanning a reachable classes tree * @param outputDir the relative output directory * @throws ClassNotFoundException */ public static void transformAndFlushHierarchy(String className, String outputDir) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { Set<CtClass> transformed = transformHierarchy(className); TransClass.flushTransform(transformed, outputDir); } public static void defaultAnnotateAndFlushHierarchy(String className, String outputDir) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { Set<CtClass> transformed = defaultAnnotateHierarchy(className); TransClass.flushTransform(transformed, outputDir); } protected Set<CtClass> computeReachableClasses(CtClass root) throws NotFoundException, IOException, CannotCompileException { Queue<CtClass> pending = new LinkedList<CtClass>(); HashSet<CtClass> visited = new HashSet<CtClass>(); pending.add(root); while (!pending.isEmpty()) { CtClass clazz = pending.remove(); if (!visited.contains(clazz)) { doTraverse(clazz, pending, visited); } } return visited; } /* * Helper method for <code>computeReachableClasses</code>. Traverses the * specified target class and adds it to the list of visited classes. Adds * all classes the class' fields to queue of pending classes, if not already * visited. */ private void doTraverse(CtClass target, Queue<CtClass> pending, Set<CtClass> visited) throws NotFoundException { visited.add(target); // collect all types this type refers to in this set final Set<CtClass> referredTypes = new HashSet<CtClass>(); CtClass superclazz = target.getSuperclass(); if (superclazz != null) { referredTypes.add(superclazz); } // for (CtClass clazz : target.getInterfaces()) { // referredTypes.add(clazz); // } CtField[] fs = target.getDeclaredFields(); for (CtField f : fs) { CtClass ft = f.getType(); if (ft.isPrimitive()) continue; referredTypes.add(ft); } List<CtMethod> methods = Arrays.asList(target.getMethods()); for (CtMethod method : methods) { List<CtClass> returnType = Arrays.asList(method.getReturnType()); referredTypes.addAll(returnType); } List<CtConstructor> ctors = Arrays.asList(target.getConstructors()); List<CtBehavior> methodsAndCtors = new ArrayList<CtBehavior>(); methodsAndCtors.addAll(methods); methodsAndCtors.addAll(ctors); for (CtBehavior methodOrCtor : methodsAndCtors) { List<CtClass> exceptionTypes = Arrays.asList(methodOrCtor.getExceptionTypes()); referredTypes.addAll(exceptionTypes); List<CtClass> paramTypes = Arrays.asList(methodOrCtor.getParameterTypes()); referredTypes.addAll(paramTypes); try { final List<NotFoundException> notFoundexceptions = new ArrayList<NotFoundException>(1); methodOrCtor.instrument(new ExprEditor() { public void edit(NewExpr expr) throws CannotCompileException { try { CtClass type = expr.getConstructor().getDeclaringClass(); logger.finer("Reference to instantiated type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(Instanceof expr) throws CannotCompileException { try { CtClass type = expr.getType(); logger.finer("Reference to instanceof right-hand side type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(NewArray expr) throws CannotCompileException { try { CtClass type = expr.getComponentType(); logger.finer("Reference to array component type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(MethodCall expr) throws CannotCompileException { try { CtClass type = expr.getMethod().getDeclaringClass(); logger.finer("Reference to method-declaring type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(Handler expr) throws CannotCompileException { try { CtClass type = expr.getType(); logger.finer("Reference to handler type " + ((type != null) ? type.getName() : type) + " at " + expr.getFileName() + ":" + expr.getLineNumber()); // type can be null in case of synchronized blocks // which are compiled to handler for type 'any' if (type != null) { referredTypes.add(type); } } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(FieldAccess expr) throws CannotCompileException { try { CtClass type = expr.getField().getDeclaringClass(); logger.finer("Reference to field-declaring type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); methodOrCtor.instrument(new ExprEditor() { public void edit(Cast expr) throws CannotCompileException { try { CtClass type = expr.getType(); logger.finer("Reference to cast target type " + type.getName() + " at " + expr.getFileName() + ":" + expr.getLineNumber()); referredTypes.add(type); } catch (NotFoundException e) { notFoundexceptions.add(e); } } }); if (!notFoundexceptions.isEmpty()) { throw notFoundexceptions.get(0); } } catch (CannotCompileException e) { // we do not compile and therefore expect no such exception assert(false); } } // basic filtering of referred types for (CtClass type : referredTypes) { if (type.isPrimitive()) continue; if (type.getName().matches(filterVisitRegex)) continue; enter(type, pending, visited); } } /* * Helper method for <code>computeReachableClasses</code>. Adds the * specified class to queue of pending classes, if not already visited. */ private void enter(CtClass clazz, Queue<CtClass> pending, Set<CtClass> visited) { logger.entering(TransClass.class.getSimpleName(), "enter", (clazz != null) ? clazz.getName() : clazz); if (!visited.contains(clazz)) { pending.add(clazz); } logger.exiting("TransClass", "enter"); } private Set<CtClass> filterClassesToTransform(Set<CtClass> visited) { HashSet<CtClass> toTransform = new HashSet<CtClass>(); for (CtClass clazz : visited) { if (!clazz.getName().matches(filterTransformRegex)) { toTransform.add(clazz); } } return toTransform; } protected Set<CtClass> performDefaultAnnotatation(Set<CtClass> classes) throws NotFoundException { Set<CtClass> toTransform = filterClassesToTransform(classes); if (logger.isLoggable(Level.FINEST)) { StringBuilder sb = new StringBuilder(); for (CtClass visitedClazz : toTransform) { sb.append(visitedClazz.getName()+"\n"); } logger.finest("Classes to transform:\n" +sb.toString()); } final HashSet<CtClass> transformed = new HashSet<CtClass>(); for (CtClass cc : toTransform) { if (cc.isFrozen()) { continue; } // collect all methods and constructors // List<CtMethod> ownMethods = Arrays.asList(cc.getDeclaredMethods()); // List<CtConstructor> ctors = Arrays.asList(cc.getConstructors()); // List<CtBehavior> methodsAndCtors = new ArrayList<CtBehavior>(); // methodsAndCtors.addAll(ownMethods); // methodsAndCtors.addAll(ctors); List<CtBehavior> methodsAndCtors = Arrays.asList(cc.getDeclaredBehaviors()); ClassFile ccFile = cc.getClassFile(); ConstPool constpool = ccFile.getConstPool(); for (CtBehavior methodOrCtor : methodsAndCtors) { logger.fine("Annotating method or ctor: " + ((methodOrCtor != null) ? methodOrCtor.getLongName() : methodOrCtor)); // create and add the method-level annotation AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag); Annotation annot = new Annotation(Grant.class.getName(), constpool); annot.addMemberValue("value", new StringMemberValue("this.*", constpool)); attr.addAnnotation(annot); methodOrCtor.getMethodInfo().addAttribute(attr); // create and add the parameter-level annotation final CtClass[] parameterTypes = methodOrCtor.getParameterTypes(); Annotation parameterAnnotation = new Annotation( Grant.class.getName(), constpool); StringMemberValue parameterMemberValue = new StringMemberValue( "*", constpool); parameterAnnotation.addMemberValue("value", parameterMemberValue); logger.fine("parameterAnnotation: " + parameterAnnotation); AttributeInfo paramAttributeInfo = methodOrCtor.getMethodInfo().getAttribute(ParameterAnnotationsAttribute.visibleTag); // or invisibleTag logger.finest("paramAttributeInfo: " + paramAttributeInfo); if (paramAttributeInfo != null) { ParameterAnnotationsAttribute parameterAtrribute = ((ParameterAnnotationsAttribute) paramAttributeInfo); Annotation[][] paramAnnots = parameterAtrribute .getAnnotations(); for (int orderNum = 0; orderNum < paramAnnots.length; orderNum++) { Annotation[] addAnno = paramAnnots[orderNum]; if (!parameterTypes[orderNum].isPrimitive()) { Annotation[] newAnno = null; if (addAnno.length == 0) { newAnno = new Annotation[1]; } else { newAnno = Arrays.copyOf(addAnno, addAnno.length + 1); } newAnno[addAnno.length] = parameterAnnotation; paramAnnots[orderNum] = newAnno; } } parameterAtrribute.setAnnotations(paramAnnots); } else { ParameterAnnotationsAttribute parameterAtrribute = new ParameterAnnotationsAttribute( constpool, ParameterAnnotationsAttribute.visibleTag); Annotation[][] paramAnnots = new Annotation[parameterCountOf(methodOrCtor)][]; for (int orderNum = 0; orderNum < paramAnnots.length; orderNum++) { Annotation[] annots = {parameterAnnotation}; if (parameterTypes[orderNum].isPrimitive()) { annots = new Annotation[0]; } paramAnnots[orderNum]= annots; } parameterAtrribute.setAnnotations(paramAnnots); methodOrCtor.getMethodInfo().addAttribute(parameterAtrribute); } } } // conservatively assume all classes have been transformed transformed.addAll(toTransform); return transformed; } /* * Transforms all reachable classes. */ protected Set<CtClass> performTransformation(Set<CtClass> classes) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { ClassPool.getDefault().importPackage("java.util"); Set<CtClass> toTransform = filterClassesToTransform(classes); if (logger.isLoggable(Level.FINEST)) { StringBuilder sb = new StringBuilder(); for (CtClass visitedClazz : toTransform) { sb.append(visitedClazz.getName()+"\n"); } logger.finest("Classes to transform:\n" +sb.toString()); } final HashSet<CtClass> transformed = new HashSet<CtClass>(); for (CtClass clazz : toTransform) { Deque<CtClass> stack = new ArrayDeque<CtClass>(); CtClass current = clazz; stack.push(current); while (toTransform.contains(current.getSuperclass())) { current = current.getSuperclass(); stack.push(current); } while (!stack.isEmpty()) { CtClass superclass = stack.pop(); // if this does not hold we might miss some superclass fields assert (transformed.contains(superclass.getSuperclass()) == toTransform .contains(superclass.getSuperclass())); doTransform(superclass, transformed.contains(superclass.getSuperclass())); transformed.add(superclass); } } if (logger.isLoggable(Level.FINEST)) { StringBuilder sb = new StringBuilder(); for (CtClass transformedClazz : transformed) { sb.append(transformedClazz.getName()+"\n"); } logger.finest("Transformed types:\n" +sb.toString()); } return transformed; } /** * Flushes all reachable classes back to disk. * @param outputDir the relative output directory */ protected static void flushTransform(Set<CtClass> classes, String outputDir) throws NotFoundException, IOException, CannotCompileException { for (CtClass tc : classes) { if (!tc.isArray()) { tc.writeFile(outputDir); for (CtClass inner : tc.getNestedClasses()) { inner.writeFile(outputDir); } } } // String[] libClassNames = { "de.unifr.acp.templates.TraversalTarget__", // "de.unifr.acp.templates.TraversalImpl", // "de.unifr.acp.templates.Traversal__", // "de.unifr.acp.templates.Global", "de.unifr.acp.fst.Permission" }; // ClassPool defaultPool = ClassPool.getDefault(); // CtClass[] libClasses = defaultPool.get(libClassNames); // for (CtClass libClass : libClasses) { // libClass.writeFile(outputDir); // } } /** * Transforms a single class if not already done. * @param target the class to transform * @param hasTransformedSuperclass the target has an already transformed superclass * @throws NotFoundException * @throws IOException * @throws CannotCompileException * @throws ClassNotFoundException */ public static void doTransform(CtClass target, boolean hasTransformedSuperclass) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { Object[] params4Logging = new Object[2]; params4Logging[0] = (target != null) ? target.getName() : target; params4Logging[1] = hasTransformedSuperclass; logger.entering("TransClass", "doTransform", params4Logging); if (target.isArray() || target.isInterface()) { return; } ClassPool.getDefault().importPackage("java.util"); // add: implements TRAVERSALTARGET List<CtClass> targetIfs = Arrays.asList(target.getInterfaces()); Collection<CtClass> newTargetIfs = new HashSet<CtClass>(targetIfs); // NOTE: Given the equality semantics of CtClass the condition is only // valid if the CtClass instance representing the traversal interface is // never detached from the ClassPool as this would result in a new // CtClass instance (representing the traversal interface) to be generated // by a call to ClassPool.get(...) not being equal to the old instance. // only generate implementation of traversal interface if not yet present // use traversal interface as marker for availability of other instrumentation CtClass traversalTargetInterface = ClassPool.getDefault().get(TRAVERSAL_TARGET); if (!newTargetIfs.contains(traversalTargetInterface)) { newTargetIfs.add(traversalTargetInterface); target.setInterfaces(newTargetIfs.toArray(new CtClass[0])); // add: method traverse__ (create body before adding new technically required fields) String methodbody = createBody(target, hasTransformedSuperclass); CtMethod m = CtNewMethod.make(methodbody, target); target.addMethod(m); // change methods carrying contracts // 1. Find all methods carrying contracts // 2. For each annotated method // 1. Get method annotation // 2. Generate code to generate automaton for contract // (generate code to get contract string and call into automation generation library) // 3. Use insertBefore() and insertAfter() to insert permission installation/deinstallation code // according to tutorial there's no support for generics in Javassist, thus we use raw types CtField f = CtField.make("private static java.util.HashMap "+FST_CACHE_FIELD_NAME+" = new java.util.HashMap();", target); target.addField(f); // collect all methods and constructors // List<CtMethod> methods = Arrays.asList(target.getDeclaredMethods()); List<CtConstructor> ctors = Arrays.asList(target.getDeclaredConstructors()); // List<CtBehavior> methodsAndCtors = new ArrayList<CtBehavior>(); // methodsAndCtors.addAll(methods); // methodsAndCtors.addAll(ctors); List<CtBehavior> methodsAndCtors = Arrays.asList(target.getDeclaredBehaviors()); for (CtConstructor ctor : ctors) { instrumentNew(ctor); } for (CtBehavior methodOrCtor : methodsAndCtors) { logger.fine("Consider adding traversal to behavior: "+methodOrCtor.getLongName()); if ((methodOrCtor.getModifiers() & Modifier.ABSTRACT) != 0) { continue; } instrumentFieldAccess(methodOrCtor); if (hasMethodGrantAnnotations(methodOrCtor)) { logger.fine("Add traversal to behavior: "+methodOrCtor.getLongName()); /* generate header and footer */ // filter synthetic methods if (methodOrCtor.getMethodInfo().getAttribute(SyntheticAttribute.tag) != null) { continue; } // generate method header /* * We keep method contract and all parameter contracts separate. */ StringBuilder sb = new StringBuilder(); // uniquely identifies a method globally String longName = methodOrCtor.getLongName(); // check if automata for this method already exist sb.append("String longName = \"" + longName + "\";"); // FSTs indexed by parameter position (0: FST for this & type-anchored // contracts, 1 to n: FTSs for unanchored parameter contracts) sb.append("de.unifr.acp.fst.FST[] fSTs;"); sb.append("if ("+FST_CACHE_FIELD_NAME+".containsKey(longName)) {"); sb.append(" fSTs = ((de.unifr.acp.fst.FST[])"+FST_CACHE_FIELD_NAME+".get(longName));"); sb.append("}"); sb.append("else {"); // build array of FSTs indexed by parameter sb.append(" fSTs = new de.unifr.acp.fst.FST["+(parameterCountOf(methodOrCtor)+1)+"];"); for (int i=0; i<parameterCountOf(methodOrCtor)+1; i++) { Grant grant = grantAnno(methodOrCtor, i); if (grant != null) { sb.append(" fSTs[" + i + "] = new de.unifr.acp.fst.FST(\"" + grant.value() + "\");"); } } // cache generated automata indexed by long method name sb.append(" "+FST_CACHE_FIELD_NAME+".put(longName, fSTs);"); sb.append("}"); // now we expect to have all FSTs available and cached sb.append(" Map allLocPerms = new de.unifr.acp.util.WeakIdentityHashMap();"); int i= ((isStatic(methodOrCtor)) ? 1 : 0); int limit = ((isStatic(methodOrCtor)) ? (parameterCountOf(methodOrCtor)) : parameterCountOf(methodOrCtor)+1); for (; i<limit; i++) { // only grant-annotated methods/parameters require any action if (grantAnno(methodOrCtor, i) == null) { continue; } if (!mightBeReferenceParameter(methodOrCtor, i)) { continue; } // TODO: factor out this code in external class, parameterize over i and allPermissions // a location permission is a Map<Object, Map<String, Permission>> sb.append("{"); sb.append(" de.unifr.acp.fst.FST fst = fSTs["+i+"];"); sb.append(" de.unifr.acp.fst.FSTRunner runner = new de.unifr.acp.fst.FSTRunner(fst);"); // step to reach FST runner state that corresponds to anchor object // for explicitly anchored contracts if (i == 0) { sb.append(" runner.resetAndStep(\"this\");"); } // here the runner should be in synch with the parameter object // (as far as non-static fields are concerned), the visitor implicitly joins locPerms - if (i == 0 || !methodOrCtor.getParameterTypes()[isStatic(methodOrCtor) ? i - 1 - : i].isArray()) { + if (i > 0 && !methodOrCtor.getParameterTypes()[i-1].isArray()) { sb.append(" if ($" + i + " instanceof de.unifr.acp.templates.TraversalTarget__) {"); sb.append(" de.unifr.acp.templates.TraversalImpl visitor = new de.unifr.acp.templates.TraversalImpl(runner,allLocPerms);"); sb.append(" ((de.unifr.acp.templates.TraversalTarget__)$" + i + ").traverse__(visitor);"); sb.append(" }"); } // TODO: explicit representation of locations and location permissions (supporting join) // (currently it's all generic maps and implicit joins in visitor similar to Maxine implementation) sb.append("}"); } // install allLocPerms and push new objects set on (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.push(allLocPerms);"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.push(Collections.newSetFromMap(new de.unifr.acp.util.WeakIdentityHashMap()));"); // TODO: figure out how to instrument thread start/end and field access String header = sb.toString(); methodOrCtor.insertBefore(header); // generate method footer sb = new StringBuilder(); // pop location permissions and new locations entry from // (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.pop();"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.pop();"); String footer = sb.toString(); // make sure all method exits are covered (exceptions, multiple returns) methodOrCtor.insertAfter(footer, true); } // end if (hasMethodGrantAnnotations(methodOrCtor)) } } logger.exiting("TransClass", "doTransform"); } private static boolean isStatic(CtBehavior methodOrCtor) { return ((methodOrCtor.getModifiers() & Modifier.STATIC) != 0); } private static void instrumentFieldAccess(CtBehavior methodOrCtor) throws CannotCompileException { // if (!isInstrumented.get()) { methodOrCtor.instrument(new ExprEditor() { public void edit(FieldAccess expr) throws CannotCompileException { String qualifiedFieldName = expr.getClassName() + "." + expr.getFieldName(); // exclude standard API (to be factored out) if (!(qualifiedFieldName.startsWith("java") || qualifiedFieldName .startsWith("javax"))) { StringBuilder code = new StringBuilder(); code.append("{"); // get active permission for location to access code.append("if (!de.unifr.acp.templates.Global.newObjectsStack.isEmpty()) {"); code.append("de.unifr.acp.fst.Permission effectivePerm = de.unifr.acp.templates.Global.installedPermissionStackNotEmpty($0, \"" + qualifiedFieldName + "\");"); // get permission needed for this access code.append("de.unifr.acp.fst.Permission accessPerm = de.unifr.acp.fst.Permission." + (expr.isReader() ? "READ_ONLY" : "WRITE_ONLY") + ";"); // code.append("de.unifr.acp.fst.Permission accessPerm = de.unifr.acp.fst.Permission.values()[" // + (expr.isReader() ? "1" : "2") // + "];"); //code.append("if (!effectivePerm.containsAll(accessPerm)) {"); code.append("if (!de.unifr.acp.fst.Permission.containsAll(effectivePerm, accessPerm)) {"); code.append(" de.unifr.acp.templates.Global.printViolation($0, \""+qualifiedFieldName+"\", effectivePerm, accessPerm);"); code.append("}"); code.append("}"); if (expr.isReader()) { code.append(" $_ = $proceed();"); } else { code.append(" $proceed($$);"); } code.append("}"); expr.replace(code.toString()); } } }); // } } /* * Instruments constructors to such that the constructed object is added to * the new objects stack's top entry. */ private static void instrumentNew(CtConstructor ctor) throws CannotCompileException { // Apparently Javassist does not support instrumentation between new // bytecode and constructor using the expression editor on new // expressions (in AspectJ this might work using Initialization Pointcut // Designators). Hence, we go for instrumenting the constructor, but // we need to make sure that the object is a valid by the time we // add it to the new objects (after this() or super() call). ctor.instrument(new ExprEditor() { public void edit(ConstructorCall expr) throws CannotCompileException { StringBuilder code = new StringBuilder(); code.append("{"); code.append(" $_ = $proceed($$);"); code.append(" de.unifr.acp.templates.Global.addNewObject($0);"); code.append("}"); expr.replace(code.toString()); } }); } /* * Instrument array creation such that the new array is added to the new * objects stack's top entry. */ private static void instrumentNewArray(CtBehavior methodOrCtor) throws CannotCompileException { methodOrCtor.instrument(new ExprEditor() { public void edit(NewArray expr) throws CannotCompileException { StringBuilder code = new StringBuilder(); code.append("{"); code.append(" $_ = $proceed($$);"); code.append(" de.unifr.acp.templates.Global.addNewObject($0);"); code.append("}"); expr.replace(code.toString()); } }); } private static int parameterCountOf(CtBehavior methodOrCtor) { return methodOrCtor.getAvailableParameterAnnotations().length; } /** * Currently is an under-approximation (might return false for primitive parameters) * @param methodOrCtor * @param index the parameter index * @return false if non-primitive or primitive, true if primitive */ private static boolean mightBeReferenceParameter(CtBehavior methodOrCtor, int index) { if (index == 0) { return true; } else { try { return !(methodOrCtor.getParameterTypes()[index-1].isPrimitive()); } catch (NotFoundException e) { // TODO: fix this return true; } } } /** * Return the grant annotation for the specified parameter (1 to n) or * behavior (0) if available. * * @param methodOrCtor * the behavior * @param index * 1 to n refers to a parameter index, 0 refers to the behavior * itself * @return the grant annotation if available, <code>null</code> otherwise * @throws ClassNotFoundException */ private static Grant grantAnno(CtBehavior methodOrCtor, int index) throws ClassNotFoundException { if (index == 0) { Grant methodGrantAnnot = ((Grant) methodOrCtor .getAnnotation(Grant.class)); return methodGrantAnnot; } else { // optional parameter types annotations indexed by parameter position Object[][] availParamAnnot = methodOrCtor .getAvailableParameterAnnotations(); final Object[] oa = availParamAnnot[index-1]; for (Object o : oa) { if (o instanceof Grant) { // there's one grant annotation per parameter only return (Grant) o; } } return null; } } /** * @deprecated */ private String concateSingleContracts(Grant methodGrantAnnot, Grant[] paramGrantAnnots) { String compositeContract; // list of single contracts to form the composite contract final ArrayList<String> singleContracts = new ArrayList<String>(); // add method contract if available if (methodGrantAnnot != null) { singleContracts.add(methodGrantAnnot.value()); } // add anchor-prefixed parameter contracts for (int i = 0; i < paramGrantAnnots.length; i++) { Grant grant = paramGrantAnnots[i]; String[] singleParamContracts = grant.value().split(","); for (String contract : singleParamContracts) { singleContracts.add((i + 1) + "." + contract); // add anchor prefix } } // append comma-separated single contracts final StringBuilder compositeBuilder = new StringBuilder(); if (singleContracts.size() > 0) { for (int i = 0; i < singleContracts.size() - 1; i++) { String contract = singleContracts.get(i); compositeBuilder.append(contract + ","); } compositeBuilder.append(singleContracts.get(singleContracts.size() -1)); } compositeContract = compositeBuilder.toString(); return compositeContract; } /** * Returns true if the specified method/constructor or one of its parameters * has a Grant annotation. * @param methodOrCtor the method/constructor to check * @return true if Grant annotation exists, false otherwise. * @throws NotFoundException * @throws CannotCompileException */ private static boolean hasMethodGrantAnnotations(CtBehavior methodOrCtor) throws NotFoundException, CannotCompileException { if (methodOrCtor.hasAnnotation(Grant.class)) return true; CtClass[] parameterTypes = methodOrCtor.getParameterTypes(); int i = 0; for (Object[] oa : methodOrCtor.getAvailableParameterAnnotations()) { CtClass paramType = parameterTypes[i++]; // we can savely ignore grant annotations on primitive formal // parameters if (!paramType.isPrimitive()) { for (Object o : oa) { if (o instanceof Grant) { return true; } } } } return false; } protected static String createBody(CtClass target, boolean hasSuperclass) throws NotFoundException { StringBuilder sb = new StringBuilder(); sb.append("public void traverse__(de.unifr.acp.templates.Traversal__ t) {\n"); for (CtField f : target.getDeclaredFields()) { CtClass tf = f.getType(); String fname = f.getName(); if (!fname.equals(FST_CACHE_FIELD_NAME)) { appendVisitorCalls(sb, target, tf, fname); } } if (hasSuperclass) { sb.append("super.traverse__(t);\n"); } sb.append('}'); return sb.toString(); } protected static void appendVisitorCalls(StringBuilder sb, CtClass target, CtClass tf, String fname) throws NotFoundException { int nesting = 0; String index = ""; while (tf.isArray()) { String var = "i" + nesting; /* generate for header */ sb.append("for (int " + var + " = 0; "); // static type of 'this' corresponds to field's declaring class, no cast needed sb.append(var + "<this."+fname+index+".length; "); sb.append(var + "++"); sb.append(")\n"); index = index + "[" + var + "]"; nesting++; tf = tf.getComponentType(); } if (tf.isPrimitive()) { sb.append("t.visitPrimitive__("); } else { sb.append("t.visit__("); } sb.append("this, "); sb.append('"'); sb.append(target.getName()); sb.append('.'); sb.append(fname); sb.append('"'); if (!tf.isPrimitive()) { // static type of 'this' corresponds to field's declaring class, no cast needed sb.append(", this."); sb.append(fname + index); } sb.append(");\n"); } }
true
true
public static void doTransform(CtClass target, boolean hasTransformedSuperclass) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { Object[] params4Logging = new Object[2]; params4Logging[0] = (target != null) ? target.getName() : target; params4Logging[1] = hasTransformedSuperclass; logger.entering("TransClass", "doTransform", params4Logging); if (target.isArray() || target.isInterface()) { return; } ClassPool.getDefault().importPackage("java.util"); // add: implements TRAVERSALTARGET List<CtClass> targetIfs = Arrays.asList(target.getInterfaces()); Collection<CtClass> newTargetIfs = new HashSet<CtClass>(targetIfs); // NOTE: Given the equality semantics of CtClass the condition is only // valid if the CtClass instance representing the traversal interface is // never detached from the ClassPool as this would result in a new // CtClass instance (representing the traversal interface) to be generated // by a call to ClassPool.get(...) not being equal to the old instance. // only generate implementation of traversal interface if not yet present // use traversal interface as marker for availability of other instrumentation CtClass traversalTargetInterface = ClassPool.getDefault().get(TRAVERSAL_TARGET); if (!newTargetIfs.contains(traversalTargetInterface)) { newTargetIfs.add(traversalTargetInterface); target.setInterfaces(newTargetIfs.toArray(new CtClass[0])); // add: method traverse__ (create body before adding new technically required fields) String methodbody = createBody(target, hasTransformedSuperclass); CtMethod m = CtNewMethod.make(methodbody, target); target.addMethod(m); // change methods carrying contracts // 1. Find all methods carrying contracts // 2. For each annotated method // 1. Get method annotation // 2. Generate code to generate automaton for contract // (generate code to get contract string and call into automation generation library) // 3. Use insertBefore() and insertAfter() to insert permission installation/deinstallation code // according to tutorial there's no support for generics in Javassist, thus we use raw types CtField f = CtField.make("private static java.util.HashMap "+FST_CACHE_FIELD_NAME+" = new java.util.HashMap();", target); target.addField(f); // collect all methods and constructors // List<CtMethod> methods = Arrays.asList(target.getDeclaredMethods()); List<CtConstructor> ctors = Arrays.asList(target.getDeclaredConstructors()); // List<CtBehavior> methodsAndCtors = new ArrayList<CtBehavior>(); // methodsAndCtors.addAll(methods); // methodsAndCtors.addAll(ctors); List<CtBehavior> methodsAndCtors = Arrays.asList(target.getDeclaredBehaviors()); for (CtConstructor ctor : ctors) { instrumentNew(ctor); } for (CtBehavior methodOrCtor : methodsAndCtors) { logger.fine("Consider adding traversal to behavior: "+methodOrCtor.getLongName()); if ((methodOrCtor.getModifiers() & Modifier.ABSTRACT) != 0) { continue; } instrumentFieldAccess(methodOrCtor); if (hasMethodGrantAnnotations(methodOrCtor)) { logger.fine("Add traversal to behavior: "+methodOrCtor.getLongName()); /* generate header and footer */ // filter synthetic methods if (methodOrCtor.getMethodInfo().getAttribute(SyntheticAttribute.tag) != null) { continue; } // generate method header /* * We keep method contract and all parameter contracts separate. */ StringBuilder sb = new StringBuilder(); // uniquely identifies a method globally String longName = methodOrCtor.getLongName(); // check if automata for this method already exist sb.append("String longName = \"" + longName + "\";"); // FSTs indexed by parameter position (0: FST for this & type-anchored // contracts, 1 to n: FTSs for unanchored parameter contracts) sb.append("de.unifr.acp.fst.FST[] fSTs;"); sb.append("if ("+FST_CACHE_FIELD_NAME+".containsKey(longName)) {"); sb.append(" fSTs = ((de.unifr.acp.fst.FST[])"+FST_CACHE_FIELD_NAME+".get(longName));"); sb.append("}"); sb.append("else {"); // build array of FSTs indexed by parameter sb.append(" fSTs = new de.unifr.acp.fst.FST["+(parameterCountOf(methodOrCtor)+1)+"];"); for (int i=0; i<parameterCountOf(methodOrCtor)+1; i++) { Grant grant = grantAnno(methodOrCtor, i); if (grant != null) { sb.append(" fSTs[" + i + "] = new de.unifr.acp.fst.FST(\"" + grant.value() + "\");"); } } // cache generated automata indexed by long method name sb.append(" "+FST_CACHE_FIELD_NAME+".put(longName, fSTs);"); sb.append("}"); // now we expect to have all FSTs available and cached sb.append(" Map allLocPerms = new de.unifr.acp.util.WeakIdentityHashMap();"); int i= ((isStatic(methodOrCtor)) ? 1 : 0); int limit = ((isStatic(methodOrCtor)) ? (parameterCountOf(methodOrCtor)) : parameterCountOf(methodOrCtor)+1); for (; i<limit; i++) { // only grant-annotated methods/parameters require any action if (grantAnno(methodOrCtor, i) == null) { continue; } if (!mightBeReferenceParameter(methodOrCtor, i)) { continue; } // TODO: factor out this code in external class, parameterize over i and allPermissions // a location permission is a Map<Object, Map<String, Permission>> sb.append("{"); sb.append(" de.unifr.acp.fst.FST fst = fSTs["+i+"];"); sb.append(" de.unifr.acp.fst.FSTRunner runner = new de.unifr.acp.fst.FSTRunner(fst);"); // step to reach FST runner state that corresponds to anchor object // for explicitly anchored contracts if (i == 0) { sb.append(" runner.resetAndStep(\"this\");"); } // here the runner should be in synch with the parameter object // (as far as non-static fields are concerned), the visitor implicitly joins locPerms if (i == 0 || !methodOrCtor.getParameterTypes()[isStatic(methodOrCtor) ? i - 1 : i].isArray()) { sb.append(" if ($" + i + " instanceof de.unifr.acp.templates.TraversalTarget__) {"); sb.append(" de.unifr.acp.templates.TraversalImpl visitor = new de.unifr.acp.templates.TraversalImpl(runner,allLocPerms);"); sb.append(" ((de.unifr.acp.templates.TraversalTarget__)$" + i + ").traverse__(visitor);"); sb.append(" }"); } // TODO: explicit representation of locations and location permissions (supporting join) // (currently it's all generic maps and implicit joins in visitor similar to Maxine implementation) sb.append("}"); } // install allLocPerms and push new objects set on (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.push(allLocPerms);"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.push(Collections.newSetFromMap(new de.unifr.acp.util.WeakIdentityHashMap()));"); // TODO: figure out how to instrument thread start/end and field access String header = sb.toString(); methodOrCtor.insertBefore(header); // generate method footer sb = new StringBuilder(); // pop location permissions and new locations entry from // (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.pop();"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.pop();"); String footer = sb.toString(); // make sure all method exits are covered (exceptions, multiple returns) methodOrCtor.insertAfter(footer, true); } // end if (hasMethodGrantAnnotations(methodOrCtor)) } } logger.exiting("TransClass", "doTransform"); }
public static void doTransform(CtClass target, boolean hasTransformedSuperclass) throws NotFoundException, IOException, CannotCompileException, ClassNotFoundException { Object[] params4Logging = new Object[2]; params4Logging[0] = (target != null) ? target.getName() : target; params4Logging[1] = hasTransformedSuperclass; logger.entering("TransClass", "doTransform", params4Logging); if (target.isArray() || target.isInterface()) { return; } ClassPool.getDefault().importPackage("java.util"); // add: implements TRAVERSALTARGET List<CtClass> targetIfs = Arrays.asList(target.getInterfaces()); Collection<CtClass> newTargetIfs = new HashSet<CtClass>(targetIfs); // NOTE: Given the equality semantics of CtClass the condition is only // valid if the CtClass instance representing the traversal interface is // never detached from the ClassPool as this would result in a new // CtClass instance (representing the traversal interface) to be generated // by a call to ClassPool.get(...) not being equal to the old instance. // only generate implementation of traversal interface if not yet present // use traversal interface as marker for availability of other instrumentation CtClass traversalTargetInterface = ClassPool.getDefault().get(TRAVERSAL_TARGET); if (!newTargetIfs.contains(traversalTargetInterface)) { newTargetIfs.add(traversalTargetInterface); target.setInterfaces(newTargetIfs.toArray(new CtClass[0])); // add: method traverse__ (create body before adding new technically required fields) String methodbody = createBody(target, hasTransformedSuperclass); CtMethod m = CtNewMethod.make(methodbody, target); target.addMethod(m); // change methods carrying contracts // 1. Find all methods carrying contracts // 2. For each annotated method // 1. Get method annotation // 2. Generate code to generate automaton for contract // (generate code to get contract string and call into automation generation library) // 3. Use insertBefore() and insertAfter() to insert permission installation/deinstallation code // according to tutorial there's no support for generics in Javassist, thus we use raw types CtField f = CtField.make("private static java.util.HashMap "+FST_CACHE_FIELD_NAME+" = new java.util.HashMap();", target); target.addField(f); // collect all methods and constructors // List<CtMethod> methods = Arrays.asList(target.getDeclaredMethods()); List<CtConstructor> ctors = Arrays.asList(target.getDeclaredConstructors()); // List<CtBehavior> methodsAndCtors = new ArrayList<CtBehavior>(); // methodsAndCtors.addAll(methods); // methodsAndCtors.addAll(ctors); List<CtBehavior> methodsAndCtors = Arrays.asList(target.getDeclaredBehaviors()); for (CtConstructor ctor : ctors) { instrumentNew(ctor); } for (CtBehavior methodOrCtor : methodsAndCtors) { logger.fine("Consider adding traversal to behavior: "+methodOrCtor.getLongName()); if ((methodOrCtor.getModifiers() & Modifier.ABSTRACT) != 0) { continue; } instrumentFieldAccess(methodOrCtor); if (hasMethodGrantAnnotations(methodOrCtor)) { logger.fine("Add traversal to behavior: "+methodOrCtor.getLongName()); /* generate header and footer */ // filter synthetic methods if (methodOrCtor.getMethodInfo().getAttribute(SyntheticAttribute.tag) != null) { continue; } // generate method header /* * We keep method contract and all parameter contracts separate. */ StringBuilder sb = new StringBuilder(); // uniquely identifies a method globally String longName = methodOrCtor.getLongName(); // check if automata for this method already exist sb.append("String longName = \"" + longName + "\";"); // FSTs indexed by parameter position (0: FST for this & type-anchored // contracts, 1 to n: FTSs for unanchored parameter contracts) sb.append("de.unifr.acp.fst.FST[] fSTs;"); sb.append("if ("+FST_CACHE_FIELD_NAME+".containsKey(longName)) {"); sb.append(" fSTs = ((de.unifr.acp.fst.FST[])"+FST_CACHE_FIELD_NAME+".get(longName));"); sb.append("}"); sb.append("else {"); // build array of FSTs indexed by parameter sb.append(" fSTs = new de.unifr.acp.fst.FST["+(parameterCountOf(methodOrCtor)+1)+"];"); for (int i=0; i<parameterCountOf(methodOrCtor)+1; i++) { Grant grant = grantAnno(methodOrCtor, i); if (grant != null) { sb.append(" fSTs[" + i + "] = new de.unifr.acp.fst.FST(\"" + grant.value() + "\");"); } } // cache generated automata indexed by long method name sb.append(" "+FST_CACHE_FIELD_NAME+".put(longName, fSTs);"); sb.append("}"); // now we expect to have all FSTs available and cached sb.append(" Map allLocPerms = new de.unifr.acp.util.WeakIdentityHashMap();"); int i= ((isStatic(methodOrCtor)) ? 1 : 0); int limit = ((isStatic(methodOrCtor)) ? (parameterCountOf(methodOrCtor)) : parameterCountOf(methodOrCtor)+1); for (; i<limit; i++) { // only grant-annotated methods/parameters require any action if (grantAnno(methodOrCtor, i) == null) { continue; } if (!mightBeReferenceParameter(methodOrCtor, i)) { continue; } // TODO: factor out this code in external class, parameterize over i and allPermissions // a location permission is a Map<Object, Map<String, Permission>> sb.append("{"); sb.append(" de.unifr.acp.fst.FST fst = fSTs["+i+"];"); sb.append(" de.unifr.acp.fst.FSTRunner runner = new de.unifr.acp.fst.FSTRunner(fst);"); // step to reach FST runner state that corresponds to anchor object // for explicitly anchored contracts if (i == 0) { sb.append(" runner.resetAndStep(\"this\");"); } // here the runner should be in synch with the parameter object // (as far as non-static fields are concerned), the visitor implicitly joins locPerms if (i > 0 && !methodOrCtor.getParameterTypes()[i-1].isArray()) { sb.append(" if ($" + i + " instanceof de.unifr.acp.templates.TraversalTarget__) {"); sb.append(" de.unifr.acp.templates.TraversalImpl visitor = new de.unifr.acp.templates.TraversalImpl(runner,allLocPerms);"); sb.append(" ((de.unifr.acp.templates.TraversalTarget__)$" + i + ").traverse__(visitor);"); sb.append(" }"); } // TODO: explicit representation of locations and location permissions (supporting join) // (currently it's all generic maps and implicit joins in visitor similar to Maxine implementation) sb.append("}"); } // install allLocPerms and push new objects set on (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.push(allLocPerms);"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.push(Collections.newSetFromMap(new de.unifr.acp.util.WeakIdentityHashMap()));"); // TODO: figure out how to instrument thread start/end and field access String header = sb.toString(); methodOrCtor.insertBefore(header); // generate method footer sb = new StringBuilder(); // pop location permissions and new locations entry from // (current thread's) stack //sb.append("System.out.println(\"locPermStack: \"+de.unifr.acp.templates.Global.locPermStack);"); //sb.append("System.out.println(\"locPermStack.peek(): \"+de.unifr.acp.templates.Global.locPermStack.peek());"); sb.append("de.unifr.acp.templates.Global.locPermStack.pop();"); sb.append("de.unifr.acp.templates.Global.newObjectsStack.pop();"); String footer = sb.toString(); // make sure all method exits are covered (exceptions, multiple returns) methodOrCtor.insertAfter(footer, true); } // end if (hasMethodGrantAnnotations(methodOrCtor)) } } logger.exiting("TransClass", "doTransform"); }
diff --git a/src/plugins/Freetalk/WoT/WoTIdentityManager.java b/src/plugins/Freetalk/WoT/WoTIdentityManager.java index 1eda09a3..8f5542da 100644 --- a/src/plugins/Freetalk/WoT/WoTIdentityManager.java +++ b/src/plugins/Freetalk/WoT/WoTIdentityManager.java @@ -1,1134 +1,1134 @@ /* This code is part of Freenet. It is distributed under the GNU General * Public License, version 2 (or at your option any later version). See * http://www.gnu.org/ for further details of the GPL. */ package plugins.Freetalk.WoT; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Random; import plugins.Freetalk.Freetalk; import plugins.Freetalk.Identity; import plugins.Freetalk.IdentityManager; import plugins.Freetalk.MessageManager; import plugins.Freetalk.OwnIdentity; import plugins.Freetalk.Persistent; import plugins.Freetalk.PluginTalkerBlocking; import plugins.Freetalk.exceptions.DuplicateIdentityException; import plugins.Freetalk.exceptions.InvalidParameterException; import plugins.Freetalk.exceptions.NoSuchIdentityException; import plugins.Freetalk.exceptions.NotInTrustTreeException; import plugins.Freetalk.exceptions.NotTrustedException; import plugins.Freetalk.exceptions.WoTDisconnectedException; import plugins.Freetalk.tasks.PersistentTask; import plugins.Freetalk.tasks.PersistentTaskManager; import plugins.Freetalk.tasks.WoT.IntroduceIdentityTask; import com.db4o.ObjectSet; import com.db4o.query.Query; import freenet.keys.FreenetURI; import freenet.node.PrioRunnable; import freenet.pluginmanager.PluginNotFoundException; import freenet.support.Base64; import freenet.support.CurrentTimeUTC; import freenet.support.Executor; import freenet.support.IllegalBase64Exception; import freenet.support.LRUCache; import freenet.support.Logger; import freenet.support.SimpleFieldSet; import freenet.support.TrivialTicker; import freenet.support.api.Bucket; import freenet.support.io.NativeThread; /** * An identity manager which uses the identities from the WoT plugin. * * @author xor ([email protected]) */ public final class WoTIdentityManager extends IdentityManager implements PrioRunnable { private static final int THREAD_PERIOD = Freetalk.FAST_DEBUG_MODE ? (3 * 60 * 1000) : (5 * 60 * 1000); private static final int GARBAGE_COLLECT_DELAY = Freetalk.FAST_DEBUG_MODE ? (1 * 60 * 1000) : (3 * THREAD_PERIOD); /** The amount of time between each attempt to connect to the WoT plugin */ private static final int WOT_RECONNECT_DELAY = 5 * 1000; /** The minimal amount of time between fetching identities */ private static final int MINIMAL_IDENTITY_FETCH_DELAY = 60 * 1000; /** The minimal amount of time between fetching own identities */ private static final int MINIMAL_OWN_IDENTITY_FETCH_DELAY = 1000; private boolean mConnectedToWoT = false; private boolean mIdentityFetchInProgress = false; private boolean mOwnIdentityFetchInProgress = false; private long mLastIdentityFetchTime = 0; private long mLastOwnIdentityFetchTime = 0; /** If true, this identity manager is being use in a unit test - it will return 0 for any score / trust value then */ private final boolean mIsUnitTest; private final TrivialTicker mTicker; private final Random mRandom; private PluginTalkerBlocking mTalker = null; /** * Caches the shortest unique nickname for each identity. Key = Identity it, Value = Shortest nickname. */ private volatile HashMap<String, String> mShortestUniqueNicknameCache = new HashMap<String, String>(); private boolean mShortestUniqueNicknameCacheNeedsUpdate = true; private WebOfTrustCache mWoTCache = new WebOfTrustCache(); public WoTIdentityManager(Freetalk myFreetalk, Executor myExecutor) { super(myFreetalk); mIsUnitTest = false; mTicker = new TrivialTicker(myExecutor); mRandom = mFreetalk.getPluginRespirator().getNode().fastWeakRandom; } /** * For being used in JUnit tests to run without a node. */ public WoTIdentityManager(Freetalk myFreetalk) { super(myFreetalk); mIsUnitTest = true; mTicker = null; mRandom = null; } /** * Sends a blocking FCP message to the WoT plugin, checks whether the reply is really the expected reply message and throws an exception * if not. Also checks whether the reply is an error message and throws an exception if it is. Therefore, the purpose of this function * is that the callee can assume that no errors occurred if no exception is thrown. * * @param params The params of the FCP message. * @param expectedReplyMessage The excepted content of the "Message" field of the SimpleFieldSet of the reply message. * @return The unmodified HashResult object which was returned by the PluginTalker. * @throws WoTDisconnectedException If the connection to WoT was lost. * @throws Exception If the WoT plugin replied with an error message or not with the expected message. */ private PluginTalkerBlocking.Result sendFCPMessageBlocking(SimpleFieldSet params, Bucket data, String expectedReplyMessage) throws Exception { if(mTalker == null) throw new WoTDisconnectedException(); PluginTalkerBlocking.Result result; try { result = mTalker.sendBlocking(params, data); } catch (PluginNotFoundException e) { throw new WoTDisconnectedException(); } if(result.params.get("Message").equals("Error")) { final String description = result.params.get("Description"); if(description.indexOf("UnknownIdentityException") >= 0) throw new NoSuchIdentityException(description); throw new Exception("FCP message " + result.params.get("OriginalMessage") + " failed: " + description); } if(result.params.get("Message").equals(expectedReplyMessage) == false) throw new Exception("FCP message " + params.get("Message") + " received unexpected reply: " + result.params.get("Message")); return result; } public synchronized WoTOwnIdentity createOwnIdentity(String newNickname, boolean publishesTrustList, boolean publishesIntroductionPuzzles, boolean autoSubscribeToNewBoards) throws Exception { Logger.normal(this, "Creating new own identity via FCP, nickname: " + newNickname); SimpleFieldSet params = new SimpleFieldSet(true); params.putOverwrite("Message", "CreateIdentity"); params.putOverwrite("Nickname", newNickname); params.putOverwrite("PublishTrustList", publishesTrustList ? "true" : "false"); params.putOverwrite("PublishIntroductionPuzzles", publishesIntroductionPuzzles ? "true" : "false"); params.putOverwrite("Context", Freetalk.WOT_CONTEXT); PluginTalkerBlocking.Result result = sendFCPMessageBlocking(params, null, "IdentityCreated"); WoTOwnIdentity identity = new WoTOwnIdentity(result.params.get("ID"), new FreenetURI(result.params.get("RequestURI")), new FreenetURI(result.params.get("InsertURI")), newNickname, autoSubscribeToNewBoards); identity.initializeTransient(mFreetalk); Logger.normal(this, "Created WoTOwnidentity via FCP, now storing... " + identity); synchronized(mFreetalk.getTaskManager()) { // Required by onNewOwnidentityAdded synchronized(db.lock()) { try { identity.initializeTransient(mFreetalk); identity.storeWithoutCommit(); onNewOwnIdentityAdded(identity); identity.checkedCommit(this); Logger.normal(this, "Stored new WoTOwnIdentity " + identity); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(db, this, e); } } } return identity; } public synchronized WoTOwnIdentity createOwnIdentity(String newNickname, boolean publishesTrustList, boolean publishesIntroductionPuzzles, boolean autoSubscribeToNewBoards, FreenetURI newRequestURI, FreenetURI newInsertURI) throws Exception { Logger.normal(this, "Creating new own identity via FCP, nickname: " + newNickname); SimpleFieldSet params = new SimpleFieldSet(true); params.putOverwrite("Message", "CreateIdentity"); params.putOverwrite("Nickname", newNickname); params.putOverwrite("PublishTrustList", publishesTrustList ? "true" : "false"); params.putOverwrite("PublishIntroductionPuzzles", publishesTrustList && publishesIntroductionPuzzles ? "true" : "false"); params.putOverwrite("Context", Freetalk.WOT_CONTEXT); params.putOverwrite("RequestURI", newRequestURI.toString()); params.putOverwrite("InsertURI", newInsertURI.toString()); PluginTalkerBlocking.Result result = sendFCPMessageBlocking(params, null, "IdentityCreated"); /* We take the URIs which were returned by the WoT plugin instead of the requested ones because this allows the identity to work * even if the WoT plugin ignores our requested URIs: If we just stored the URIs we requested, we would store an identity with * wrong URIs which would result in the identity not being useable. */ WoTOwnIdentity identity = new WoTOwnIdentity(result.params.get("ID"), new FreenetURI(result.params.get("RequestURI")), new FreenetURI(result.params.get("InsertURI")), newNickname, autoSubscribeToNewBoards); identity.initializeTransient(mFreetalk); Logger.normal(this, "Created WoTOwnidentity via FCP, now storing... " + identity); synchronized(mFreetalk.getTaskManager()) { synchronized(db.lock()) { try { identity.storeWithoutCommit(); onNewOwnIdentityAdded(identity); identity.checkedCommit(this); Logger.normal(this, "Stored new WoTOwnIdentity " + identity); } catch(RuntimeException e) { Persistent.checkedRollback(db, this, e); } } } return identity; } public ObjectSet<WoTIdentity> getAllIdentities() { Query q = db.query(); q.constrain(WoTIdentity.class); return new Persistent.InitializingObjectSet<WoTIdentity>(mFreetalk, q); } public synchronized ObjectSet<WoTOwnIdentity> ownIdentityIterator() { try { fetchOwnIdentities(); garbageCollectIdentities(); } catch(Exception e) {} /* Ignore, return the ones which are in database now */ final Query q = db.query(); q.constrain(WoTOwnIdentity.class); return new Persistent.InitializingObjectSet<WoTOwnIdentity>(mFreetalk, q); } @SuppressWarnings("unchecked") public synchronized WoTIdentity getIdentity(String id) throws NoSuchIdentityException { Query q = db.query(); q.constrain(WoTIdentity.class); q.descend("mID").constrain(id); ObjectSet<WoTIdentity> result = q.execute(); switch(result.size()) { case 1: WoTIdentity identity = result.next(); identity.initializeTransient(mFreetalk); return identity; case 0: throw new NoSuchIdentityException(id); default: throw new DuplicateIdentityException(id); } } public Identity getIdentityByURI(FreenetURI uri) throws NoSuchIdentityException { return getIdentity(WoTIdentity.getIDFromURI(uri)); } @SuppressWarnings("unchecked") public synchronized WoTOwnIdentity getOwnIdentity(String id) throws NoSuchIdentityException { Query q = db.query(); q.constrain(WoTOwnIdentity.class); q.descend("mID").constrain(id); ObjectSet<WoTOwnIdentity> result = q.execute(); switch(result.size()) { case 1: WoTOwnIdentity identity = result.next(); identity.initializeTransient(mFreetalk); return identity; case 0: throw new NoSuchIdentityException(id); default: throw new DuplicateIdentityException(id); } } /** * Not synchronized, the involved identities might be deleted during the query - which is not really a problem. */ private String getProperty(OwnIdentity truster, Identity target, String property) throws Exception { SimpleFieldSet sfs = new SimpleFieldSet(true); sfs.putOverwrite("Message", "GetIdentity"); sfs.putOverwrite("Truster", truster.getID()); sfs.putOverwrite("Identity", target.getID()); return sendFCPMessageBlocking(sfs, null, "Identity").params.get(property); } /** * Not synchronized, the involved identities might be deleted during the query - which is not really a problem. */ public int getScore(final WoTOwnIdentity truster, final WoTIdentity trustee) throws NotInTrustTreeException, Exception { if(mIsUnitTest) return 0; final String score = getProperty(truster, trustee, "Score"); if(score.equals("null")) throw new NotInTrustTreeException(truster, trustee); final int value = Integer.parseInt(score); mWoTCache.putScore(truster, trustee, value); return value; } /** * Not synchronized, the involved identities might be deleted during the query - which is not really a problem. */ public byte getTrust(final WoTOwnIdentity truster, final WoTIdentity trustee) throws NotTrustedException, Exception { if(mIsUnitTest) return 0; final String trust = getProperty(truster, trustee, "Trust"); if(trust.equals("null")) throw new NotTrustedException(truster, trustee); final byte value = Byte.parseByte(trust); mWoTCache.putTrust(truster, trustee, value); return value; } /** * Not synchronized, the involved identities might be deleted during the query or some other WoT client might modify the trust value * during the query - which is not really a problem, you should not be modifying trust values of your own identity with multiple clients simultaneously. */ public void setTrust(OwnIdentity truster, Identity trustee, byte trust, String comment) throws Exception { WoTOwnIdentity wotTruster = (WoTOwnIdentity)truster; WoTIdentity wotTrustee = (WoTIdentity)trustee; SimpleFieldSet request = new SimpleFieldSet(true); request.putOverwrite("Message", "SetTrust"); request.putOverwrite("Truster", wotTruster.getID()); request.putOverwrite("Trustee", wotTrustee.getID()); request.putOverwrite("Value", Integer.toString(trust)); request.putOverwrite("Comment", comment); sendFCPMessageBlocking(request, null, "TrustSet"); mWoTCache.putTrust(wotTruster, wotTrustee, trust); } /** * Not synchronized, the involved identity might be deleted during the query - which is not really a problem. */ public List<WoTTrust> getReceivedTrusts(Identity trustee) throws Exception { List<WoTTrust> result = new ArrayList<WoTTrust>(); SimpleFieldSet request = new SimpleFieldSet(true); request.putOverwrite("Message", "GetTrusters"); request.putOverwrite("Context", ""); request.putOverwrite("Identity", trustee.getID()); try { SimpleFieldSet answer = sendFCPMessageBlocking(request, null, "Identities").params; for(int idx = 0; ; idx++) { String id = answer.get("Identity"+idx); if(id == null || id.equals("")) /* TODO: Figure out whether the second condition is necessary */ break; try { final WoTTrust trust = new WoTTrust(getIdentity(id), trustee, (byte)Integer.parseInt(answer.get("Value"+idx)), answer.get("Comment"+idx)); mWoTCache.putTrust(trust); result.add(trust); } catch (NoSuchIdentityException e) { } catch (InvalidParameterException e) { } } } catch(PluginNotFoundException e) { throw new WoTDisconnectedException(); } return result; } /** * Not synchronized, the involved identity might be deleted during the query - which is not really a problem. */ public int getReceivedTrustsCount(Identity trustee) throws Exception { SimpleFieldSet request = new SimpleFieldSet(true); request.putOverwrite("Message", "GetTrustersCount"); request.putOverwrite("Identity", trustee.getID()); request.putOverwrite("Context", Freetalk.WOT_CONTEXT); try { SimpleFieldSet answer = sendFCPMessageBlocking(request, null, "TrustersCount").params; return Integer.parseInt(answer.get("Value")); } catch(PluginNotFoundException e) { throw new WoTDisconnectedException(); } } /** * Get the number of trust values for a given identity with the ability to select which values should be counted. * * Not synchronized, the involved identity might be deleted during the query - which is not really a problem. * * @param selection Use 1 for counting trust values greater than or equal to zero, 0 for counting trust values exactly equal to 0 and -1 for counting trust * values less than zero. */ public int getReceivedTrustsCount(Identity trustee, int selection) throws Exception { SimpleFieldSet request = new SimpleFieldSet(true); request.putOverwrite("Message", "GetTrustersCount"); request.putOverwrite("Identity", trustee.getID()); request.putOverwrite("Context", Freetalk.WOT_CONTEXT); if(selection > 0) request.putOverwrite("Selection", "+"); else if(selection == 0) request.putOverwrite("Selection", "0"); else request.putOverwrite("Selection", "-"); try { SimpleFieldSet answer = sendFCPMessageBlocking(request, null, "TrustersCount").params; return Integer.parseInt(answer.get("Value")); } catch(PluginNotFoundException e) { throw new WoTDisconnectedException(); } } public int getGivenTrustsCount(Identity trustee, int selection) throws Exception { SimpleFieldSet request = new SimpleFieldSet(true); request.putOverwrite("Message", "GetTrusteesCount"); request.putOverwrite("Identity", trustee.getID()); request.putOverwrite("Context", Freetalk.WOT_CONTEXT); if(selection > 0) request.putOverwrite("Selection", "+"); else if(selection == 0) request.putOverwrite("Selection", "0"); else request.putOverwrite("Selection", "-"); try { SimpleFieldSet answer = sendFCPMessageBlocking(request, null, "TrusteesCount").params; return Integer.parseInt(answer.get("Value")); } catch(PluginNotFoundException e) { throw new WoTDisconnectedException(); } } public static final class IntroductionPuzzle { public final String ID; public final String MimeType; public final byte[] Data; protected IntroductionPuzzle(String myID, String myMimeType, byte[] myData) { if(myID == null) throw new NullPointerException(); if(myMimeType == null) throw new NullPointerException(); if(myData == null) throw new NullPointerException(); ID = myID; MimeType = myMimeType; Data = myData; } } /** * Get a set of introduction puzzle IDs which the given own identity might solve. * * The puzzle's data is not returned because when generating HTML for displaying the puzzles we must reference them with a IMG-tag and we cannot * embed the data of the puzzles in the IMG-tag because embedding image-data has only recently been added to browsers and many do not support it yet. * * @param ownIdentity The identity which wants to solve the puzzles. * @param amount The amount of puzzles to request. * @return A list of the IDs of the puzzles. The amount might be less than the requested amount and even zero if WoT has not downloaded puzzles yet. * @throws Exception */ public List<String> getIntroductionPuzzles(WoTOwnIdentity ownIdentity, int amount) throws Exception { ArrayList<String> puzzleIDs = new ArrayList<String>(amount + 1); SimpleFieldSet params = new SimpleFieldSet(true); params.putOverwrite("Message", "GetIntroductionPuzzles"); params.putOverwrite("Identity", ownIdentity.getID()); params.putOverwrite("Type", "Captcha"); // TODO: Don't hardcode the String params.put("Amount", amount); try { SimpleFieldSet result = sendFCPMessageBlocking(params, null, "IntroductionPuzzles").params; for(int idx = 0; ; idx++) { String id = result.get("Puzzle" + idx); if(id == null || id.equals("")) /* TODO: Figure out whether the second condition is necessary */ break; puzzleIDs.add(id); } } catch(PluginNotFoundException e) { Logger.error(this, "Getting puzzles failed", e); } return puzzleIDs; } public IntroductionPuzzle getIntroductionPuzzle(String id) throws Exception { SimpleFieldSet params = new SimpleFieldSet(true); params.putOverwrite("Message", "GetIntroductionPuzzle"); params.putOverwrite("Puzzle", id); try { SimpleFieldSet result = sendFCPMessageBlocking(params, null, "IntroductionPuzzle").params; try { return new IntroductionPuzzle(id, result.get("MimeType"), Base64.decodeStandard(result.get("Data"))); } catch(RuntimeException e) { Logger.error(this, "Parsing puzzle failed", e); } catch(IllegalBase64Exception e) { Logger.error(this, "Parsing puzzle failed", e); } return null; } catch(PluginNotFoundException e) { Logger.error(this, "Getting puzzles failed", e); return null; } } public void solveIntroductionPuzzle(WoTOwnIdentity ownIdentity, String puzzleID, String solution) throws Exception { SimpleFieldSet params = new SimpleFieldSet(true); params.putOverwrite("Message", "SolveIntroductionPuzzle"); params.putOverwrite("Identity", ownIdentity.getID()); params.putOverwrite("Puzzle", puzzleID); params.putOverwrite("Solution", solution); sendFCPMessageBlocking(params, null, "PuzzleSolved"); } private synchronized void addFreetalkContext(WoTIdentity oid) throws Exception { SimpleFieldSet params = new SimpleFieldSet(true); params.putOverwrite("Message", "AddContext"); params.putOverwrite("Identity", oid.getID()); params.putOverwrite("Context", Freetalk.WOT_CONTEXT); sendFCPMessageBlocking(params, null, "ContextAdded"); } /** * Fetches the identities with positive score from WoT and stores them in the database. * @throws Exception */ private void fetchIdentities() throws Exception { // parseIdentities() acquires and frees the WoTIdentityManager-lock for each identity to allow other threads to access the identity manager while the // parsing is in progress. Therefore, we do not take the lock for the whole execution of this function. synchronized(this) { if(mIdentityFetchInProgress) return; long now = CurrentTimeUTC.getInMillis(); if((now - mLastIdentityFetchTime) < MINIMAL_IDENTITY_FETCH_DELAY) return; mIdentityFetchInProgress = true; } try { Logger.normal(this, "Requesting identities with positive score from WoT ..."); SimpleFieldSet p1 = new SimpleFieldSet(true); p1.putOverwrite("Message", "GetIdentitiesByScore"); p1.putOverwrite("Selection", "+"); p1.putOverwrite("Context", Freetalk.WOT_CONTEXT); parseIdentities(sendFCPMessageBlocking(p1, null, "Identities").params, false); synchronized(this) { // We must update the fetch-time after the parsing and only if the parsing succeeded: // If we updated before the parsing and parsing failed or took ages (the thread sometimes takes 2 hours to execute, don't ask me why) // then the garbage collector would delete identities. mLastIdentityFetchTime = CurrentTimeUTC.getInMillis(); } } finally { synchronized(this) { mIdentityFetchInProgress = false; } } // We usually call garbageCollectIdentities() after calling this function, it updates the cache already... // if(mShortestUniqueNicknameCacheNeedsUpdate) // updateShortestUniqueNicknameCache(); } /** * Fetches the own identities with positive score from WoT and stores them in the database. * @throws Exception */ private void fetchOwnIdentities() throws Exception { // parseIdentities() acquires and frees the WoTIdentityManager-lock for each identity to allow other threads to access the identity manager while the // parsing is in progress. Therefore, we do not take the lock for the whole execution of this function. synchronized(this) { if(mOwnIdentityFetchInProgress) return; long now = CurrentTimeUTC.getInMillis(); if((now - mLastOwnIdentityFetchTime) < MINIMAL_OWN_IDENTITY_FETCH_DELAY) return; mOwnIdentityFetchInProgress = true; } try { Logger.normal(this, "Requesting own identities from WoT ..."); SimpleFieldSet p2 = new SimpleFieldSet(true); p2.putOverwrite("Message","GetOwnIdentities"); parseIdentities(sendFCPMessageBlocking(p2, null, "OwnIdentities").params, true); synchronized(this) { // We must update the fetch-time after the parsing and only if the parsing succeeded: // If we updated before the parsing and parsing failed or took ages (the thread sometimes takes 2 hours to execute, don't ask me why) // then the garbage collector would delete identities. mLastOwnIdentityFetchTime = CurrentTimeUTC.getInMillis(); } } finally { synchronized(this) { mOwnIdentityFetchInProgress = false; } } // We usually call garbageCollectIdentities() after calling this function, it updates the cache already... // if(mShortestUniqueNicknameCacheNeedsUpdate) // updateShortestUniqueNicknameCache(); } private void onNewIdentityAdded(Identity identity) { Logger.normal(this, "onNewIdentityAdded " + identity); mShortestUniqueNicknameCacheNeedsUpdate = true; doNewIdentityCallbacks(identity); if(!(identity instanceof OwnIdentity)) onShouldFetchStateChanged(identity, false, true); } /** * Called by this WoTIdentityManager after a new WoTIdentity has been stored to the database and before committing the transaction. * * You have to lock this WoTIdentityManager, the PersistentTaskManager and the database before calling this function. * * @param newIdentity * @throws Exception If adding the Freetalk context to the identity in WoT failed. */ private void onNewOwnIdentityAdded(OwnIdentity identity) { Logger.normal(this, "onNewOwnIdentityAdded " + identity); WoTOwnIdentity newIdentity = (WoTOwnIdentity)identity; // TODO: Do after an own message is posted. I have not decided at which place to do this :| try { addFreetalkContext(newIdentity); } catch (Exception e) { throw new RuntimeException(e); } PersistentTask introductionTask = new IntroduceIdentityTask((WoTOwnIdentity)newIdentity); mFreetalk.getTaskManager().storeTaskWithoutCommit(introductionTask); doNewOwnIdentityCallbacks(newIdentity); onShouldFetchStateChanged(newIdentity, false, true); } private void beforeIdentityDeletion(Identity identity) { Logger.normal(this, "beforeIdentityDeletion " + identity); doIdentityDeletedCallbacks(identity); if(!(identity instanceof OwnIdentity)) // Don't call it twice onShouldFetchStateChanged(identity, true, false); } private void beforeOwnIdentityDeletion(OwnIdentity identity) { Logger.normal(this, "beforeOwnIdentityDeletion " + identity); doOwnIdentityDeletedCallbacks(identity); onShouldFetchStateChanged(identity, true, false); } private void onShouldFetchStateChanged(Identity author, boolean oldShouldFetch, boolean newShouldFetch) { Logger.normal(this, "onShouldFetchStateChanged " + author); doShouldFetchStateChangedCallbacks(author, oldShouldFetch, newShouldFetch); } private void importIdentity(boolean ownIdentity, String identityID, String requestURI, String insertURI, String nickname) { synchronized(mFreetalk.getTaskManager()) { synchronized(db.lock()) { try { Logger.normal(this, "Importing identity from WoT: " + requestURI); final WoTIdentity id = ownIdentity ? new WoTOwnIdentity(identityID, new FreenetURI(requestURI), new FreenetURI(insertURI), nickname) : new WoTIdentity(identityID, new FreenetURI(requestURI), nickname); id.initializeTransient(mFreetalk); id.storeWithoutCommit(); onNewIdentityAdded(id); if(ownIdentity) onNewOwnIdentityAdded((WoTOwnIdentity)id); id.checkedCommit(this); } catch(Exception e) { Persistent.checkedRollbackAndThrow(db, this, new RuntimeException(e)); } } } } @SuppressWarnings("unchecked") private void parseIdentities(SimpleFieldSet params, boolean bOwnIdentities) { if(bOwnIdentities) Logger.normal(this, "Parsing received own identities..."); else Logger.normal(this, "Parsing received identities..."); int idx; int ignoredCount = 0; int newCount = 0; for(idx = 0; ; idx++) { String identityID = params.get("Identity"+idx); if(identityID == null || identityID.equals("")) /* TODO: Figure out whether the second condition is necessary */ break; String requestURI = params.get("RequestURI"+idx); String insertURI = bOwnIdentities ? params.get("InsertURI"+idx) : null; String nickname = params.get("Nickname"+idx); - if(nickname.length() == 0) { + if(nickname == null || nickname.length() == 0) { // If an identity publishes an invalid nickname in one of its first WoT inserts then WoT will return an empty // nickname for that identity until a new XML was published with a valid nickname. We ignore the identity until // then to prevent confusing error logs. // TODO: Maybe handle this in WoT. Would require checks in many places though. continue; } synchronized(this) { /* We lock here and not during the whole function to allow other threads to execute */ Query q = db.query(); // TODO: Encapsulate the query in a function... q.constrain(WoTIdentity.class); q.descend("mID").constrain(identityID); ObjectSet<WoTIdentity> result = q.execute(); WoTIdentity id = null; if(result.size() == 0) { try { importIdentity(bOwnIdentities, identityID, requestURI, insertURI, nickname); ++newCount; } catch(Exception e) { Logger.error(this, "Importing a new identity failed.", e); } } else { Logger.debug(this, "Not importing already existing identity " + requestURI); ++ignoredCount; assert(result.size() == 1); id = result.next(); id.initializeTransient(mFreetalk); if(bOwnIdentities != (id instanceof WoTOwnIdentity)) { // The type of the identity changed so we need to delete and re-import it. try { Logger.normal(this, "Identity type changed, replacing it: " + id); // We MUST NOT take the following locks because deleteIdentity does other locks (MessageManager/TaskManager) which must happen before... // synchronized(id) // synchronized(db.lock()) deleteIdentity(id, mFreetalk.getMessageManager(), mFreetalk.getTaskManager()); importIdentity(bOwnIdentities, identityID, requestURI, insertURI, nickname); } catch(Exception e) { Logger.error(this, "Replacing a WoTIdentity with WoTOwnIdentity failed.", e); } } else { // Normal case: Update the last received time of the idefnt synchronized(id) { synchronized(db.lock()) { try { // TODO: The thread sometimes takes hours to parse the identities and I don't know why. // So right now its better to re-query the time for each identity. id.setLastReceivedFromWoT(CurrentTimeUTC.getInMillis()); id.checkedCommit(this); } catch(Exception e) { Persistent.checkedRollback(db, this, e); } } } } } } Thread.yield(); } Logger.normal(this, "parseIdentities(bOwnIdentities==" + bOwnIdentities + " received " + idx + " identities. Ignored " + ignoredCount + "; New: " + newCount ); } @SuppressWarnings("unchecked") private void garbageCollectIdentities() { final MessageManager messageManager = mFreetalk.getMessageManager(); final PersistentTaskManager taskManager = mFreetalk.getTaskManager(); synchronized(this) { if(mIdentityFetchInProgress || mOwnIdentityFetchInProgress || mLastIdentityFetchTime == 0 || mLastOwnIdentityFetchTime == 0) return; /* Executing the thread loop once will always take longer than THREAD_PERIOD. Therefore, if we set the limit to 3*THREAD_PERIOD, * it will hit identities which were last received before more than 2*THREAD_LOOP, not exactly 3*THREAD_LOOP. */ long lastAcceptTime = Math.min(mLastIdentityFetchTime, mLastOwnIdentityFetchTime) - GARBAGE_COLLECT_DELAY; lastAcceptTime = Math.max(lastAcceptTime, 0); // This is not really needed but a time less than 0 does not make sense.; Query q = db.query(); q.constrain(WoTIdentity.class); q.descend("mLastReceivedFromWoT").constrain(lastAcceptTime).smaller(); ObjectSet<WoTIdentity> result = q.execute(); for(WoTIdentity identity : result) { identity.initializeTransient(mFreetalk); Logger.debug(this, "Garbage collecting identity " + identity); deleteIdentity(identity, messageManager, taskManager); } if(mShortestUniqueNicknameCacheNeedsUpdate) updateShortestUniqueNicknameCache(); } } private synchronized void deleteIdentity(WoTIdentity identity, MessageManager messageManager, PersistentTaskManager taskManager) { identity.initializeTransient(mFreetalk); beforeIdentityDeletion(identity); if(identity instanceof WoTOwnIdentity) beforeOwnIdentityDeletion((WoTOwnIdentity)identity); synchronized(identity) { synchronized(db.lock()) { try { identity.deleteWithoutCommit(); Logger.normal(this, "Identity deleted: " + identity); identity.checkedCommit(this); } catch(RuntimeException e) { Persistent.checkedRollbackAndThrow(db, this, e); } } } mShortestUniqueNicknameCacheNeedsUpdate = true; } private synchronized boolean connectToWoT() { if(mTalker != null) { /* Old connection exists */ SimpleFieldSet sfs = new SimpleFieldSet(true); sfs.putOverwrite("Message", "Ping"); try { mTalker.sendBlocking(sfs, null); /* Verify that the old connection is still alive */ return true; } catch(PluginNotFoundException e) { mTalker = null; /* Do not return, try to reconnect in next try{} block */ } } try { mTalker = new PluginTalkerBlocking(mFreetalk.getPluginRespirator()); mFreetalk.handleWotConnected(); return true; } catch(PluginNotFoundException e) { mFreetalk.handleWotDisconnected(); return false; } } public void run() { Logger.debug(this, "Main loop running..."); try { mConnectedToWoT = connectToWoT(); if(mConnectedToWoT) { try { fetchOwnIdentities(); // Fetch the own identities first to prevent own-identities from being imported as normal identity... fetchIdentities(); garbageCollectIdentities(); } catch (Exception e) { Logger.error(this, "Fetching identities failed.", e); } } } finally { final long sleepTime = mConnectedToWoT ? (THREAD_PERIOD/2 + mRandom.nextInt(THREAD_PERIOD)) : WOT_RECONNECT_DELAY; Logger.debug(this, "Sleeping for " + (sleepTime / (60*1000)) + " minutes."); mTicker.queueTimedJob(this, "Freetalk " + this.getClass().getSimpleName(), sleepTime, false, true); } Logger.debug(this, "Main loop finished."); } public int getPriority() { return NativeThread.MIN_PRIORITY; } public void start() { Logger.debug(this, "Starting..."); deleteDuplicateIdentities(); mTicker.queueTimedJob(this, "Freetalk " + this.getClass().getSimpleName(), 0, false, true); // TODO: Queue this as a job aswell. try { updateShortestUniqueNicknameCache(); } catch(Exception e) { Logger.error(this, "Initializing shortest unique nickname cache failed", e); } Logger.debug(this, "Started."); } /** * Checks for duplicate identity objects and deletes duplicates if they exist. * I have absolutely NO idea why Bombe does happen to have a duplicate identity, I see no code path which could cause this. * TODO: Get rid of this function if nobody reports a duplicate for some time - the function was added at 2011-01-10 */ private synchronized void deleteDuplicateIdentities() { WoTMessageManager messageManager = mFreetalk.getMessageManager(); PersistentTaskManager taskManager = mFreetalk.getTaskManager(); synchronized(messageManager) { synchronized(taskManager) { synchronized(db.lock()) { try { HashSet<String> deleted = new HashSet<String>(); Logger.normal(this, "Searching for duplicate identities ..."); for(WoTIdentity identity : getAllIdentities()) { Query q = db.query(); q.constrain(WoTIdentity.class); q.descend("mID").constrain(identity.getID()); q.constrain(identity).identity().not(); ObjectSet<WoTIdentity> duplicates = new Persistent.InitializingObjectSet<WoTIdentity>(mFreetalk, q); for(WoTIdentity duplicate : duplicates) { if(deleted.contains(duplicate.getID()) == false) { Logger.error(duplicate, "Deleting duplicate identity " + duplicate.getRequestURI()); deleteIdentity(duplicate, messageManager, taskManager); } } deleted.add(identity.getID()); } Persistent.checkedCommit(db, this); Logger.normal(this, "Finished searching for duplicate identities."); } catch(RuntimeException e) { Persistent.checkedRollback(db, this, e); } } } } } public void terminate() { Logger.debug(this, "Terminating ..."); mTicker.shutdown(); Logger.debug(this, "Terminated."); } // TODO: This function should be a feature of WoT. @SuppressWarnings("unchecked") private synchronized void updateShortestUniqueNicknameCache() { Logger.debug(this, "Updating shortest unique nickname cache..."); // We don't use getAllIdentities() because we do not need to have intializeTransient() called on each identity, we only query strings anyway. final Query q = db.query(); q.constrain(WoTIdentity.class); ObjectSet<WoTIdentity> result = q.execute(); final WoTIdentity[] identities = result.toArray(new WoTIdentity[result.size()]); Arrays.sort(identities, new Comparator<WoTIdentity>() { public int compare(WoTIdentity i1, WoTIdentity i2) { return i1.getFreetalkAddress().compareToIgnoreCase(i2.getFreetalkAddress()); } }); final String[] nicknames = new String[identities.length]; for(int i=0; i < identities.length; ++i) { nicknames[i] = identities[i].getNickname(); int minLength = nicknames[i].length(); int firstDuplicate; do { firstDuplicate = i; while((firstDuplicate-1) >= 0 && nicknames[firstDuplicate-1].equalsIgnoreCase(nicknames[i])) { --firstDuplicate; } if(firstDuplicate < i) { ++minLength; for(int j=i; j >= firstDuplicate; --j) { nicknames[j] = identities[j].getFreetalkAddress(minLength); } } } while(firstDuplicate != i); } final HashMap<String,String> newCache = new HashMap<String, String>(identities.length * 2); for(int i = 0; i < identities.length; ++i) newCache.put(identities[i].getID(), nicknames[i]); mShortestUniqueNicknameCache = newCache; mShortestUniqueNicknameCacheNeedsUpdate = false; Logger.debug(this, "Finished updating shortest unique nickname cache."); } @Override public String getShortestUniqueName(Identity identity) { // We must not synchronize anything according to the specification of this function (to prevent deadlocks) String nickname = mShortestUniqueNicknameCache.get(identity.getID()); if(nickname == null) nickname = identity.getFreetalkAddress(); return nickname; } private final class WebOfTrustCache { public static final long EXPIRATION_DELAY = 5 * 60 * 1000; private final class TrustKey { public final String mTrusterID; public final String mTrusteeID; public TrustKey(final WoTTrust trust) { mTrusterID = trust.getTruster().getID(); mTrusteeID = trust.getTrustee().getID(); } public TrustKey(final WoTIdentity truster, final WoTIdentity trustee) { mTrusterID = truster.getID(); mTrusteeID = trustee.getID(); } @Override public boolean equals(final Object o) { final TrustKey other = (TrustKey)o; return mTrusterID.equals(other.mTrusterID) && mTrusteeID.equals(other.mTrusteeID); } @Override public int hashCode() { return mTrusterID.hashCode() ^ mTrusteeID.hashCode(); } } private final LRUCache<TrustKey, Byte> mTrustCache = new LRUCache<TrustKey, Byte>(256, EXPIRATION_DELAY); private final LRUCache<TrustKey, Integer> mScoreCache = new LRUCache<TrustKey, Integer>(256, EXPIRATION_DELAY); // TODO: Create getter methods in WoTIdentityManager which actually use this caching function... public synchronized byte getTrust(final WoTOwnIdentity truster, final WoTIdentity trustee) throws NotTrustedException, Exception { { final Byte cachedValue = mTrustCache.get(new TrustKey(truster, trustee)); if(cachedValue != null) return cachedValue; } return WoTIdentityManager.this.getTrust(truster, trustee); // This will update the cache } // TODO: Create getter methods in WoTIdentityManager which actually use this caching function... public synchronized int getScore(final WoTOwnIdentity truster, final WoTIdentity trustee) throws NotInTrustTreeException, Exception { { final Integer cachedValue = mScoreCache.get(new TrustKey(truster, trustee)); if(cachedValue != null) return cachedValue; } return WoTIdentityManager.this.getScore(truster, trustee); // This will update the cache } public synchronized void putTrust(final WoTIdentity truster, final WoTIdentity trustee, final byte value) { mTrustCache.put(new TrustKey(truster, trustee), value); } public synchronized void putTrust(final WoTTrust trust) { mTrustCache.put(new TrustKey(trust), trust.getValue()); } public synchronized void putScore(final WoTOwnIdentity truster, final WoTIdentity trustee, final int value) { mScoreCache.put(new TrustKey(truster, trustee), value); } } }
true
true
private void parseIdentities(SimpleFieldSet params, boolean bOwnIdentities) { if(bOwnIdentities) Logger.normal(this, "Parsing received own identities..."); else Logger.normal(this, "Parsing received identities..."); int idx; int ignoredCount = 0; int newCount = 0; for(idx = 0; ; idx++) { String identityID = params.get("Identity"+idx); if(identityID == null || identityID.equals("")) /* TODO: Figure out whether the second condition is necessary */ break; String requestURI = params.get("RequestURI"+idx); String insertURI = bOwnIdentities ? params.get("InsertURI"+idx) : null; String nickname = params.get("Nickname"+idx); if(nickname.length() == 0) { // If an identity publishes an invalid nickname in one of its first WoT inserts then WoT will return an empty // nickname for that identity until a new XML was published with a valid nickname. We ignore the identity until // then to prevent confusing error logs. // TODO: Maybe handle this in WoT. Would require checks in many places though. continue; } synchronized(this) { /* We lock here and not during the whole function to allow other threads to execute */ Query q = db.query(); // TODO: Encapsulate the query in a function... q.constrain(WoTIdentity.class); q.descend("mID").constrain(identityID); ObjectSet<WoTIdentity> result = q.execute(); WoTIdentity id = null; if(result.size() == 0) { try { importIdentity(bOwnIdentities, identityID, requestURI, insertURI, nickname); ++newCount; } catch(Exception e) { Logger.error(this, "Importing a new identity failed.", e); } } else { Logger.debug(this, "Not importing already existing identity " + requestURI); ++ignoredCount; assert(result.size() == 1); id = result.next(); id.initializeTransient(mFreetalk); if(bOwnIdentities != (id instanceof WoTOwnIdentity)) { // The type of the identity changed so we need to delete and re-import it. try { Logger.normal(this, "Identity type changed, replacing it: " + id); // We MUST NOT take the following locks because deleteIdentity does other locks (MessageManager/TaskManager) which must happen before... // synchronized(id) // synchronized(db.lock()) deleteIdentity(id, mFreetalk.getMessageManager(), mFreetalk.getTaskManager()); importIdentity(bOwnIdentities, identityID, requestURI, insertURI, nickname); } catch(Exception e) { Logger.error(this, "Replacing a WoTIdentity with WoTOwnIdentity failed.", e); } } else { // Normal case: Update the last received time of the idefnt synchronized(id) { synchronized(db.lock()) { try { // TODO: The thread sometimes takes hours to parse the identities and I don't know why. // So right now its better to re-query the time for each identity. id.setLastReceivedFromWoT(CurrentTimeUTC.getInMillis()); id.checkedCommit(this); } catch(Exception e) { Persistent.checkedRollback(db, this, e); } } } } } } Thread.yield(); } Logger.normal(this, "parseIdentities(bOwnIdentities==" + bOwnIdentities + " received " + idx + " identities. Ignored " + ignoredCount + "; New: " + newCount ); }
private void parseIdentities(SimpleFieldSet params, boolean bOwnIdentities) { if(bOwnIdentities) Logger.normal(this, "Parsing received own identities..."); else Logger.normal(this, "Parsing received identities..."); int idx; int ignoredCount = 0; int newCount = 0; for(idx = 0; ; idx++) { String identityID = params.get("Identity"+idx); if(identityID == null || identityID.equals("")) /* TODO: Figure out whether the second condition is necessary */ break; String requestURI = params.get("RequestURI"+idx); String insertURI = bOwnIdentities ? params.get("InsertURI"+idx) : null; String nickname = params.get("Nickname"+idx); if(nickname == null || nickname.length() == 0) { // If an identity publishes an invalid nickname in one of its first WoT inserts then WoT will return an empty // nickname for that identity until a new XML was published with a valid nickname. We ignore the identity until // then to prevent confusing error logs. // TODO: Maybe handle this in WoT. Would require checks in many places though. continue; } synchronized(this) { /* We lock here and not during the whole function to allow other threads to execute */ Query q = db.query(); // TODO: Encapsulate the query in a function... q.constrain(WoTIdentity.class); q.descend("mID").constrain(identityID); ObjectSet<WoTIdentity> result = q.execute(); WoTIdentity id = null; if(result.size() == 0) { try { importIdentity(bOwnIdentities, identityID, requestURI, insertURI, nickname); ++newCount; } catch(Exception e) { Logger.error(this, "Importing a new identity failed.", e); } } else { Logger.debug(this, "Not importing already existing identity " + requestURI); ++ignoredCount; assert(result.size() == 1); id = result.next(); id.initializeTransient(mFreetalk); if(bOwnIdentities != (id instanceof WoTOwnIdentity)) { // The type of the identity changed so we need to delete and re-import it. try { Logger.normal(this, "Identity type changed, replacing it: " + id); // We MUST NOT take the following locks because deleteIdentity does other locks (MessageManager/TaskManager) which must happen before... // synchronized(id) // synchronized(db.lock()) deleteIdentity(id, mFreetalk.getMessageManager(), mFreetalk.getTaskManager()); importIdentity(bOwnIdentities, identityID, requestURI, insertURI, nickname); } catch(Exception e) { Logger.error(this, "Replacing a WoTIdentity with WoTOwnIdentity failed.", e); } } else { // Normal case: Update the last received time of the idefnt synchronized(id) { synchronized(db.lock()) { try { // TODO: The thread sometimes takes hours to parse the identities and I don't know why. // So right now its better to re-query the time for each identity. id.setLastReceivedFromWoT(CurrentTimeUTC.getInMillis()); id.checkedCommit(this); } catch(Exception e) { Persistent.checkedRollback(db, this, e); } } } } } } Thread.yield(); } Logger.normal(this, "parseIdentities(bOwnIdentities==" + bOwnIdentities + " received " + idx + " identities. Ignored " + ignoredCount + "; New: " + newCount ); }
diff --git a/sgs-server/src/main/java/com/sun/sgs/impl/profile/util/NetworkReporter.java b/sgs-server/src/main/java/com/sun/sgs/impl/profile/util/NetworkReporter.java index ce7a54456..ea87567f6 100644 --- a/sgs-server/src/main/java/com/sun/sgs/impl/profile/util/NetworkReporter.java +++ b/sgs-server/src/main/java/com/sun/sgs/impl/profile/util/NetworkReporter.java @@ -1,116 +1,116 @@ /* * 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.util; import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.HashSet; import java.util.Iterator; /** * A very simple utility class used to report on a socket. This allows * any number of clients to connect and listen for text encoded in the * platform's default character set encoding. Note that this is * intended only as a means for reporting in testing and development * systems. In deployment, a more robust mechanism should be used. */ public final class NetworkReporter { // the set of connected clients private HashSet<Socket> listeners; private final ServerSocket serverSocket; private final Thread reporterThread; /** * Creates an instance of <code>NetworkReporter</code>. * * @param port the port on which to listen for client connections * * @throws IOException if the server socket cannot be created */ public NetworkReporter(int port) throws IOException { listeners = new HashSet<Socket>(); serverSocket = new ServerSocket(port); reporterThread = new Thread(new NetworkReporterRunnable()); reporterThread.start(); } /** * Reports the provided message to all connected clients. If the * message cannot be sent to a given client, then that client is * dropped from the set of connected clients. * * @param message the message to send */ public synchronized void report(String message) { Iterator<Socket> it = listeners.iterator(); while (it.hasNext()) { Socket socket = it.next(); try { OutputStream stream = socket.getOutputStream(); stream.write(message.getBytes()); stream.flush(); } catch (IOException ioe) { - listeners.remove(socket); + it.remove(); } } } /** * Cleans up. */ public void shutdown() { try { reporterThread.interrupt(); serverSocket.close(); } catch (IOException ioe) { // do nothing } } /** * A private class used to run the long-lived server task. It simply * listens for connecting clients, and adds them to the set of connected * clients. If accepting a client fails, then the server socket is closed. */ private class NetworkReporterRunnable implements Runnable { NetworkReporterRunnable() { } public void run() { try { while (true) { synchronized (this) { listeners.add(serverSocket.accept()); } } } catch (IOException e) { try { serverSocket.close(); } catch (IOException ioe) { } } } } }
true
true
public synchronized void report(String message) { Iterator<Socket> it = listeners.iterator(); while (it.hasNext()) { Socket socket = it.next(); try { OutputStream stream = socket.getOutputStream(); stream.write(message.getBytes()); stream.flush(); } catch (IOException ioe) { listeners.remove(socket); } } }
public synchronized void report(String message) { Iterator<Socket> it = listeners.iterator(); while (it.hasNext()) { Socket socket = it.next(); try { OutputStream stream = socket.getOutputStream(); stream.write(message.getBytes()); stream.flush(); } catch (IOException ioe) { it.remove(); } } }
diff --git a/code/potrans/src/test/java/org/overturetool/potrans/external_tools/CommandLineProcessTest.java b/code/potrans/src/test/java/org/overturetool/potrans/external_tools/CommandLineProcessTest.java index e8437be34f..180f03ed12 100644 --- a/code/potrans/src/test/java/org/overturetool/potrans/external_tools/CommandLineProcessTest.java +++ b/code/potrans/src/test/java/org/overturetool/potrans/external_tools/CommandLineProcessTest.java @@ -1,388 +1,387 @@ /** * */ package org.overturetool.potrans.external_tools; import java.io.ByteArrayInputStream; import java.io.IOException; import org.overturetool.potrans.external_tools.CommandLineProcess; import org.overturetool.potrans.external_tools.CommandLineProcessCommand; import org.overturetool.potrans.external_tools.CommandLineProcessStringInput; import org.overturetool.potrans.external_tools.InputValidator; import junit.framework.TestCase; /** * @author miguel_ferreira * */ public class CommandLineProcessTest extends TestCase { private final static String newLine = System.getProperty("line.separator"); private static final String VPPDE_PROPERTY_ERROR_MESSAGE = "You have to set the flag -DvppdeExecutable=<path to executable> for the JVM in" + " the JUnit launch configuration."; private static String vppdeExecutable = System .getProperty("vppdeExecutable");; private static String settingsWarning = "If this test fails check that you set the property " + "\"-DvppdeExecutable=</path/to/vdmtools/bin/>vppde\" in the JVM arguments."; /* * (non-Javadoc) * * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); InputValidator.validateStringNotEmptyNorNull(vppdeExecutable, VPPDE_PROPERTY_ERROR_MESSAGE); } /* * (non-Javadoc) * * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#executeProcessAndWaitForItToFinish()} * . */ public void testExecuteProcessAndWaitForItToFinish() throws Exception { String inputString = "This is a test"; CommandLineProcessCommand command = new CommandLineProcessCommand( "echo", new String[] { inputString }); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); int exitValue = cmdLineProcess.executeProcessAndWaitForItToFinish(); assertEquals(0, exitValue); } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#executeProcessAndWaitForItToFinish()} * . */ public void testExecuteProcessAndWaitForItToFinishInvalidCommand() throws Exception { String invalidCommand = "invalid_command"; CommandLineProcessCommand command = new CommandLineProcessCommand( "echo", new String[] { invalidCommand }); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); try { cmdLineProcess.executeProcessAndWaitForItToFinish(); } catch (IOException e) { assertEquals(invalidCommand + ": not found", e.getMessage()); } finally { cmdLineProcess.destroy(); } } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#executeProcessAndWaitForItToFinish()} * . */ public void testExecuteProcessAndWaitForItToFinishEmptyCommand() throws Exception { String emptyCommand = ""; CommandLineProcessCommand command = new CommandLineProcessCommand( "echo", new String[] { emptyCommand }); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); try { cmdLineProcess.executeProcessAndWaitForItToFinish(); } catch (IOException e) { assertEquals(emptyCommand + ": not found", e.getMessage()); } finally { cmdLineProcess.destroy(); } } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#executeProcess()} * . */ public void testExecuteProcess() throws Exception { String waitCommand; if (System.getProperty("os.name").startsWith("Windows")) waitCommand = "PAUSE"; else waitCommand = "read"; CommandLineProcessCommand command = new CommandLineProcessCommand( "echo", new String[] { waitCommand }); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); cmdLineProcess.executeProcess(); try { cmdLineProcess.getExitValue(); } catch (IllegalThreadStateException e) { assertEquals("process hasn't exited", e.getMessage()); } finally { if(!cmdLineProcess.isFinished()) cmdLineProcess.destroy(); } } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#executeProcess()} * . */ public void testExecuteProcessInvalidCommand() throws Exception { String invalidCommand = "invalid_command"; CommandLineProcessCommand command = new CommandLineProcessCommand( "echo", new String[] { invalidCommand }); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); try { cmdLineProcess.executeProcess(); } catch (IOException e) { assertEquals(invalidCommand + ": not found", e.getMessage()); } finally { if(!cmdLineProcess.isFinished()) cmdLineProcess.destroy(); } } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#executeProcess()} * . */ public void testExecuteProcessEmptyCommand() throws Exception { String emptyCommand = ""; CommandLineProcessCommand command = new CommandLineProcessCommand( "echo", new String[] { emptyCommand }); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); try { cmdLineProcess.executeProcess(); } catch (IOException e) { assertEquals(emptyCommand + ": not found", e.getMessage()); } finally { if(!cmdLineProcess.isFinished()) cmdLineProcess.destroy(); } } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#getProcessOutput()} * . */ public void testGetProcessOutput() throws Exception { String inputString = "This is a test"; CommandLineProcessCommand command = new CommandLineProcessCommand( "echo", new String[] { inputString }); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); cmdLineProcess.executeProcessAndWaitForItToFinish(); String actual = cmdLineProcess.getProcessOutput(); assertEquals(inputString, actual.trim()); } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#getProcessError()} * . */ public void testGetProcessError() throws Exception { String invalidFlag = "-invalid_flag"; CommandLineProcessCommand command = new CommandLineProcessCommand( vppdeExecutable, new String[] { invalidFlag }); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); cmdLineProcess.executeProcessAndWaitForItToFinish(); String actual = cmdLineProcess.getProcessError(); assertTrue(settingsWarning, cmdLineProcess.getExitValue() != 0); assertTrue(settingsWarning, actual .contains("Usage: vppde [options] [specfiles]")); } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#setProcessInput(java.lang.String)} * . * * Miguel: This test will probably fail on Windows. If it does please * contact me and supply the output from JUnit. */ public void testSetProcessInput() throws Exception { CommandLineProcessCommand command = new CommandLineProcessCommand( vppdeExecutable); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); cmdLineProcess.executeProcess(); cmdLineProcess.setProcessInput(new CommandLineProcessStringInput("quit" + newLine)); cmdLineProcess.waitFor(); assertEquals(settingsWarning, 0, cmdLineProcess.getExitValue()); } public void testSetProcessInputOutputInterleaved() throws Exception { - String expected = "The VDM++ Toolbox v8.1.1b - Fri 24-Oct-2008 08:59:25" + newLine - + "vpp> " + String expected = "vpp> " + "backtrace (bt) init (i) tcov read file " + newLine + "break (b) dlclose (dlc) tcov write file " + newLine + "classes disable (dis) ident tcov reset " + newLine + "codegen (cg) class [opt] enable (ena) ident script file " + newLine + "cont (c) instvars class selthread " + newLine + "cquit javacg (jcg) class [opt] set option " + newLine + "create (cr) last singlestep (g) " + newLine + "curthread latex (l) opt ident step (s) " + newLine + "debug (d) expr next (n) stepin (si) " + newLine + "delete (dl) ident,... objects system (sys) " + newLine + "destroy obj operations class threads " + newLine + "dir path,... priorityfile (pf) typecheck (tc) class opt " + newLine + "encode previous (pr) types class " + newLine + "fscode print (p) expr,.. unset option " + newLine + "finish pwd values class " + newLine + "first (f) quit (q) version (v) " + newLine + "functions class read (r) file " + newLine + "info (?) command rtinfo ident " + newLine + "vpp> "; CommandLineProcessCommand command = new CommandLineProcessCommand( vppdeExecutable); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); cmdLineProcess.executeProcess(); cmdLineProcess.setProcessInput(new CommandLineProcessStringInput("help" + newLine)); cmdLineProcess.setProcessInput(new CommandLineProcessStringInput("quit" + newLine)); cmdLineProcess.waitFor(); assertEquals(settingsWarning, 0, cmdLineProcess.getExitValue()); - assertEquals(settingsWarning, expected, cmdLineProcess.getProcessOutput()); + assertTrue(settingsWarning, cmdLineProcess.getProcessOutput().endsWith(expected)); } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#getProcessOutputFromStream(java.io.InputStream)} * . */ public void testGetProcessOutputFromStream() throws Exception { String expected = "This is a test."; ByteArrayInputStream inputStream = new ByteArrayInputStream(expected .getBytes()); String actual = CommandLineProcess .getProcessOutputFromStream(inputStream); assertEquals(expected, actual); } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#getProcessOutputFromStream(java.io.InputStream)} * . */ public void testGetProcessOutputFromStreamNullInputStream() throws Exception { ByteArrayInputStream inputStream = null; String actual = CommandLineProcess .getProcessOutputFromStream(inputStream); assertEquals("", actual); } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#getTextFromStreamToStringBuffer(java.io.InputStream, java.lang.StringBuffer)} * . */ public void testGetTextFromStreamToStringBuffer() throws Exception { String expected = "This is a test."; ByteArrayInputStream inputStream = new ByteArrayInputStream(expected .getBytes()); StringBuffer text = new StringBuffer(); CommandLineProcess.getTextFromStreamToStringBuffer(inputStream, text); assertEquals(expected, text.toString()); } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#getTextFromStreamToStringBuffer(java.io.InputStream, java.lang.StringBuffer)} * . */ public void testGetTextFromStreamToStringBufferNullInputStream() throws Exception { ByteArrayInputStream inputStream = null; StringBuffer text = new StringBuffer(); CommandLineProcess.getTextFromStreamToStringBuffer(inputStream, text); assertEquals("", text.toString()); } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#getTextFromStreamToStringBuffer(java.io.InputStream, java.lang.StringBuffer)} * . */ public void testGetTextFromStreamToStringBufferNullTextBuffer() throws Exception { ByteArrayInputStream inputStream = new ByteArrayInputStream( "This is a test.".getBytes()); StringBuffer text = null; CommandLineProcess.getTextFromStreamToStringBuffer(inputStream, text); assertNull(text); } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#getExitValue()} * . */ public void testGetExitValue() throws Exception { String inputString = "This is a test"; CommandLineProcessCommand command = new CommandLineProcessCommand( "echo", new String[] { inputString }); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); int expected = cmdLineProcess.executeProcessAndWaitForItToFinish(); assertEquals(expected, cmdLineProcess.getExitValue()); } /** * Test method for * {@link org.overturetool.potrans.external_tools.CommandLineProcess#getExitValue()} * . */ public void testGetExitValueProcessNotFinished() throws Exception { String waitCommand; if (System.getProperty("os.name").startsWith("Windows")) waitCommand = "PAUSE"; else waitCommand = "read"; CommandLineProcessCommand command = new CommandLineProcessCommand( "echo", new String[] { waitCommand }); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); cmdLineProcess.executeProcess(); try { cmdLineProcess.getExitValue(); } catch (IllegalThreadStateException e) { assertEquals("process hasn't exited", e.getMessage()); } finally { if(!cmdLineProcess.isFinished()) cmdLineProcess.destroy(); } } }
false
true
public void testSetProcessInputOutputInterleaved() throws Exception { String expected = "The VDM++ Toolbox v8.1.1b - Fri 24-Oct-2008 08:59:25" + newLine + "vpp> " + "backtrace (bt) init (i) tcov read file " + newLine + "break (b) dlclose (dlc) tcov write file " + newLine + "classes disable (dis) ident tcov reset " + newLine + "codegen (cg) class [opt] enable (ena) ident script file " + newLine + "cont (c) instvars class selthread " + newLine + "cquit javacg (jcg) class [opt] set option " + newLine + "create (cr) last singlestep (g) " + newLine + "curthread latex (l) opt ident step (s) " + newLine + "debug (d) expr next (n) stepin (si) " + newLine + "delete (dl) ident,... objects system (sys) " + newLine + "destroy obj operations class threads " + newLine + "dir path,... priorityfile (pf) typecheck (tc) class opt " + newLine + "encode previous (pr) types class " + newLine + "fscode print (p) expr,.. unset option " + newLine + "finish pwd values class " + newLine + "first (f) quit (q) version (v) " + newLine + "functions class read (r) file " + newLine + "info (?) command rtinfo ident " + newLine + "vpp> "; CommandLineProcessCommand command = new CommandLineProcessCommand( vppdeExecutable); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); cmdLineProcess.executeProcess(); cmdLineProcess.setProcessInput(new CommandLineProcessStringInput("help" + newLine)); cmdLineProcess.setProcessInput(new CommandLineProcessStringInput("quit" + newLine)); cmdLineProcess.waitFor(); assertEquals(settingsWarning, 0, cmdLineProcess.getExitValue()); assertEquals(settingsWarning, expected, cmdLineProcess.getProcessOutput()); }
public void testSetProcessInputOutputInterleaved() throws Exception { String expected = "vpp> " + "backtrace (bt) init (i) tcov read file " + newLine + "break (b) dlclose (dlc) tcov write file " + newLine + "classes disable (dis) ident tcov reset " + newLine + "codegen (cg) class [opt] enable (ena) ident script file " + newLine + "cont (c) instvars class selthread " + newLine + "cquit javacg (jcg) class [opt] set option " + newLine + "create (cr) last singlestep (g) " + newLine + "curthread latex (l) opt ident step (s) " + newLine + "debug (d) expr next (n) stepin (si) " + newLine + "delete (dl) ident,... objects system (sys) " + newLine + "destroy obj operations class threads " + newLine + "dir path,... priorityfile (pf) typecheck (tc) class opt " + newLine + "encode previous (pr) types class " + newLine + "fscode print (p) expr,.. unset option " + newLine + "finish pwd values class " + newLine + "first (f) quit (q) version (v) " + newLine + "functions class read (r) file " + newLine + "info (?) command rtinfo ident " + newLine + "vpp> "; CommandLineProcessCommand command = new CommandLineProcessCommand( vppdeExecutable); CommandLineProcess cmdLineProcess = new CommandLineProcess(command); cmdLineProcess.executeProcess(); cmdLineProcess.setProcessInput(new CommandLineProcessStringInput("help" + newLine)); cmdLineProcess.setProcessInput(new CommandLineProcessStringInput("quit" + newLine)); cmdLineProcess.waitFor(); assertEquals(settingsWarning, 0, cmdLineProcess.getExitValue()); assertTrue(settingsWarning, cmdLineProcess.getProcessOutput().endsWith(expected)); }
diff --git a/src/net/sf/freecol/server/model/ServerColony.java b/src/net/sf/freecol/server/model/ServerColony.java index 0309b0706..731bc4954 100644 --- a/src/net/sf/freecol/server/model/ServerColony.java +++ b/src/net/sf/freecol/server/model/ServerColony.java @@ -1,573 +1,573 @@ /** * Copyright (C) 2002-2011 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.server.model; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map.Entry; import java.util.Random; import java.util.logging.Logger; import net.sf.freecol.common.model.AbstractGoods; import net.sf.freecol.common.model.BuildQueue; import net.sf.freecol.common.model.BuildableType; import net.sf.freecol.common.model.Building; import net.sf.freecol.common.model.BuildingType; import net.sf.freecol.common.model.Colony; import net.sf.freecol.common.model.ColonyTile; import net.sf.freecol.common.model.ExportData; import net.sf.freecol.common.model.FreeColGameObject; import net.sf.freecol.common.model.Game; import net.sf.freecol.common.model.Goods; import net.sf.freecol.common.model.GoodsContainer; import net.sf.freecol.common.model.GoodsType; import net.sf.freecol.common.model.Market; import net.sf.freecol.common.model.ModelMessage; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.ProductionInfo; import net.sf.freecol.common.model.Specification; import net.sf.freecol.common.model.Tile; import net.sf.freecol.common.model.TileImprovement; import net.sf.freecol.common.model.TypeCountMap; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.Unit.UnitState; import net.sf.freecol.common.model.UnitType; import net.sf.freecol.common.model.WorkLocation; import net.sf.freecol.common.util.Utils; import net.sf.freecol.server.control.ChangeSet; import net.sf.freecol.server.control.ChangeSet.See; /** * The server version of a colony. */ public class ServerColony extends Colony implements ServerModelObject { private static final Logger logger = Logger.getLogger(ServerColony.class.getName()); // Temporary variable: private int lastVisited; /** * Trivial constructor required for all ServerModelObjects. */ public ServerColony(Game game, String id) { super(game, id); } /** * Creates a new ServerColony. * * @param game The <code>Game</code> in which this object belongs. * @param owner The <code>Player</code> owning this <code>Colony</code>. * @param name The name of the new <code>Colony</code>. * @param tile The location of the <code>Colony</code>. */ public ServerColony(Game game, Player owner, String name, Tile tile) { super(game, owner, name, tile); Specification spec = getSpecification(); goodsContainer = new GoodsContainer(game, this); goodsContainer.addPropertyChangeListener(this); sonsOfLiberty = 0; oldSonsOfLiberty = 0; established = game.getTurn(); tile.setOwner(owner); if (!tile.hasRoad()) { TileImprovement road = new TileImprovement(game, tile, spec.getTileImprovementType("model.improvement.road")); road.setTurnsToComplete(0); road.setVirtual(true); tile.add(road); } ColonyTile colonyTile = new ServerColonyTile(game, this, tile); colonyTiles.add(colonyTile); for (Tile t : tile.getSurroundingTiles(getRadius())) { colonyTiles.add(new ServerColonyTile(game, this, t)); if (t.getType().isWater()) { landLocked = false; } } // set up default production queues if (landLocked) { buildQueue.add(spec.getBuildingType("model.building.warehouse")); } else { buildQueue.add(spec.getBuildingType("model.building.docks")); getFeatureContainer().addAbility(HAS_PORT); } for (UnitType unitType : spec.getUnitTypesWithAbility("model.ability.bornInColony")) { if (!unitType.getGoodsRequired().isEmpty()) { populationQueue.add(unitType); } } Building building; List<BuildingType> buildingTypes = spec.getBuildingTypeList(); for (BuildingType buildingType : buildingTypes) { if (buildingType.isAutomaticBuild() || isAutomaticBuild(buildingType)) { building = new ServerBuilding(getGame(), this, buildingType); addBuilding(building); } } lastVisited = -1; } /** * New turn for this colony. * Try to find out if the colony is going to survive (last colonist does * not starve) before generating lots of production-related messages. * TODO: use the warehouse to store things? * * @param random A <code>Random</code> number source. * @param cs A <code>ChangeSet</code> to update. */ public void csNewTurn(Random random, ChangeSet cs) { logger.finest("ServerColony.csNewTurn, for " + toString()); ServerPlayer owner = (ServerPlayer) getOwner(); Specification spec = getSpecification(); boolean tileDirty = false; boolean colonyDirty = false; List<FreeColGameObject> updates = new ArrayList<FreeColGameObject>(); GoodsContainer container = getGoodsContainer(); container.saveState(); java.util.Map<Object, ProductionInfo> info = getProductionAndConsumption(); TypeCountMap<GoodsType> netProduction = new TypeCountMap<GoodsType>(); for (Entry<Object, ProductionInfo> entry : info.entrySet()) { ProductionInfo productionInfo = entry.getValue(); if (entry.getKey() instanceof WorkLocation) { WorkLocation workLocation = (WorkLocation) entry.getKey(); ((ServerModelObject) workLocation).csNewTurn(random, cs); if (workLocation.getUnitCount() > 0) { for (AbstractGoods goods : productionInfo.getProduction()) { int experience = goods.getAmount() / workLocation.getUnitCount(); for (Unit unit : workLocation.getUnitList()) { unit.setExperience(unit.getExperience() + experience); cs.addPartial(See.only(owner), unit, "experience"); } } } } else if (entry.getKey() instanceof BuildQueue && !productionInfo.getConsumption().isEmpty()) { // this means we are actually building something BuildQueue queue = (BuildQueue) entry.getKey(); BuildableType buildable = queue.getCurrentlyBuilding(); if (buildable instanceof UnitType) { tileDirty = buildUnit(queue, cs, random); } else if (buildable instanceof BuildingType) { colonyDirty = buildBuilding(queue, cs, updates); } else { throw new IllegalStateException("Bogus buildable: " + buildable); } // Having removed something from the build queue, nudge it again // to see if there is a problem with the next item if any. buildable = csGetBuildable(cs); } for (AbstractGoods goods : productionInfo.getProduction()) { netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount()); } for (AbstractGoods goods : productionInfo.getStorage()) { netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount()); } for (AbstractGoods goods : productionInfo.getConsumption()) { netProduction.incrementCount(goods.getType().getStoredAs(), -goods.getAmount()); } } // Apply the changes accumulated in the netProduction map for (Entry<GoodsType, Integer> entry : netProduction.getValues().entrySet()) { GoodsType goodsType = entry.getKey(); int net = entry.getValue(); int stored = getGoodsCount(goodsType); if (net + stored < 0) { removeGoods(goodsType, stored); } else { addGoods(goodsType, net); } } // Now check the food situation int storedFood = getGoodsCount(spec.getPrimaryFoodType()); - if (storedFood <= 0) { + if (storedFood < 0) { if (getUnitCount() > 1) { Unit victim = Utils.getRandomMember(logger, "Choose starver", getUnitList(), random); updates.add((FreeColGameObject) victim.getLocation()); cs.addDispose(owner, this, victim); cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.UNIT_LOST, "model.colony.colonistStarved", this) .addName("%colony%", getName())); } else { // Its dead, Jim. cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.UNIT_LOST, "model.colony.colonyStarved", this) .addName("%colony%", getName())); cs.addDispose(owner, getTile(), this); return; } } else { int netFood = netProduction.getCount(spec.getPrimaryFoodType()); int turns; if (netFood < 0 && (turns = storedFood / -netFood) <= 3) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WARNING, "model.colony.famineFeared", this) .addName("%colony%", getName()) .addName("%number%", String.valueOf(turns))); logger.finest("Famine feared in " + getName() + " food=" + storedFood + " production=" + netFood + " turns=" + turns); } } /** TODO: do we want this? if (goodsInput == 0 && !canAutoProduce() && getMaximumGoodsInput() > 0) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.MISSING_GOODS, "model.building.notEnoughInput", colony, goodsInputType) .add("%inputGoods%", goodsInputType.getNameKey()) .add("%building%", getNameKey()) .addName("%colony%", colony.getName())); } */ // Export goods if custom house is built. // Do not flush price changes yet, as any price change may change // yet again in csYearlyGoodsRemoval. if (hasAbility("model.ability.export")) { boolean gold = false; for (Goods goods : container.getCompactGoods()) { GoodsType type = goods.getType(); ExportData data = getExportData(type); if (data.isExported() && (owner.canTrade(goods, Market.Access.CUSTOM_HOUSE))) { int amount = goods.getAmount() - data.getExportLevel(); if (amount > 0) { owner.sell(container, type, amount, random); gold = true; } } } if (gold) { cs.addPartial(See.only(owner), owner, "gold"); } } // Throw away goods there is no room for, and warn about // levels that will be exceeded next turn int limit = getWarehouseCapacity(); int adjustment = limit / GoodsContainer.CARGO_SIZE; for (Goods goods : container.getCompactGoods()) { GoodsType type = goods.getType(); if (!type.isStorable()) continue; ExportData exportData = getExportData(type); int low = exportData.getLowLevel() * adjustment; int high = exportData.getHighLevel() * adjustment; int amount = goods.getAmount(); int oldAmount = container.getOldGoodsCount(type); if (amount < low && oldAmount >= low) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, "model.building.warehouseEmpty", this, type) .add("%goods%", type.getNameKey()) .addAmount("%level%", low) .addName("%colony%", getName())); continue; } if (type.limitIgnored()) continue; String messageId = null; int waste = 0; if (amount > limit) { // limit has been exceeded waste = amount - limit; container.removeGoods(type, waste); messageId = "model.building.warehouseWaste"; } else if (amount == limit && oldAmount < limit) { // limit has been reached during this turn messageId = "model.building.warehouseOverfull"; } else if (amount > high && oldAmount <= high) { // high-water-mark has been reached this turn messageId = "model.building.warehouseFull"; } if (messageId != null) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, messageId, this, type) .add("%goods%", type.getNameKey()) .addAmount("%waste%", waste) .addAmount("%level%", high) .addName("%colony%", getName())); } // No problem this turn, but what about the next? if (!(exportData.isExported() && hasAbility("model.ability.export") && owner.canTrade(type, Market.Access.CUSTOM_HOUSE)) && amount <= limit) { int loss = amount + netProduction.getCount(type) - limit; if (loss > 0) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, "model.building.warehouseSoonFull", this, type) .add("%goods%", goods.getNameKey()) .addName("%colony%", getName()) .addAmount("%amount%", loss)); } } } // Check for free buildings for (BuildingType buildingType : spec.getBuildingTypeList()) { if (isAutomaticBuild(buildingType)) { addBuilding(new ServerBuilding(getGame(), this, buildingType)); } } // Update SoL. updateSoL(); if (sonsOfLiberty / 10 != oldSonsOfLiberty / 10) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY, (sonsOfLiberty > oldSonsOfLiberty) ? "model.colony.SoLIncrease" : "model.colony.SoLDecrease", this, spec.getGoodsType("model.goods.bells")) .addAmount("%oldSoL%", oldSonsOfLiberty) .addAmount("%newSoL%", sonsOfLiberty) .addName("%colony%", getName())); ModelMessage govMgtMessage = checkForGovMgtChangeMessage(); if (govMgtMessage != null) { cs.addMessage(See.only(owner), govMgtMessage); } } updateProductionBonus(); // Try to update minimally. if (tileDirty) { cs.add(See.perhaps(), getTile()); } else { cs.add(See.only(owner), this); } } private boolean buildUnit(BuildQueue buildQueue, ChangeSet cs, Random random) { Unit unit = new ServerUnit(getGame(), getTile(), owner, (UnitType) buildQueue.getCurrentlyBuilding(), UnitState.ACTIVE); if (unit.hasAbility("model.ability.bornInColony")) { cs.addMessage(See.only((ServerPlayer) owner), new ModelMessage(ModelMessage.MessageType.UNIT_ADDED, "model.colony.newColonist", this, unit) .addName("%colony%", getName())); if (buildQueue.size() > 1) { Collections.shuffle(buildQueue.getValues(), random); } } else { cs.addMessage(See.only((ServerPlayer) owner), new ModelMessage(ModelMessage.MessageType.UNIT_ADDED, "model.colony.unitReady", this, unit) .addName("%colony%", getName()) .addStringTemplate("%unit%", unit.getLabel())); // Remove the unit-to-build unless it is the last entry. if (buildQueue.size() > 1) buildQueue.remove(0); } logger.info("New unit created in " + getName() + ": " + unit.toString()); return true; } private boolean buildBuilding(BuildQueue buildQueue, ChangeSet cs, List<FreeColGameObject> updates) { BuildingType type = (BuildingType) buildQueue.getCurrentlyBuilding(); BuildingType from = type.getUpgradesFrom(); boolean success; boolean colonyDirty = false; if (from == null) { addBuilding(new ServerBuilding(getGame(), this, type)); colonyDirty = true; success = true; } else { Building building = getBuilding(from); if (building.upgrade()) { updates.add(building); success = true; } else { cs.addMessage(See.only((ServerPlayer) owner), new ModelMessage(ModelMessage.MessageType.BUILDING_COMPLETED, "colonyPanel.unbuildable", this) .addName("%colony%", getName()) .add("%object%", type.getNameKey())); success = false; } } if (success) { tile.updatePlayerExploredTiles(); // See stockade changes cs.addMessage(See.only((ServerPlayer) owner), new ModelMessage(ModelMessage.MessageType.BUILDING_COMPLETED, "model.colony.buildingReady", this) .addName("%colony%", getName()) .add("%building%", type.getNameKey())); if (buildQueue.size() == 1) { cs.addMessage(See.only((ServerPlayer) owner), new ModelMessage(ModelMessage.MessageType.BUILDING_COMPLETED, "model.colony.notBuildingAnything", this) .addName("%colony%", getName()) .add("%building%", type.getNameKey())); } } buildQueue.remove(0); return colonyDirty; } /** * Gets what this colony really is building, removing anything that * is currently impossible. * * @param cs A <code>ChangeSet</code> to update. * @return A buildable that can be built, or null if nothing. */ private BuildableType csGetBuildable(ChangeSet cs) { ServerPlayer owner = (ServerPlayer) getOwner(); Specification spec = getSpecification(); while (!buildQueue.isEmpty()) { BuildableType buildable = buildQueue.getCurrentlyBuilding(); switch (getNoBuildReason(buildable)) { case NONE: return buildable; case NOT_BUILDING: for (GoodsType goodsType : spec.getGoodsTypeList()) { if (goodsType.isBuildingMaterial() && !goodsType.isStorable() && getProductionOf(goodsType) > 0) { // Production is idle cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WARNING, "model.colony.cannotBuild", this) .addName("%colony%", getName())); } } return null; case POPULATION_TOO_SMALL: cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WARNING, "model.colony.buildNeedPop", this) .addName("%colony%", getName()) .add("%building%", buildable.getNameKey())); break; default: // Are there other warnings to send? cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WARNING, "colonyPanel.unbuildable", this, buildable) .addName("%colony%", getName()) .add("%object%", buildable.getNameKey())); break; } buildQueue.remove(0); } return null; } /** * Are all the requirements to complete a buildable satisfied? * * @param buildable The <code>Buildable</code> to check. * @param cs A <code>ChangeSet</code> to update. */ private boolean csHasAllRequirements(BuildableType buildable, ChangeSet cs) { ServerPlayer owner = (ServerPlayer) getOwner(); GoodsContainer container = getGoodsContainer(); // Check availability of goods required for construction ArrayList<ModelMessage> messages = new ArrayList<ModelMessage>(); for (AbstractGoods required : buildable.getGoodsRequired()) { GoodsType type = required.getType(); int available = container.getGoodsCount(type); if (available < required.getAmount()) { if (type.isStorable()) { int need = required.getAmount() - available; messages.add(new ModelMessage(ModelMessage.MessageType.MISSING_GOODS, "model.colony.buildableNeedsGoods", this, type) .addName("%colony%", getName()) .add("%buildable%", buildable.getNameKey()) .addName("%amount%", String.valueOf(need)) .add("%goodsType%", type.getNameKey())); } else { // Not complete due to missing unstorable goods // (probably hammers) so there is no point griping. return false; } } } if (!messages.isEmpty()) { // Not complete due to missing storable goods. // Gripe away. for (ModelMessage message : messages) { cs.addMessage(See.only(owner), message); } return false; } return true; } /** * Returns the tag name of the root element representing this object. * * @return "serverColony" */ public String getServerXMLElementTagName() { return "serverColony"; } }
true
true
public void csNewTurn(Random random, ChangeSet cs) { logger.finest("ServerColony.csNewTurn, for " + toString()); ServerPlayer owner = (ServerPlayer) getOwner(); Specification spec = getSpecification(); boolean tileDirty = false; boolean colonyDirty = false; List<FreeColGameObject> updates = new ArrayList<FreeColGameObject>(); GoodsContainer container = getGoodsContainer(); container.saveState(); java.util.Map<Object, ProductionInfo> info = getProductionAndConsumption(); TypeCountMap<GoodsType> netProduction = new TypeCountMap<GoodsType>(); for (Entry<Object, ProductionInfo> entry : info.entrySet()) { ProductionInfo productionInfo = entry.getValue(); if (entry.getKey() instanceof WorkLocation) { WorkLocation workLocation = (WorkLocation) entry.getKey(); ((ServerModelObject) workLocation).csNewTurn(random, cs); if (workLocation.getUnitCount() > 0) { for (AbstractGoods goods : productionInfo.getProduction()) { int experience = goods.getAmount() / workLocation.getUnitCount(); for (Unit unit : workLocation.getUnitList()) { unit.setExperience(unit.getExperience() + experience); cs.addPartial(See.only(owner), unit, "experience"); } } } } else if (entry.getKey() instanceof BuildQueue && !productionInfo.getConsumption().isEmpty()) { // this means we are actually building something BuildQueue queue = (BuildQueue) entry.getKey(); BuildableType buildable = queue.getCurrentlyBuilding(); if (buildable instanceof UnitType) { tileDirty = buildUnit(queue, cs, random); } else if (buildable instanceof BuildingType) { colonyDirty = buildBuilding(queue, cs, updates); } else { throw new IllegalStateException("Bogus buildable: " + buildable); } // Having removed something from the build queue, nudge it again // to see if there is a problem with the next item if any. buildable = csGetBuildable(cs); } for (AbstractGoods goods : productionInfo.getProduction()) { netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount()); } for (AbstractGoods goods : productionInfo.getStorage()) { netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount()); } for (AbstractGoods goods : productionInfo.getConsumption()) { netProduction.incrementCount(goods.getType().getStoredAs(), -goods.getAmount()); } } // Apply the changes accumulated in the netProduction map for (Entry<GoodsType, Integer> entry : netProduction.getValues().entrySet()) { GoodsType goodsType = entry.getKey(); int net = entry.getValue(); int stored = getGoodsCount(goodsType); if (net + stored < 0) { removeGoods(goodsType, stored); } else { addGoods(goodsType, net); } } // Now check the food situation int storedFood = getGoodsCount(spec.getPrimaryFoodType()); if (storedFood <= 0) { if (getUnitCount() > 1) { Unit victim = Utils.getRandomMember(logger, "Choose starver", getUnitList(), random); updates.add((FreeColGameObject) victim.getLocation()); cs.addDispose(owner, this, victim); cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.UNIT_LOST, "model.colony.colonistStarved", this) .addName("%colony%", getName())); } else { // Its dead, Jim. cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.UNIT_LOST, "model.colony.colonyStarved", this) .addName("%colony%", getName())); cs.addDispose(owner, getTile(), this); return; } } else { int netFood = netProduction.getCount(spec.getPrimaryFoodType()); int turns; if (netFood < 0 && (turns = storedFood / -netFood) <= 3) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WARNING, "model.colony.famineFeared", this) .addName("%colony%", getName()) .addName("%number%", String.valueOf(turns))); logger.finest("Famine feared in " + getName() + " food=" + storedFood + " production=" + netFood + " turns=" + turns); } } /** TODO: do we want this? if (goodsInput == 0 && !canAutoProduce() && getMaximumGoodsInput() > 0) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.MISSING_GOODS, "model.building.notEnoughInput", colony, goodsInputType) .add("%inputGoods%", goodsInputType.getNameKey()) .add("%building%", getNameKey()) .addName("%colony%", colony.getName())); } */ // Export goods if custom house is built. // Do not flush price changes yet, as any price change may change // yet again in csYearlyGoodsRemoval. if (hasAbility("model.ability.export")) { boolean gold = false; for (Goods goods : container.getCompactGoods()) { GoodsType type = goods.getType(); ExportData data = getExportData(type); if (data.isExported() && (owner.canTrade(goods, Market.Access.CUSTOM_HOUSE))) { int amount = goods.getAmount() - data.getExportLevel(); if (amount > 0) { owner.sell(container, type, amount, random); gold = true; } } } if (gold) { cs.addPartial(See.only(owner), owner, "gold"); } } // Throw away goods there is no room for, and warn about // levels that will be exceeded next turn int limit = getWarehouseCapacity(); int adjustment = limit / GoodsContainer.CARGO_SIZE; for (Goods goods : container.getCompactGoods()) { GoodsType type = goods.getType(); if (!type.isStorable()) continue; ExportData exportData = getExportData(type); int low = exportData.getLowLevel() * adjustment; int high = exportData.getHighLevel() * adjustment; int amount = goods.getAmount(); int oldAmount = container.getOldGoodsCount(type); if (amount < low && oldAmount >= low) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, "model.building.warehouseEmpty", this, type) .add("%goods%", type.getNameKey()) .addAmount("%level%", low) .addName("%colony%", getName())); continue; } if (type.limitIgnored()) continue; String messageId = null; int waste = 0; if (amount > limit) { // limit has been exceeded waste = amount - limit; container.removeGoods(type, waste); messageId = "model.building.warehouseWaste"; } else if (amount == limit && oldAmount < limit) { // limit has been reached during this turn messageId = "model.building.warehouseOverfull"; } else if (amount > high && oldAmount <= high) { // high-water-mark has been reached this turn messageId = "model.building.warehouseFull"; } if (messageId != null) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, messageId, this, type) .add("%goods%", type.getNameKey()) .addAmount("%waste%", waste) .addAmount("%level%", high) .addName("%colony%", getName())); } // No problem this turn, but what about the next? if (!(exportData.isExported() && hasAbility("model.ability.export") && owner.canTrade(type, Market.Access.CUSTOM_HOUSE)) && amount <= limit) { int loss = amount + netProduction.getCount(type) - limit; if (loss > 0) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, "model.building.warehouseSoonFull", this, type) .add("%goods%", goods.getNameKey()) .addName("%colony%", getName()) .addAmount("%amount%", loss)); } } } // Check for free buildings for (BuildingType buildingType : spec.getBuildingTypeList()) { if (isAutomaticBuild(buildingType)) { addBuilding(new ServerBuilding(getGame(), this, buildingType)); } } // Update SoL. updateSoL(); if (sonsOfLiberty / 10 != oldSonsOfLiberty / 10) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY, (sonsOfLiberty > oldSonsOfLiberty) ? "model.colony.SoLIncrease" : "model.colony.SoLDecrease", this, spec.getGoodsType("model.goods.bells")) .addAmount("%oldSoL%", oldSonsOfLiberty) .addAmount("%newSoL%", sonsOfLiberty) .addName("%colony%", getName())); ModelMessage govMgtMessage = checkForGovMgtChangeMessage(); if (govMgtMessage != null) { cs.addMessage(See.only(owner), govMgtMessage); } } updateProductionBonus(); // Try to update minimally. if (tileDirty) { cs.add(See.perhaps(), getTile()); } else { cs.add(See.only(owner), this); } }
public void csNewTurn(Random random, ChangeSet cs) { logger.finest("ServerColony.csNewTurn, for " + toString()); ServerPlayer owner = (ServerPlayer) getOwner(); Specification spec = getSpecification(); boolean tileDirty = false; boolean colonyDirty = false; List<FreeColGameObject> updates = new ArrayList<FreeColGameObject>(); GoodsContainer container = getGoodsContainer(); container.saveState(); java.util.Map<Object, ProductionInfo> info = getProductionAndConsumption(); TypeCountMap<GoodsType> netProduction = new TypeCountMap<GoodsType>(); for (Entry<Object, ProductionInfo> entry : info.entrySet()) { ProductionInfo productionInfo = entry.getValue(); if (entry.getKey() instanceof WorkLocation) { WorkLocation workLocation = (WorkLocation) entry.getKey(); ((ServerModelObject) workLocation).csNewTurn(random, cs); if (workLocation.getUnitCount() > 0) { for (AbstractGoods goods : productionInfo.getProduction()) { int experience = goods.getAmount() / workLocation.getUnitCount(); for (Unit unit : workLocation.getUnitList()) { unit.setExperience(unit.getExperience() + experience); cs.addPartial(See.only(owner), unit, "experience"); } } } } else if (entry.getKey() instanceof BuildQueue && !productionInfo.getConsumption().isEmpty()) { // this means we are actually building something BuildQueue queue = (BuildQueue) entry.getKey(); BuildableType buildable = queue.getCurrentlyBuilding(); if (buildable instanceof UnitType) { tileDirty = buildUnit(queue, cs, random); } else if (buildable instanceof BuildingType) { colonyDirty = buildBuilding(queue, cs, updates); } else { throw new IllegalStateException("Bogus buildable: " + buildable); } // Having removed something from the build queue, nudge it again // to see if there is a problem with the next item if any. buildable = csGetBuildable(cs); } for (AbstractGoods goods : productionInfo.getProduction()) { netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount()); } for (AbstractGoods goods : productionInfo.getStorage()) { netProduction.incrementCount(goods.getType().getStoredAs(), goods.getAmount()); } for (AbstractGoods goods : productionInfo.getConsumption()) { netProduction.incrementCount(goods.getType().getStoredAs(), -goods.getAmount()); } } // Apply the changes accumulated in the netProduction map for (Entry<GoodsType, Integer> entry : netProduction.getValues().entrySet()) { GoodsType goodsType = entry.getKey(); int net = entry.getValue(); int stored = getGoodsCount(goodsType); if (net + stored < 0) { removeGoods(goodsType, stored); } else { addGoods(goodsType, net); } } // Now check the food situation int storedFood = getGoodsCount(spec.getPrimaryFoodType()); if (storedFood < 0) { if (getUnitCount() > 1) { Unit victim = Utils.getRandomMember(logger, "Choose starver", getUnitList(), random); updates.add((FreeColGameObject) victim.getLocation()); cs.addDispose(owner, this, victim); cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.UNIT_LOST, "model.colony.colonistStarved", this) .addName("%colony%", getName())); } else { // Its dead, Jim. cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.UNIT_LOST, "model.colony.colonyStarved", this) .addName("%colony%", getName())); cs.addDispose(owner, getTile(), this); return; } } else { int netFood = netProduction.getCount(spec.getPrimaryFoodType()); int turns; if (netFood < 0 && (turns = storedFood / -netFood) <= 3) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WARNING, "model.colony.famineFeared", this) .addName("%colony%", getName()) .addName("%number%", String.valueOf(turns))); logger.finest("Famine feared in " + getName() + " food=" + storedFood + " production=" + netFood + " turns=" + turns); } } /** TODO: do we want this? if (goodsInput == 0 && !canAutoProduce() && getMaximumGoodsInput() > 0) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.MISSING_GOODS, "model.building.notEnoughInput", colony, goodsInputType) .add("%inputGoods%", goodsInputType.getNameKey()) .add("%building%", getNameKey()) .addName("%colony%", colony.getName())); } */ // Export goods if custom house is built. // Do not flush price changes yet, as any price change may change // yet again in csYearlyGoodsRemoval. if (hasAbility("model.ability.export")) { boolean gold = false; for (Goods goods : container.getCompactGoods()) { GoodsType type = goods.getType(); ExportData data = getExportData(type); if (data.isExported() && (owner.canTrade(goods, Market.Access.CUSTOM_HOUSE))) { int amount = goods.getAmount() - data.getExportLevel(); if (amount > 0) { owner.sell(container, type, amount, random); gold = true; } } } if (gold) { cs.addPartial(See.only(owner), owner, "gold"); } } // Throw away goods there is no room for, and warn about // levels that will be exceeded next turn int limit = getWarehouseCapacity(); int adjustment = limit / GoodsContainer.CARGO_SIZE; for (Goods goods : container.getCompactGoods()) { GoodsType type = goods.getType(); if (!type.isStorable()) continue; ExportData exportData = getExportData(type); int low = exportData.getLowLevel() * adjustment; int high = exportData.getHighLevel() * adjustment; int amount = goods.getAmount(); int oldAmount = container.getOldGoodsCount(type); if (amount < low && oldAmount >= low) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, "model.building.warehouseEmpty", this, type) .add("%goods%", type.getNameKey()) .addAmount("%level%", low) .addName("%colony%", getName())); continue; } if (type.limitIgnored()) continue; String messageId = null; int waste = 0; if (amount > limit) { // limit has been exceeded waste = amount - limit; container.removeGoods(type, waste); messageId = "model.building.warehouseWaste"; } else if (amount == limit && oldAmount < limit) { // limit has been reached during this turn messageId = "model.building.warehouseOverfull"; } else if (amount > high && oldAmount <= high) { // high-water-mark has been reached this turn messageId = "model.building.warehouseFull"; } if (messageId != null) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, messageId, this, type) .add("%goods%", type.getNameKey()) .addAmount("%waste%", waste) .addAmount("%level%", high) .addName("%colony%", getName())); } // No problem this turn, but what about the next? if (!(exportData.isExported() && hasAbility("model.ability.export") && owner.canTrade(type, Market.Access.CUSTOM_HOUSE)) && amount <= limit) { int loss = amount + netProduction.getCount(type) - limit; if (loss > 0) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.WAREHOUSE_CAPACITY, "model.building.warehouseSoonFull", this, type) .add("%goods%", goods.getNameKey()) .addName("%colony%", getName()) .addAmount("%amount%", loss)); } } } // Check for free buildings for (BuildingType buildingType : spec.getBuildingTypeList()) { if (isAutomaticBuild(buildingType)) { addBuilding(new ServerBuilding(getGame(), this, buildingType)); } } // Update SoL. updateSoL(); if (sonsOfLiberty / 10 != oldSonsOfLiberty / 10) { cs.addMessage(See.only(owner), new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY, (sonsOfLiberty > oldSonsOfLiberty) ? "model.colony.SoLIncrease" : "model.colony.SoLDecrease", this, spec.getGoodsType("model.goods.bells")) .addAmount("%oldSoL%", oldSonsOfLiberty) .addAmount("%newSoL%", sonsOfLiberty) .addName("%colony%", getName())); ModelMessage govMgtMessage = checkForGovMgtChangeMessage(); if (govMgtMessage != null) { cs.addMessage(See.only(owner), govMgtMessage); } } updateProductionBonus(); // Try to update minimally. if (tileDirty) { cs.add(See.perhaps(), getTile()); } else { cs.add(See.only(owner), this); } }
diff --git a/src/com/dmdirc/addons/ui_web/uicomponents/WebWindow.java b/src/com/dmdirc/addons/ui_web/uicomponents/WebWindow.java index e8a79e91..25fca2af 100644 --- a/src/com/dmdirc/addons/ui_web/uicomponents/WebWindow.java +++ b/src/com/dmdirc/addons/ui_web/uicomponents/WebWindow.java @@ -1,282 +1,282 @@ /* * Copyright (c) 2006-2012 DMDirc Developers * * 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.dmdirc.addons.ui_web.uicomponents; import com.dmdirc.FrameContainer; import com.dmdirc.addons.ui_web.DynamicRequestHandler; import com.dmdirc.addons.ui_web.Event; import com.dmdirc.addons.ui_web.Message; import com.dmdirc.addons.ui_web.WebInterfaceUI; import com.dmdirc.interfaces.FrameCloseListener; import com.dmdirc.interfaces.FrameInfoListener; import com.dmdirc.interfaces.ui.UIController; import com.dmdirc.interfaces.ui.Window; import com.dmdirc.ui.messages.IRCDocumentListener; import com.dmdirc.ui.messages.IRCTextAttribute; import com.dmdirc.ui.messages.Styliser; import java.awt.Color; import java.awt.font.TextAttribute; import java.text.AttributedCharacterIterator; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringEscapeUtils; /** * A server-side representation of a "window" in the Web UI. */ public class WebWindow implements Window, IRCDocumentListener, FrameInfoListener, FrameCloseListener { /** The unique ID of this window, used by clients to address the window. */ private final String id; /** The container that this window corresponds to. */ private final FrameContainer parent; /** The handler to pass global events to. */ private final DynamicRequestHandler handler; /** The controller that owns this window. */ private final WebInterfaceUI controller; public WebWindow(final WebInterfaceUI controller, final FrameContainer parent, final String id) { super(); this.id = id; this.parent = parent; this.controller = controller; this.handler = controller.getHandler(); parent.getDocument().addIRCDocumentListener(this); parent.addFrameInfoListener(this); if (parent.getParent() == null) { handler.addEvent(new Event("newwindow", this)); } else { handler.addEvent(new Event("newchildwindow", new Object[]{controller.getWindowManager().getWindow( parent.getParent()), this})); } } public List<String> getMessages() { final List<String> messages = new ArrayList<String>(getContainer() .getDocument().getNumLines()); for (int i = 0; i < getContainer().getDocument().getNumLines(); i++) { messages.add(style(getContainer().getDocument().getStyledLine(i))); } return messages; } /** {@inheritDoc} */ @Override public FrameContainer getContainer() { return parent; } public String getId() { return id; } protected String style(final AttributedCharacterIterator aci) { final StringBuilder builder = new StringBuilder(); Map<AttributedCharacterIterator.Attribute, Object> map = null; char chr = aci.current(); while (aci.getIndex() < aci.getEndIndex()) { if (!aci.getAttributes().equals(map)) { style(aci.getAttributes(), builder); map = aci.getAttributes(); } builder.append(StringEscapeUtils.escapeHtml(String.valueOf(chr))); chr = aci.next(); } return builder.toString(); } protected static void style( final Map<AttributedCharacterIterator.Attribute, Object> map, final StringBuilder builder) { if (builder.length() > 0) { builder.append("</span>"); } String link = null; builder.append("<span style=\""); for (Map.Entry<AttributedCharacterIterator.Attribute, Object> entry : map.entrySet()) { if (entry.getKey().equals(TextAttribute.FOREGROUND)) { builder.append("color: "); builder.append(toColour(entry.getValue())); builder.append("; "); } else if (entry.getKey().equals(TextAttribute.BACKGROUND)) { builder.append("background-color: "); builder.append(toColour(entry.getValue())); builder.append("; "); } else if (entry.getKey().equals(TextAttribute.WEIGHT)) { builder.append("font-weight: bold; "); - } else if (entry.getKey().equals(TextAttribute.FAMILY)) { + } else if (entry.getKey().equals(TextAttribute.FAMILY) && "monospaced".equals(entry.getValue())) { builder.append("font-family: monospace; "); } else if (entry.getKey().equals(TextAttribute.POSTURE)) { builder.append("font-style: italic; "); } else if (entry.getKey().equals(TextAttribute.UNDERLINE)) { builder.append("text-decoration: underline; "); } else if (entry.getKey().equals(IRCTextAttribute.HYPERLINK)) { builder.append("cursor: pointer; "); link = "link_hyperlink('" + StringEscapeUtils.escapeHtml(StringEscapeUtils .escapeJavaScript((String) entry.getValue())) + "');"; } else if (entry.getKey().equals(IRCTextAttribute.CHANNEL)) { builder.append("cursor: pointer; "); link = "link_channel('" + StringEscapeUtils.escapeHtml( StringEscapeUtils.escapeJavaScript( (String) entry.getValue())) + "');"; } else if (entry.getKey().equals(IRCTextAttribute.NICKNAME)) { builder.append("cursor: pointer; "); link = "link_query('" + StringEscapeUtils.escapeHtml( StringEscapeUtils.escapeJavaScript( (String) entry.getValue())) + "');"; } } builder.append('"'); if (link != null) { builder.append(" onClick=\""); builder.append(link); builder.append('"'); } builder.append('>'); } protected static String toColour(final Object object) { final Color colour = (Color) object; return "rgb(" + colour.getRed() + ", " + colour.getGreen() + ", " + colour.getBlue() + ")"; } /** {@inheritDoc} */ @Override public UIController getController() { return controller; } /** {@inheritDoc} */ @Override public void linesAdded(final int line, final int length, final int size) { for (int i = 0; i < length; i++) { handler.addEvent(new Event("lineadded", new Message( style(parent.getDocument().getStyledLine(line)), this))); } } /** {@inheritDoc} */ @Override public void trimmed(final int newSize, final int numTrimmed) { //TODO FIXME } /** {@inheritDoc} */ @Override public void cleared() { //TODO FIXME } /** {@inheritDoc} */ @Override public void repaintNeeded() { //TODO FIXME } /** {@inheritDoc} */ @Override public void iconChanged(final FrameContainer window, final String icon) { //TODO FIXME } /** {@inheritDoc} */ @Override public void nameChanged(final FrameContainer window, final String name) { //TODO FIXME } /** {@inheritDoc} */ @Override public void titleChanged(final FrameContainer window, final String title) { //TODO FIXME } /** {@inheritDoc} */ @Override public void windowClosing(final FrameContainer window) { handler.addEvent(new Event("closewindow", id)); } /** * Retrieves the title of this window. * * @return This window's title */ public String getTitle() { return Styliser.stipControlCodes(parent.getTitle()); } /** * Retrieves the name of this window. * * @return This window's name */ public String getName() { return Styliser.stipControlCodes(parent.getName()); } /** * Retrieves the type of this window. * * @return This window's type */ public String getType() { // TODO: Pass icon properly instead of relying on type return parent.getClass().getSimpleName().toLowerCase(); } }
true
true
protected static void style( final Map<AttributedCharacterIterator.Attribute, Object> map, final StringBuilder builder) { if (builder.length() > 0) { builder.append("</span>"); } String link = null; builder.append("<span style=\""); for (Map.Entry<AttributedCharacterIterator.Attribute, Object> entry : map.entrySet()) { if (entry.getKey().equals(TextAttribute.FOREGROUND)) { builder.append("color: "); builder.append(toColour(entry.getValue())); builder.append("; "); } else if (entry.getKey().equals(TextAttribute.BACKGROUND)) { builder.append("background-color: "); builder.append(toColour(entry.getValue())); builder.append("; "); } else if (entry.getKey().equals(TextAttribute.WEIGHT)) { builder.append("font-weight: bold; "); } else if (entry.getKey().equals(TextAttribute.FAMILY)) { builder.append("font-family: monospace; "); } else if (entry.getKey().equals(TextAttribute.POSTURE)) { builder.append("font-style: italic; "); } else if (entry.getKey().equals(TextAttribute.UNDERLINE)) { builder.append("text-decoration: underline; "); } else if (entry.getKey().equals(IRCTextAttribute.HYPERLINK)) { builder.append("cursor: pointer; "); link = "link_hyperlink('" + StringEscapeUtils.escapeHtml(StringEscapeUtils .escapeJavaScript((String) entry.getValue())) + "');"; } else if (entry.getKey().equals(IRCTextAttribute.CHANNEL)) { builder.append("cursor: pointer; "); link = "link_channel('" + StringEscapeUtils.escapeHtml( StringEscapeUtils.escapeJavaScript( (String) entry.getValue())) + "');"; } else if (entry.getKey().equals(IRCTextAttribute.NICKNAME)) { builder.append("cursor: pointer; "); link = "link_query('" + StringEscapeUtils.escapeHtml( StringEscapeUtils.escapeJavaScript( (String) entry.getValue())) + "');"; } } builder.append('"'); if (link != null) { builder.append(" onClick=\""); builder.append(link); builder.append('"'); } builder.append('>'); }
protected static void style( final Map<AttributedCharacterIterator.Attribute, Object> map, final StringBuilder builder) { if (builder.length() > 0) { builder.append("</span>"); } String link = null; builder.append("<span style=\""); for (Map.Entry<AttributedCharacterIterator.Attribute, Object> entry : map.entrySet()) { if (entry.getKey().equals(TextAttribute.FOREGROUND)) { builder.append("color: "); builder.append(toColour(entry.getValue())); builder.append("; "); } else if (entry.getKey().equals(TextAttribute.BACKGROUND)) { builder.append("background-color: "); builder.append(toColour(entry.getValue())); builder.append("; "); } else if (entry.getKey().equals(TextAttribute.WEIGHT)) { builder.append("font-weight: bold; "); } else if (entry.getKey().equals(TextAttribute.FAMILY) && "monospaced".equals(entry.getValue())) { builder.append("font-family: monospace; "); } else if (entry.getKey().equals(TextAttribute.POSTURE)) { builder.append("font-style: italic; "); } else if (entry.getKey().equals(TextAttribute.UNDERLINE)) { builder.append("text-decoration: underline; "); } else if (entry.getKey().equals(IRCTextAttribute.HYPERLINK)) { builder.append("cursor: pointer; "); link = "link_hyperlink('" + StringEscapeUtils.escapeHtml(StringEscapeUtils .escapeJavaScript((String) entry.getValue())) + "');"; } else if (entry.getKey().equals(IRCTextAttribute.CHANNEL)) { builder.append("cursor: pointer; "); link = "link_channel('" + StringEscapeUtils.escapeHtml( StringEscapeUtils.escapeJavaScript( (String) entry.getValue())) + "');"; } else if (entry.getKey().equals(IRCTextAttribute.NICKNAME)) { builder.append("cursor: pointer; "); link = "link_query('" + StringEscapeUtils.escapeHtml( StringEscapeUtils.escapeJavaScript( (String) entry.getValue())) + "');"; } } builder.append('"'); if (link != null) { builder.append(" onClick=\""); builder.append(link); builder.append('"'); } builder.append('>'); }
diff --git a/grails/src/persistence/grails/orm/HibernateCriteriaBuilder.java b/grails/src/persistence/grails/orm/HibernateCriteriaBuilder.java index 4cf8d7d90..94392d295 100644 --- a/grails/src/persistence/grails/orm/HibernateCriteriaBuilder.java +++ b/grails/src/persistence/grails/orm/HibernateCriteriaBuilder.java @@ -1,1213 +1,1213 @@ /* * Copyright 2004-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package grails.orm; import groovy.lang.*; import org.codehaus.groovy.grails.commons.GrailsClassUtils; import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil; import org.hibernate.*; import org.hibernate.criterion.*; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.metadata.ClassMetadata; import org.hibernate.transform.ResultTransformer; import org.hibernate.type.AssociationType; import org.hibernate.type.Type; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.orm.hibernate3.SessionHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; import java.util.*; /** * <p>Wraps the Hibernate Criteria API in a builder. The builder can be retrieved through the "createCriteria()" dynamic static * method of Grails domain classes (Example in Groovy): * * <pre> * def c = Account.createCriteria() * def results = c { * projections { * groupProperty("branch") * } * like("holderFirstName", "Fred%") * and { * between("balance", 500, 1000) * eq("branch", "London") * } * maxResults(10) * order("holderLastName", "desc") * } * </pre> * * <p>The builder can also be instantiated standalone with a SessionFactory and persistent Class instance: * * <pre> * new HibernateCriteriaBuilder(clazz, sessionFactory).list { * eq("firstName", "Fred") * } * </pre> * * @author Graeme Rocher * @since Oct 10, 2005 */ public class HibernateCriteriaBuilder extends GroovyObjectSupport { public static final String AND = "and"; // builder public static final String IS_NULL = "isNull"; // builder public static final String IS_NOT_NULL = "isNotNull"; // builder public static final String NOT = "not";// builder public static final String OR = "or"; // builder public static final String ID_EQUALS = "idEq"; // builder public static final String IS_EMPTY = "isEmpty"; //builder public static final String IS_NOT_EMPTY = "isNotEmpty"; //builder public static final String RLIKE = "rlike";//method public static final String BETWEEN = "between";//method public static final String EQUALS = "eq";//method public static final String EQUALS_PROPERTY = "eqProperty";//method public static final String GREATER_THAN = "gt";//method public static final String GREATER_THAN_PROPERTY = "gtProperty";//method public static final String GREATER_THAN_OR_EQUAL = "ge";//method public static final String GREATER_THAN_OR_EQUAL_PROPERTY = "geProperty";//method public static final String ILIKE = "ilike";//method public static final String IN = "in";//method public static final String LESS_THAN = "lt"; //method public static final String LESS_THAN_PROPERTY = "ltProperty";//method public static final String LESS_THAN_OR_EQUAL = "le";//method public static final String LESS_THAN_OR_EQUAL_PROPERTY = "leProperty";//method public static final String LIKE = "like";//method public static final String NOT_EQUAL = "ne";//method public static final String NOT_EQUAL_PROPERTY = "neProperty";//method public static final String SIZE_EQUALS = "sizeEq"; //method public static final String ORDER_DESCENDING = "desc"; public static final String ORDER_ASCENDING = "asc"; private static final String ROOT_DO_CALL = "doCall"; private static final String ROOT_CALL = "call"; private static final String LIST_CALL = "list"; private static final String LIST_DISTINCT_CALL = "listDistinct"; private static final String COUNT_CALL = "count"; private static final String GET_CALL = "get"; private static final String SCROLL_CALL = "scroll"; private static final String PROJECTIONS = "projections"; private SessionFactory sessionFactory; private Session hibernateSession; private Class targetClass; private Criteria criteria; private MetaClass criteriaMetaClass; private boolean uniqueResult = false; private List<LogicalExpression> logicalExpressionStack = new ArrayList<LogicalExpression>(); private List<String> associationStack = new ArrayList<String>(); private boolean participate; private boolean scroll; private boolean count; private ProjectionList projectionList; private BeanWrapper targetBean; private List<String> aliasStack = new ArrayList<String>(); private List<Criteria> aliasInstanceStack = new ArrayList<Criteria>(); private Map<String, String> aliasMap = new HashMap<String, String>(); private static final String ALIAS = "_alias"; private ResultTransformer resultTransformer; private int aliasCount; public HibernateCriteriaBuilder(Class targetClass, SessionFactory sessionFactory) { super(); this.targetClass = targetClass; this.targetBean = new BeanWrapperImpl(BeanUtils.instantiateClass(targetClass)); this.sessionFactory = sessionFactory; } public HibernateCriteriaBuilder(Class targetClass, SessionFactory sessionFactory, boolean uniqueResult) { super(); this.targetClass = targetClass; this.sessionFactory = sessionFactory; this.uniqueResult = uniqueResult; } /** * Returns the criteria instance * @return The criteria instance */ public Criteria getInstance() { return criteria; } /** * Set whether a unique result should be returned * @param uniqueResult True if a unique result should be returned */ public void setUniqueResult(boolean uniqueResult) { this.uniqueResult = uniqueResult; } /** * A projection that selects a property name * @param propertyName The name of the property */ public void property(String propertyName) { if(this.projectionList == null) { throwRuntimeException( new IllegalArgumentException("call to [property] must be within a [projections] node")); } else { this.projectionList.add(Projections.property(calculatePropertyName(propertyName))); } } /** * A projection that selects a distince property name * @param propertyName The property name */ public void distinct(String propertyName) { if(this.projectionList == null) { throwRuntimeException( new IllegalArgumentException("call to [distinct] must be within a [projections] node")); } else { this.projectionList.add(Projections.distinct(Projections.property(calculatePropertyName(propertyName)))); } } /** * A distinct projection that takes a list * * @param propertyNames The list of distince property names */ public void distinct(Collection propertyNames) { if(this.projectionList == null) { throwRuntimeException( new IllegalArgumentException("call to [distinct] must be within a [projections] node")); } else { ProjectionList list = Projections.projectionList(); for (Iterator i = propertyNames.iterator(); i.hasNext();) { Object o = i.next(); list.add(Projections.property(calculatePropertyName(o.toString()))); } this.projectionList.add(Projections.distinct(list)); } } /** * Adds a projection that allows the criteria to return the property average value * * @param propertyName The name of the property */ public void avg(String propertyName) { if(this.projectionList == null) { throwRuntimeException( new IllegalArgumentException("call to [avg] must be within a [projections] node")); } else { this.projectionList.add(Projections.avg(calculatePropertyName(propertyName))); } } /** * Use a join query * * @param associationPath The path of the association */ public void join(String associationPath) { this.criteria.setFetchMode(calculatePropertyName(associationPath),FetchMode.JOIN); } /** * Whether a pessimisick lock should be obtained * * @param shouldLock True if it should */ public void lock(boolean shouldLock) { String lastAlias = getLastAlias(); if(shouldLock) { if(lastAlias != null) { this.criteria.setLockMode(lastAlias, LockMode.UPGRADE); } else { this.criteria.setLockMode(LockMode.UPGRADE); } } else { if(lastAlias != null) { this.criteria.setLockMode(lastAlias, LockMode.NONE); } else { this.criteria.setLockMode(LockMode.NONE); } } } /** * Use a select query * * @param associationPath The path of the association */ public void select(String associationPath) { this.criteria.setFetchMode(calculatePropertyName(associationPath),FetchMode.SELECT); } /** * Whether to use the query cache * @param shouldCache True if the query should be cached */ public void cache(boolean shouldCache) { this.criteria.setCacheable(shouldCache); } /** * Calculates the property name including any alias paths * * @param propertyName The property name * @return The calculated property name */ private String calculatePropertyName(String propertyName) { String lastAlias = getLastAlias(); if(lastAlias != null) return lastAlias +'.'+propertyName; else return propertyName; } private String getLastAlias() { if(this.aliasStack.size()>0) { return this.aliasStack.get(this.aliasStack.size()-1).toString(); } return null; } /** * Calculates the property value, converting GStrings if necessary * * @param propertyValue The property value * @return The calculated property value */ private Object calculatePropertyValue(Object propertyValue) { if(propertyValue instanceof GString) { return propertyValue.toString(); } return propertyValue; } /** * Adds a projection that allows the criteria to return the property count * * @param propertyName The name of the property */ public void count(String propertyName) { if(this.projectionList == null) { throwRuntimeException( new IllegalArgumentException("call to [count] must be within a [projections] node")); } else { this.projectionList.add(Projections.count(calculatePropertyName(propertyName))); } } /** * Adds a projection that allows the criteria to return the distinct property count * * @param propertyName The name of the property */ public void countDistinct(String propertyName) { if(this.projectionList == null) { throwRuntimeException( new IllegalArgumentException("call to [countDistinct] must be within a [projections] node")); } else { this.projectionList.add(Projections.countDistinct(calculatePropertyName(propertyName))); } } /** * Adds a projection that allows the criteria's result to be grouped by a property * * @param propertyName The name of the property */ public void groupProperty(String propertyName) { if(this.projectionList == null) { throwRuntimeException( new IllegalArgumentException("call to [groupProperty] must be within a [projections] node")); } else { this.projectionList.add(Projections.groupProperty(calculatePropertyName(propertyName))); } } /** * Adds a projection that allows the criteria to retrieve a maximum property value * * @param propertyName The name of the property */ public void max(String propertyName) { if(this.projectionList == null) { throwRuntimeException( new IllegalArgumentException("call to [max] must be within a [projections] node")); } else { this.projectionList.add(Projections.max(calculatePropertyName(propertyName))); } } /** * Adds a projection that allows the criteria to retrieve a minimum property value * * @param propertyName The name of the property */ public void min(String propertyName) { if(this.projectionList == null) { throwRuntimeException( new IllegalArgumentException("call to [min] must be within a [projections] node")); } else { this.projectionList.add(Projections.min(calculatePropertyName(propertyName))); } } /** * Adds a projection that allows the criteria to return the row count * */ public void rowCount() { if(this.projectionList == null) { throwRuntimeException( new IllegalArgumentException("call to [rowCount] must be within a [projections] node")); } else { this.projectionList.add(Projections.rowCount()); } } /** * Adds a projection that allows the criteria to retrieve the sum of the results of a property * * @param propertyName The name of the property */ public void sum(String propertyName) { if(this.projectionList == null) { throwRuntimeException( new IllegalArgumentException("call to [sum] must be within a [projections] node")); } else { this.projectionList.add(Projections.sum(calculatePropertyName(propertyName))); } } /** * Sets the fetch mode of an associated path * * @param associationPath The name of the associated path * @param fetchMode The fetch mode to set */ public void fetchMode(String associationPath, FetchMode fetchMode) { if(criteria!=null) { criteria.setFetchMode(associationPath, fetchMode); } } /** * Sets the resultTransformer. * @param resultTransformer The result transformer to use. */ public void resultTransformer(ResultTransformer resultTransformer) { if (criteria == null) { throwRuntimeException( new IllegalArgumentException("Call to [resultTransformer] not supported here")); } this.resultTransformer = resultTransformer; } /** * Creates a Criterion that compares to class properties for equality * @param propertyName The first property name * @param otherPropertyName The second property name * @return A Criterion instance */ public Object eqProperty(String propertyName, String otherPropertyName) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [eqProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here.") ); } propertyName = calculatePropertyName(propertyName); otherPropertyName = calculatePropertyName(otherPropertyName); return addToCriteria(Restrictions.eqProperty( propertyName, otherPropertyName )); } /** * Creates a Criterion that compares to class properties for !equality * @param propertyName The first property name * @param otherPropertyName The second property name * @return A Criterion instance */ public Object neProperty(String propertyName, String otherPropertyName) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [neProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); otherPropertyName = calculatePropertyName(otherPropertyName); return addToCriteria(Restrictions.neProperty( propertyName, otherPropertyName )); } /** * Creates a Criterion that tests if the first property is greater than the second property * @param propertyName The first property name * @param otherPropertyName The second property name * @return A Criterion instance */ public Object gtProperty(String propertyName, String otherPropertyName) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [gtProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); otherPropertyName = calculatePropertyName(otherPropertyName); return addToCriteria(Restrictions.gtProperty( propertyName, otherPropertyName )); } /** * Creates a Criterion that tests if the first property is greater than or equal to the second property * @param propertyName The first property name * @param otherPropertyName The second property name * @return A Criterion instance */ public Object geProperty(String propertyName, String otherPropertyName) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [geProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); otherPropertyName = calculatePropertyName(otherPropertyName); return addToCriteria(Restrictions.geProperty( propertyName, otherPropertyName )); } /** * Creates a Criterion that tests if the first property is less than the second property * @param propertyName The first property name * @param otherPropertyName The second property name * @return A Criterion instance */ public Object ltProperty(String propertyName, String otherPropertyName) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [ltProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); otherPropertyName = calculatePropertyName(otherPropertyName); return addToCriteria(Restrictions.ltProperty( propertyName, otherPropertyName )); } /** * Creates a Criterion that tests if the first property is less than or equal to the second property * @param propertyName The first property name * @param otherPropertyName The second property name * @return A Criterion instance */ public Object leProperty(String propertyName, String otherPropertyName) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [leProperty] with propertyName ["+propertyName+"] and other property name ["+otherPropertyName+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); otherPropertyName = calculatePropertyName(otherPropertyName); return addToCriteria(Restrictions.leProperty(propertyName, otherPropertyName)); } /** * Creates a "greater than" Criterion based on the specified property name and value * @param propertyName The property name * @param propertyValue The property value * @return A Criterion instance */ public Object gt(String propertyName, Object propertyValue) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [gt] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); propertyValue = calculatePropertyValue(propertyValue); return addToCriteria(Restrictions.gt(propertyName, propertyValue)); } /** * Creates a "greater than or equal to" Criterion based on the specified property name and value * @param propertyName The property name * @param propertyValue The property value * @return A Criterion instance */ public Object ge(String propertyName, Object propertyValue) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [ge] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); propertyValue = calculatePropertyValue(propertyValue); return addToCriteria(Restrictions.ge(propertyName, propertyValue)); } /** * Creates a "less than" Criterion based on the specified property name and value * @param propertyName The property name * @param propertyValue The property value * @return A Criterion instance */ public Object lt(String propertyName, Object propertyValue) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [lt] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); propertyValue = calculatePropertyValue(propertyValue); return addToCriteria(Restrictions.lt(propertyName, propertyValue)); } /** * Creates a "less than or equal to" Criterion based on the specified property name and value * @param propertyName The property name * @param propertyValue The property value * @return A Criterion instance */ public Object le(String propertyName, Object propertyValue) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [le] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); propertyValue = calculatePropertyValue(propertyValue); return addToCriteria(Restrictions.le(propertyName, propertyValue)); } /** * Creates an "equals" Criterion based on the specified property name and value * @param propertyName The property name * @param propertyValue The property value * * @return A Criterion instance */ public Object eq(String propertyName, Object propertyValue) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [eq] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); propertyValue = calculatePropertyValue(propertyValue); return addToCriteria(Restrictions.eq(propertyName, propertyValue)); } /** * Creates a Criterion with from the specified property name and "like" expression * @param propertyName The property name * @param propertyValue The like value * * @return A Criterion instance */ public Object like(String propertyName, Object propertyValue) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [like] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); propertyValue = calculatePropertyValue(propertyValue); return addToCriteria(Restrictions.like(propertyName, propertyValue)); } /** * Creates a Criterion with from the specified property name and "rlike" (a regular expression version of "like") expression * @param propertyName The property name * @param propertyValue The ilike value * * @return A Criterion instance */ public Object rlike(String propertyName, Object propertyValue) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [rlike] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); propertyValue = calculatePropertyValue(propertyValue); return addToCriteria(new RlikeExpression(propertyName, propertyValue)); } /** * Creates a Criterion with from the specified property name and "ilike" (a case sensitive version of "like") expression * @param propertyName The property name * @param propertyValue The ilike value * * @return A Criterion instance */ public Object ilike(String propertyName, Object propertyValue) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [ilike] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); propertyValue = calculatePropertyValue(propertyValue); return addToCriteria(Restrictions.ilike(propertyName, propertyValue)); } /** * Applys a "in" contrain on the specified property * @param propertyName The property name * @param values A collection of values * * @return A Criterion instance */ public Object in(String propertyName, Collection values) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [in] with propertyName ["+propertyName+"] and values ["+values+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); return addToCriteria(Restrictions.in(propertyName, values)); } /** * Delegates to in as in is a Groovy keyword **/ public Object inList(String propertyName, Collection values) { return in(propertyName, values); } /** * Delegates to in as in is a Groovy keyword **/ public Object inList(String propertyName, Object[] values) { return in(propertyName, values); } /** * Applys a "in" contrain on the specified property * @param propertyName The property name * @param values A collection of values * * @return A Criterion instance */ public Object in(String propertyName, Object[] values) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [in] with propertyName ["+propertyName+"] and values ["+values+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); return addToCriteria(Restrictions.in(propertyName, values)); } /** * Orders by the specified property name (defaults to ascending) * * @param propertyName The property name to order by * @return A Order instance */ public Object order(String propertyName) { if(this.criteria == null) throwRuntimeException( new IllegalArgumentException("Call to [order] with propertyName ["+propertyName+"]not allowed here.")); propertyName = calculatePropertyName(propertyName); Order o = Order.asc(propertyName); this.criteria.addOrder(o); return o; } /** * Orders by the specified property name and direction * * @param propertyName The property name to order by * @param direction Either "asc" for ascending or "desc" for descending * * @return A Order instance */ public Object order(String propertyName, String direction) { if(this.criteria == null) throwRuntimeException( new IllegalArgumentException("Call to [order] with propertyName ["+propertyName+"]not allowed here.")); propertyName = calculatePropertyName(propertyName); Order o; if(direction.equals( ORDER_DESCENDING )) { o = Order.desc(propertyName); } else { o = Order.asc(propertyName); } this.criteria.addOrder(o); return o; } /** * Creates a Criterion that contrains a collection property by size * * @param propertyName The property name * @param size The size to constrain by * * @return A Criterion instance */ public Object sizeEq(String propertyName, int size) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [sizeEq] with propertyName ["+propertyName+"] and size ["+size+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); return addToCriteria(Restrictions.sizeEq(propertyName, size)); } /** * Creates a Criterion that contrains a collection property to be greater than the given size * * @param propertyName The property name * @param size The size to constrain by * * @return A Criterion instance */ public Object sizeGt(String propertyName, int size) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [sizeEq] with propertyName ["+propertyName+"] and size ["+size+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); return addToCriteria(Restrictions.sizeGt(propertyName, size)); } /** * Creates a Criterion that contrains a collection property to be greater than or equal to the given size * * @param propertyName The property name * @param size The size to constrain by * * @return A Criterion instance */ public Object sizeGe(String propertyName, int size) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [sizeEq] with propertyName ["+propertyName+"] and size ["+size+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); return addToCriteria(Restrictions.sizeGe(propertyName, size)); } /** * Creates a Criterion that contrains a collection property to be less than or equal to the given size * * @param propertyName The property name * @param size The size to constrain by * * @return A Criterion instance */ public Object sizeLe(String propertyName, int size) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [sizeEq] with propertyName ["+propertyName+"] and size ["+size+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); return addToCriteria(Restrictions.sizeLe(propertyName, size)); } /** * Creates a Criterion that contrains a collection property to be less than to the given size * * @param propertyName The property name * @param size The size to constrain by * * @return A Criterion instance */ public Object sizeLt(String propertyName, int size) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [sizeEq] with propertyName ["+propertyName+"] and size ["+size+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); return addToCriteria(Restrictions.sizeLt(propertyName, size)); } /** * Creates a Criterion that contrains a collection property to be not equal to the given size * * @param propertyName The property name * @param size The size to constrain by * * @return A Criterion instance */ public Object sizeNe(String propertyName, int size) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [sizeEq] with propertyName ["+propertyName+"] and size ["+size+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); return addToCriteria(Restrictions.sizeNe(propertyName, size)); } /** * Creates a "not equal" Criterion based on the specified property name and value * @param propertyName The property name * @param propertyValue The property value * @return The criterion object */ public Object ne(String propertyName, Object propertyValue) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [ne] with propertyName ["+propertyName+"] and value ["+propertyValue+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); propertyValue = calculatePropertyValue(propertyValue); return addToCriteria(Restrictions.ne(propertyName, propertyValue)); } public Object notEqual(String propertyName, Object propertyValue) { return ne(propertyName, propertyValue); } /** * Creates a "between" Criterion based on the property name and specified lo and hi values * @param propertyName The property name * @param lo The low value * @param hi The high value * @return A Criterion instance */ public Object between(String propertyName, Object lo, Object hi) { if(!validateSimpleExpression()) { throwRuntimeException( new IllegalArgumentException("Call to [between] with propertyName ["+propertyName+"] not allowed here.")); } propertyName = calculatePropertyName(propertyName); return addToCriteria(Restrictions.between(propertyName, lo, hi)); } private boolean validateSimpleExpression() { if(this.criteria == null) { return false; } return true; } public Object invokeMethod(String name, Object obj) { Object[] args = obj.getClass().isArray() ? (Object[])obj : new Object[]{obj}; if(isCriteriaConstructionMethod(name, args)) { if(this.criteria != null) { throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); } if (name.equals(GET_CALL)) { this.uniqueResult = true; } else if (name.equals(SCROLL_CALL)) { this.scroll = true; } else if (name.equals(COUNT_CALL)) { this.count = true; } else if (name.equals(LIST_DISTINCT_CALL)) { this.resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY; } boolean paginationEnabledList = false; createCriteriaInstance(); // Check for pagination params if(name.equals(LIST_CALL) && args.length == 2) { paginationEnabledList = true; invokeClosureNode(args[1]); } else { invokeClosureNode(args[0]); } if(resultTransformer != null) { this.criteria.setResultTransformer(resultTransformer); } Object result; if(!uniqueResult) { if(scroll) { result = this.criteria.scroll(); } else if(count) { this.criteria.setProjection(Projections.rowCount()); result = this.criteria.uniqueResult(); } else if(paginationEnabledList) { // Calculate how many results there are in total. This has been // moved to before the 'list()' invocation to avoid any "ORDER // BY" clause added by 'populateArgumentsForCriteria()', otherwise // an exception is thrown for non-string sort fields (GRAILS-2690). this.criteria.setFirstResult(0); this.criteria.setMaxResults(Integer.MAX_VALUE); this.criteria.setProjection(Projections.rowCount()); int totalCount = ((Integer)this.criteria.uniqueResult()).intValue(); // Drop the projection, add settings for the pagination parameters, // and then execute the query. this.criteria.setProjection(null); this.criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); GrailsHibernateUtil.populateArgumentsForCriteria(targetClass, this.criteria, (Map)args[0]); PagedResultList pagedRes = new PagedResultList(this.criteria.list()); // Updated the paged results with the total number of records // calculated previously. pagedRes.setTotalCount(totalCount); result = pagedRes; } else { result = this.criteria.list(); } } else { result = this.criteria.uniqueResult(); } if(!this.participate) { this.hibernateSession.close(); } return result; } else { if(criteria==null) createCriteriaInstance(); MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args); if(metaMethod != null) { return metaMethod.invoke(this, args); } metaMethod = criteriaMetaClass.getMetaMethod(name, args); if(metaMethod != null) { return metaMethod.invoke(criteria, args); } metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args); if(metaMethod != null) { return metaMethod.invoke(criteria, args); } else if(args.length == 1 && args[0] instanceof Closure) { if(name.equals( AND ) || name.equals( OR ) || name.equals( NOT ) ) { if(this.criteria == null) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); this.logicalExpressionStack.add(new LogicalExpression(name)); invokeClosureNode(args[0]); - LogicalExpression logicalExpression = logicalExpressionStack.get(logicalExpressionStack.size()-1); + LogicalExpression logicalExpression = logicalExpressionStack.remove(logicalExpressionStack.size()-1); addToCriteria(logicalExpression.toCriterion()); return name; } else if(name.equals( PROJECTIONS ) && args.length == 1 && (args[0] instanceof Closure)) { if(this.criteria == null) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); this.projectionList = Projections.projectionList(); invokeClosureNode(args[0]); if(this.projectionList != null && this.projectionList.getLength() > 0) { this.criteria.setProjection(this.projectionList); } return name; } else if(targetBean.isReadableProperty(name.toString())) { ClassMetadata meta = sessionFactory.getClassMetadata(targetBean.getWrappedClass()); Type type = meta.getPropertyType(name.toString()); if (type.isAssociationType()) { String otherSideEntityName = ((AssociationType) type).getAssociatedEntityName((SessionFactoryImplementor) sessionFactory); Class oldTargetClass = targetClass; targetClass = sessionFactory.getClassMetadata(otherSideEntityName).getMappedClass(EntityMode.POJO); BeanWrapper oldTargetBean = targetBean; targetBean = new BeanWrapperImpl(BeanUtils.instantiateClass(targetClass)); associationStack.add(name.toString()); final String associationPath = getAssociationPath(); createAliasIfNeccessary(name, associationPath); // the criteria within an association node are grouped with an implicit AND logicalExpressionStack.add(new LogicalExpression(AND)); invokeClosureNode(args[0]); aliasStack.remove(aliasStack.size() - 1); if(!aliasInstanceStack.isEmpty()) { aliasInstanceStack.remove(aliasInstanceStack.size() - 1); } - LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.remove(logicalExpressionStack.size()-1); + LogicalExpression logicalExpression = logicalExpressionStack.remove(logicalExpressionStack.size()-1); if (!logicalExpression.args.isEmpty()) { addToCriteria(logicalExpression.toCriterion()); } associationStack.remove(associationStack.size()-1); targetClass = oldTargetClass; targetBean = oldTargetBean; return name; } } } else if(args.length == 1 && args[0] != null) { if(this.criteria == null) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); Object value = args[0]; Criterion c = null; if(name.equals(ID_EQUALS)) { return eq("id", value); } else { if( name.equals( IS_NULL ) || name.equals( IS_NOT_NULL ) || name.equals( IS_EMPTY ) || name.equals( IS_NOT_EMPTY )) { if(!(value instanceof String)) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] with value ["+value+"] requires a String value.")); String propertyName = calculatePropertyName((String)value); if(name.equals( IS_NULL )) { c = Restrictions.isNull( propertyName ) ; } else if(name.equals( IS_NOT_NULL )) { c = Restrictions.isNotNull( propertyName ); } else if(name.equals( IS_EMPTY )) { c = Restrictions.isEmpty( propertyName ); } else if(name.equals( IS_NOT_EMPTY )) { c = Restrictions.isNotEmpty(propertyName ); } } } if(c != null) { return addToCriteria(c); } } } closeSessionFollowingException(); throw new MissingMethodException(name, getClass(), args) ; } private void addToCurrentOrAliasedCriteria(Criterion criterion) { if(!aliasInstanceStack.isEmpty()) { Criteria c = aliasInstanceStack.get(aliasInstanceStack.size()-1); c.add(criterion); } else { this.criteria.add(criterion); } } private void createAliasIfNeccessary(String associationName, String associationPath) { String newAlias; if(aliasMap.containsKey(associationPath)) { newAlias = aliasMap.get(associationPath); } else { aliasCount++; newAlias = associationName + ALIAS + aliasCount; aliasMap.put(associationPath, newAlias); this.aliasInstanceStack.add(this.criteria.createAlias(associationPath, newAlias, CriteriaSpecification.LEFT_JOIN)); } this.aliasStack.add(newAlias); } private String getAssociationPath() { StringBuilder fullPath = new StringBuilder(); for (Object anAssociationStack : associationStack) { String propertyName = (String) anAssociationStack; if (fullPath.length() > 0) fullPath.append("."); fullPath.append(propertyName); } final String associationPath = fullPath.toString(); return associationPath; } private boolean isCriteriaConstructionMethod(String name, Object[] args) { return (name.equals(LIST_CALL) && args.length == 2 && args[0] instanceof Map && args[1] instanceof Closure) || (name.equals(ROOT_CALL) || name.equals(ROOT_DO_CALL) || name.equals(LIST_CALL) || name.equals(LIST_DISTINCT_CALL) || name.equals(GET_CALL) || name.equals(COUNT_CALL) || name.equals(SCROLL_CALL) && args.length == 1 && args[0] instanceof Closure); } private void createCriteriaInstance() { if(TransactionSynchronizationManager.hasResource(sessionFactory)) { this.participate = true; this.hibernateSession = ((SessionHolder)TransactionSynchronizationManager.getResource(sessionFactory)).getSession(); } else { this.hibernateSession = sessionFactory.openSession(); } this.criteria = this.hibernateSession.createCriteria(targetClass); GrailsHibernateUtil.cacheCriteriaByMapping(targetClass, criteria); this.criteriaMetaClass = GroovySystem.getMetaClassRegistry().getMetaClass(criteria.getClass()); } private void invokeClosureNode(Object args) { Closure callable = (Closure)args; callable.setDelegate(this); callable.setResolveStrategy(Closure.DELEGATE_FIRST); callable.call(); } /** * Throws a runtime exception where necessary to ensure the session gets closed */ private void throwRuntimeException(RuntimeException t) { closeSessionFollowingException(); throw t; } private void closeSessionFollowingException() { if(this.hibernateSession != null && this.hibernateSession.isOpen() && !this.participate) { this.hibernateSession.close(); } if(this.criteria != null) { this.criteria = null; } } /** * adds and returns the given criterion to the currently active criteria set. * this might be either the root criteria or a currently open * LogicalExpression. */ private Criterion addToCriteria(Criterion c) { if (!logicalExpressionStack.isEmpty()) { logicalExpressionStack.get(logicalExpressionStack.size()-1).args.add(c); } else { this.criteria.add(c); } return c; } /** * instances of this class are pushed onto the logicalExpressionStack * to represent all the unfinished "and", "or", and "not" expressions. */ private class LogicalExpression { final Object name; final ArrayList args = new ArrayList(); LogicalExpression(Object name) { this.name = name; } Criterion toCriterion() { if (name.equals(NOT)) { switch (args.size()) { case 0: throwRuntimeException(new IllegalArgumentException("Logical expression [not] must contain at least 1 expression")); return null; case 1: return Restrictions.not((Criterion) args.get(0)); default: // treat multiple sub-criteria as an implicit "OR" return Restrictions.not(buildJunction(Restrictions.disjunction(), args)); } } else if (name.equals(AND)) { return buildJunction(Restrictions.conjunction(), args); } else if (name.equals(OR)) { return buildJunction(Restrictions.disjunction(), args); } else { throwRuntimeException(new IllegalStateException("Logical expression [" + name + "] not handled!")); return null; } } // add the Criterion objects in the given list to the given junction. Junction buildJunction(Junction junction, List criteria) { for (Iterator i = criteria.iterator(); i.hasNext();) { junction.add((Criterion) i.next()); } return junction; } } }
false
true
public Object invokeMethod(String name, Object obj) { Object[] args = obj.getClass().isArray() ? (Object[])obj : new Object[]{obj}; if(isCriteriaConstructionMethod(name, args)) { if(this.criteria != null) { throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); } if (name.equals(GET_CALL)) { this.uniqueResult = true; } else if (name.equals(SCROLL_CALL)) { this.scroll = true; } else if (name.equals(COUNT_CALL)) { this.count = true; } else if (name.equals(LIST_DISTINCT_CALL)) { this.resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY; } boolean paginationEnabledList = false; createCriteriaInstance(); // Check for pagination params if(name.equals(LIST_CALL) && args.length == 2) { paginationEnabledList = true; invokeClosureNode(args[1]); } else { invokeClosureNode(args[0]); } if(resultTransformer != null) { this.criteria.setResultTransformer(resultTransformer); } Object result; if(!uniqueResult) { if(scroll) { result = this.criteria.scroll(); } else if(count) { this.criteria.setProjection(Projections.rowCount()); result = this.criteria.uniqueResult(); } else if(paginationEnabledList) { // Calculate how many results there are in total. This has been // moved to before the 'list()' invocation to avoid any "ORDER // BY" clause added by 'populateArgumentsForCriteria()', otherwise // an exception is thrown for non-string sort fields (GRAILS-2690). this.criteria.setFirstResult(0); this.criteria.setMaxResults(Integer.MAX_VALUE); this.criteria.setProjection(Projections.rowCount()); int totalCount = ((Integer)this.criteria.uniqueResult()).intValue(); // Drop the projection, add settings for the pagination parameters, // and then execute the query. this.criteria.setProjection(null); this.criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); GrailsHibernateUtil.populateArgumentsForCriteria(targetClass, this.criteria, (Map)args[0]); PagedResultList pagedRes = new PagedResultList(this.criteria.list()); // Updated the paged results with the total number of records // calculated previously. pagedRes.setTotalCount(totalCount); result = pagedRes; } else { result = this.criteria.list(); } } else { result = this.criteria.uniqueResult(); } if(!this.participate) { this.hibernateSession.close(); } return result; } else { if(criteria==null) createCriteriaInstance(); MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args); if(metaMethod != null) { return metaMethod.invoke(this, args); } metaMethod = criteriaMetaClass.getMetaMethod(name, args); if(metaMethod != null) { return metaMethod.invoke(criteria, args); } metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args); if(metaMethod != null) { return metaMethod.invoke(criteria, args); } else if(args.length == 1 && args[0] instanceof Closure) { if(name.equals( AND ) || name.equals( OR ) || name.equals( NOT ) ) { if(this.criteria == null) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); this.logicalExpressionStack.add(new LogicalExpression(name)); invokeClosureNode(args[0]); LogicalExpression logicalExpression = logicalExpressionStack.get(logicalExpressionStack.size()-1); addToCriteria(logicalExpression.toCriterion()); return name; } else if(name.equals( PROJECTIONS ) && args.length == 1 && (args[0] instanceof Closure)) { if(this.criteria == null) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); this.projectionList = Projections.projectionList(); invokeClosureNode(args[0]); if(this.projectionList != null && this.projectionList.getLength() > 0) { this.criteria.setProjection(this.projectionList); } return name; } else if(targetBean.isReadableProperty(name.toString())) { ClassMetadata meta = sessionFactory.getClassMetadata(targetBean.getWrappedClass()); Type type = meta.getPropertyType(name.toString()); if (type.isAssociationType()) { String otherSideEntityName = ((AssociationType) type).getAssociatedEntityName((SessionFactoryImplementor) sessionFactory); Class oldTargetClass = targetClass; targetClass = sessionFactory.getClassMetadata(otherSideEntityName).getMappedClass(EntityMode.POJO); BeanWrapper oldTargetBean = targetBean; targetBean = new BeanWrapperImpl(BeanUtils.instantiateClass(targetClass)); associationStack.add(name.toString()); final String associationPath = getAssociationPath(); createAliasIfNeccessary(name, associationPath); // the criteria within an association node are grouped with an implicit AND logicalExpressionStack.add(new LogicalExpression(AND)); invokeClosureNode(args[0]); aliasStack.remove(aliasStack.size() - 1); if(!aliasInstanceStack.isEmpty()) { aliasInstanceStack.remove(aliasInstanceStack.size() - 1); } LogicalExpression logicalExpression = (LogicalExpression) logicalExpressionStack.remove(logicalExpressionStack.size()-1); if (!logicalExpression.args.isEmpty()) { addToCriteria(logicalExpression.toCriterion()); } associationStack.remove(associationStack.size()-1); targetClass = oldTargetClass; targetBean = oldTargetBean; return name; } } } else if(args.length == 1 && args[0] != null) { if(this.criteria == null) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); Object value = args[0]; Criterion c = null; if(name.equals(ID_EQUALS)) { return eq("id", value); } else { if( name.equals( IS_NULL ) || name.equals( IS_NOT_NULL ) || name.equals( IS_EMPTY ) || name.equals( IS_NOT_EMPTY )) { if(!(value instanceof String)) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] with value ["+value+"] requires a String value.")); String propertyName = calculatePropertyName((String)value); if(name.equals( IS_NULL )) { c = Restrictions.isNull( propertyName ) ; } else if(name.equals( IS_NOT_NULL )) { c = Restrictions.isNotNull( propertyName ); } else if(name.equals( IS_EMPTY )) { c = Restrictions.isEmpty( propertyName ); } else if(name.equals( IS_NOT_EMPTY )) { c = Restrictions.isNotEmpty(propertyName ); } } } if(c != null) { return addToCriteria(c); } } } closeSessionFollowingException(); throw new MissingMethodException(name, getClass(), args) ; }
public Object invokeMethod(String name, Object obj) { Object[] args = obj.getClass().isArray() ? (Object[])obj : new Object[]{obj}; if(isCriteriaConstructionMethod(name, args)) { if(this.criteria != null) { throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); } if (name.equals(GET_CALL)) { this.uniqueResult = true; } else if (name.equals(SCROLL_CALL)) { this.scroll = true; } else if (name.equals(COUNT_CALL)) { this.count = true; } else if (name.equals(LIST_DISTINCT_CALL)) { this.resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY; } boolean paginationEnabledList = false; createCriteriaInstance(); // Check for pagination params if(name.equals(LIST_CALL) && args.length == 2) { paginationEnabledList = true; invokeClosureNode(args[1]); } else { invokeClosureNode(args[0]); } if(resultTransformer != null) { this.criteria.setResultTransformer(resultTransformer); } Object result; if(!uniqueResult) { if(scroll) { result = this.criteria.scroll(); } else if(count) { this.criteria.setProjection(Projections.rowCount()); result = this.criteria.uniqueResult(); } else if(paginationEnabledList) { // Calculate how many results there are in total. This has been // moved to before the 'list()' invocation to avoid any "ORDER // BY" clause added by 'populateArgumentsForCriteria()', otherwise // an exception is thrown for non-string sort fields (GRAILS-2690). this.criteria.setFirstResult(0); this.criteria.setMaxResults(Integer.MAX_VALUE); this.criteria.setProjection(Projections.rowCount()); int totalCount = ((Integer)this.criteria.uniqueResult()).intValue(); // Drop the projection, add settings for the pagination parameters, // and then execute the query. this.criteria.setProjection(null); this.criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); GrailsHibernateUtil.populateArgumentsForCriteria(targetClass, this.criteria, (Map)args[0]); PagedResultList pagedRes = new PagedResultList(this.criteria.list()); // Updated the paged results with the total number of records // calculated previously. pagedRes.setTotalCount(totalCount); result = pagedRes; } else { result = this.criteria.list(); } } else { result = this.criteria.uniqueResult(); } if(!this.participate) { this.hibernateSession.close(); } return result; } else { if(criteria==null) createCriteriaInstance(); MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args); if(metaMethod != null) { return metaMethod.invoke(this, args); } metaMethod = criteriaMetaClass.getMetaMethod(name, args); if(metaMethod != null) { return metaMethod.invoke(criteria, args); } metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args); if(metaMethod != null) { return metaMethod.invoke(criteria, args); } else if(args.length == 1 && args[0] instanceof Closure) { if(name.equals( AND ) || name.equals( OR ) || name.equals( NOT ) ) { if(this.criteria == null) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); this.logicalExpressionStack.add(new LogicalExpression(name)); invokeClosureNode(args[0]); LogicalExpression logicalExpression = logicalExpressionStack.remove(logicalExpressionStack.size()-1); addToCriteria(logicalExpression.toCriterion()); return name; } else if(name.equals( PROJECTIONS ) && args.length == 1 && (args[0] instanceof Closure)) { if(this.criteria == null) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); this.projectionList = Projections.projectionList(); invokeClosureNode(args[0]); if(this.projectionList != null && this.projectionList.getLength() > 0) { this.criteria.setProjection(this.projectionList); } return name; } else if(targetBean.isReadableProperty(name.toString())) { ClassMetadata meta = sessionFactory.getClassMetadata(targetBean.getWrappedClass()); Type type = meta.getPropertyType(name.toString()); if (type.isAssociationType()) { String otherSideEntityName = ((AssociationType) type).getAssociatedEntityName((SessionFactoryImplementor) sessionFactory); Class oldTargetClass = targetClass; targetClass = sessionFactory.getClassMetadata(otherSideEntityName).getMappedClass(EntityMode.POJO); BeanWrapper oldTargetBean = targetBean; targetBean = new BeanWrapperImpl(BeanUtils.instantiateClass(targetClass)); associationStack.add(name.toString()); final String associationPath = getAssociationPath(); createAliasIfNeccessary(name, associationPath); // the criteria within an association node are grouped with an implicit AND logicalExpressionStack.add(new LogicalExpression(AND)); invokeClosureNode(args[0]); aliasStack.remove(aliasStack.size() - 1); if(!aliasInstanceStack.isEmpty()) { aliasInstanceStack.remove(aliasInstanceStack.size() - 1); } LogicalExpression logicalExpression = logicalExpressionStack.remove(logicalExpressionStack.size()-1); if (!logicalExpression.args.isEmpty()) { addToCriteria(logicalExpression.toCriterion()); } associationStack.remove(associationStack.size()-1); targetClass = oldTargetClass; targetBean = oldTargetBean; return name; } } } else if(args.length == 1 && args[0] != null) { if(this.criteria == null) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); Object value = args[0]; Criterion c = null; if(name.equals(ID_EQUALS)) { return eq("id", value); } else { if( name.equals( IS_NULL ) || name.equals( IS_NOT_NULL ) || name.equals( IS_EMPTY ) || name.equals( IS_NOT_EMPTY )) { if(!(value instanceof String)) throwRuntimeException( new IllegalArgumentException("call to [" + name + "] with value ["+value+"] requires a String value.")); String propertyName = calculatePropertyName((String)value); if(name.equals( IS_NULL )) { c = Restrictions.isNull( propertyName ) ; } else if(name.equals( IS_NOT_NULL )) { c = Restrictions.isNotNull( propertyName ); } else if(name.equals( IS_EMPTY )) { c = Restrictions.isEmpty( propertyName ); } else if(name.equals( IS_NOT_EMPTY )) { c = Restrictions.isNotEmpty(propertyName ); } } } if(c != null) { return addToCriteria(c); } } } closeSessionFollowingException(); throw new MissingMethodException(name, getClass(), args) ; }