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/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/webservice/eap/EAPFromJavaTest.java b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/webservice/eap/EAPFromJavaTest.java
index 18113d36..1eaa9b45 100644
--- a/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/webservice/eap/EAPFromJavaTest.java
+++ b/tests/org.jboss.tools.ws.ui.bot.test/src/org/jboss/tools/ws/ui/bot/test/webservice/eap/EAPFromJavaTest.java
@@ -1,164 +1,165 @@
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.ws.ui.bot.test.webservice.eap;
import java.util.logging.Level;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEclipseEditor;
import org.jboss.tools.ui.bot.ext.config.Annotations.Require;
import org.jboss.tools.ui.bot.ext.config.Annotations.Server;
import org.jboss.tools.ws.ui.bot.test.WSAllBotTests;
import org.jboss.tools.ws.ui.bot.test.uiutils.actions.NewFileWizardAction;
import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.Wizard;
import org.jboss.tools.ws.ui.bot.test.uiutils.wizards.WsWizardBase.Slider_Level;
import org.jboss.tools.ws.ui.bot.test.webservice.WebServiceTestBase;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runners.Suite.SuiteClasses;
/**
* Test operates on creating non-trivial EAP project from Java class
* @author jlukas
*
*/
@SuiteClasses({ WSAllBotTests.class, EAPCompAllTests.class })
@Require(perspective="Java EE",
server=@Server)
// (type=ServerType.EAP,
// version = "5.1", operator = ">="))
public class EAPFromJavaTest extends WebServiceTestBase {
private static boolean servicePassed = false;
@Before
@Override
public void setup() {
if (!projectExists(getWsProjectName())) {
projectHelper.createProject(getWsProjectName());
}
if (!projectExists(getWsClientProjectName())) {
projectHelper.createProject(getWsClientProjectName());
}
}
@After
@Override
public void cleanup() {
//do nothing here
//we don't want to undeploy our app yet
}
@AfterClass
public static void removeAllProjects() {
servers.removeAllProjectsFromServer();
}
@Override
protected String getWsProjectName() {
return "TestWSProject";
}
@Override
protected String getEarProjectName() {
return getWsProjectName() + "EAR";
}
protected String getWsClientProjectName() {
return "TestWSClientProject";
}
@Override
protected String getWsPackage() {
return "test.ws";
}
@Override
protected String getWsName() {
return "Echo";
}
@Override
protected Slider_Level getLevel() {
return Slider_Level.DEPLOY;
}
@Test
public void testService() {
//create a class representing some complex type
SWTBotEclipseEditor st = projectHelper.createClass(getWsProjectName(), "test", "Person").toTextEditor();
st.selectRange(0, 0, st.getText().length());
st.setText(resourceHelper.readStream(EAPFromJavaTest.class.getResourceAsStream("/resources/jbossws/Person.java.ws")));
st.saveAndClose();
//refresh workspace - workaround??? for JBIDE-6731
try {
ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IWorkspaceRoot.DEPTH_INFINITE, new NullProgressMonitor());
} catch (CoreException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e);
}
bot.sleep(TIME_500MS);
bottomUpJbossWebService(EAPFromJavaTest.class.getResourceAsStream("/resources/jbossws/Echo.java.ws"));
IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(getWsProjectName());
IFile f = project.getFile("WebContent/WEB-INF/web.xml");
String content = resourceHelper.readFile(f);
Assert.assertNotNull(content);
Assert.assertTrue(content.contains("<servlet-class>test.ws.Echo</servlet-class>"));
Assert.assertTrue(content.contains("<url-pattern>/Echo</url-pattern>"));
deploymentHelper.runProject(getEarProjectName());
deploymentHelper.assertServiceDeployed(deploymentHelper.getWSDLUrl(getWsProjectName(), getWsName()), 10000);
servicePassed = true;
}
@Test
public void testClient() {
Assert.assertTrue("service must exist", servicePassed);
clientHelper.createClient(deploymentHelper.getWSDLUrl(getWsProjectName(), getWsName()),
getWsClientProjectName(), getLevel(), "");
IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject(getWsClientProjectName());
String pkg = "test/ws";
String cls = "src/" + pkg + "/EchoService.java";
Assert.assertTrue(p.getFile(cls).exists());
cls = "src/" + pkg + "/clientsample/ClientSample.java";
Assert.assertTrue(p.getFile(cls).exists());
//create JSP
new NewFileWizardAction().run().selectTemplate("Web", "JSP File").next();
Wizard w = new Wizard();
w.bot().textWithLabel("File name:").setText("index");
w.bot().textWithLabel("Enter or select the parent folder:").setText(getWsClientProjectName() + "/WebContent");
w.finish();
bot.sleep(TIME_5S);
/**
* Workaround for 4.x branch
*
* bot.activeShell().bot().button("Skip").click();
* bot.sleep(TIME_5S);
*/
SWTBotEclipseEditor st = bot.editorByTitle("index.jsp").toTextEditor();
st.selectRange(0, 0, st.getText().length());
st.setText(resourceHelper.readStream(EAPFromJavaTest.class.getResourceAsStream("/resources/jbossws/index.jsp.ws")));
st.saveAndClose();
bot.sleep(TIME_1S*2);
deploymentHelper.runProject(getWsClientProjectName());
+ servers.cleanServer(configuredState.getServer().name);
String pageContent = deploymentHelper.getPage("http://localhost:8080/" + getWsClientProjectName() + "/index.jsp", 15000);
LOGGER.info(pageContent);
Assert.assertTrue(pageContent.contains("BartSimpson(age: 12)"));
Assert.assertTrue(pageContent.contains("Homer(age: 44)"));
}
}
| true | true | public void testClient() {
Assert.assertTrue("service must exist", servicePassed);
clientHelper.createClient(deploymentHelper.getWSDLUrl(getWsProjectName(), getWsName()),
getWsClientProjectName(), getLevel(), "");
IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject(getWsClientProjectName());
String pkg = "test/ws";
String cls = "src/" + pkg + "/EchoService.java";
Assert.assertTrue(p.getFile(cls).exists());
cls = "src/" + pkg + "/clientsample/ClientSample.java";
Assert.assertTrue(p.getFile(cls).exists());
//create JSP
new NewFileWizardAction().run().selectTemplate("Web", "JSP File").next();
Wizard w = new Wizard();
w.bot().textWithLabel("File name:").setText("index");
w.bot().textWithLabel("Enter or select the parent folder:").setText(getWsClientProjectName() + "/WebContent");
w.finish();
bot.sleep(TIME_5S);
/**
* Workaround for 4.x branch
*
* bot.activeShell().bot().button("Skip").click();
* bot.sleep(TIME_5S);
*/
SWTBotEclipseEditor st = bot.editorByTitle("index.jsp").toTextEditor();
st.selectRange(0, 0, st.getText().length());
st.setText(resourceHelper.readStream(EAPFromJavaTest.class.getResourceAsStream("/resources/jbossws/index.jsp.ws")));
st.saveAndClose();
bot.sleep(TIME_1S*2);
deploymentHelper.runProject(getWsClientProjectName());
String pageContent = deploymentHelper.getPage("http://localhost:8080/" + getWsClientProjectName() + "/index.jsp", 15000);
LOGGER.info(pageContent);
Assert.assertTrue(pageContent.contains("BartSimpson(age: 12)"));
Assert.assertTrue(pageContent.contains("Homer(age: 44)"));
}
| public void testClient() {
Assert.assertTrue("service must exist", servicePassed);
clientHelper.createClient(deploymentHelper.getWSDLUrl(getWsProjectName(), getWsName()),
getWsClientProjectName(), getLevel(), "");
IProject p = ResourcesPlugin.getWorkspace().getRoot().getProject(getWsClientProjectName());
String pkg = "test/ws";
String cls = "src/" + pkg + "/EchoService.java";
Assert.assertTrue(p.getFile(cls).exists());
cls = "src/" + pkg + "/clientsample/ClientSample.java";
Assert.assertTrue(p.getFile(cls).exists());
//create JSP
new NewFileWizardAction().run().selectTemplate("Web", "JSP File").next();
Wizard w = new Wizard();
w.bot().textWithLabel("File name:").setText("index");
w.bot().textWithLabel("Enter or select the parent folder:").setText(getWsClientProjectName() + "/WebContent");
w.finish();
bot.sleep(TIME_5S);
/**
* Workaround for 4.x branch
*
* bot.activeShell().bot().button("Skip").click();
* bot.sleep(TIME_5S);
*/
SWTBotEclipseEditor st = bot.editorByTitle("index.jsp").toTextEditor();
st.selectRange(0, 0, st.getText().length());
st.setText(resourceHelper.readStream(EAPFromJavaTest.class.getResourceAsStream("/resources/jbossws/index.jsp.ws")));
st.saveAndClose();
bot.sleep(TIME_1S*2);
deploymentHelper.runProject(getWsClientProjectName());
servers.cleanServer(configuredState.getServer().name);
String pageContent = deploymentHelper.getPage("http://localhost:8080/" + getWsClientProjectName() + "/index.jsp", 15000);
LOGGER.info(pageContent);
Assert.assertTrue(pageContent.contains("BartSimpson(age: 12)"));
Assert.assertTrue(pageContent.contains("Homer(age: 44)"));
}
|
diff --git a/containers/sip-servlets-as7-drop-in/jboss-as-mobicents/src/main/java/org/mobicents/as7/SipServerService.java b/containers/sip-servlets-as7-drop-in/jboss-as-mobicents/src/main/java/org/mobicents/as7/SipServerService.java
index 2311d2d2d..ca3bb338f 100644
--- a/containers/sip-servlets-as7-drop-in/jboss-as-mobicents/src/main/java/org/mobicents/as7/SipServerService.java
+++ b/containers/sip-servlets-as7-drop-in/jboss-as-mobicents/src/main/java/org/mobicents/as7/SipServerService.java
@@ -1,314 +1,314 @@
/*
* TeleStax, Open Source Cloud Communications Copyright 2012.
* 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.mobicents.as7;
import static org.mobicents.as7.SipMessages.MESSAGES;
import javax.management.MBeanServer;
import org.apache.catalina.Host;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.core.StandardService;
import org.apache.tomcat.util.modeler.Registry;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.mobicents.servlet.sip.core.SipApplicationDispatcherImpl;
import org.mobicents.servlet.sip.startup.SipProtocolHandler;
import org.mobicents.servlet.sip.startup.SipStandardEngine;
import org.mobicents.servlet.sip.startup.SipStandardService;
/**
* Service configuring and starting the web container.
*
* @author Emanuel Muckenhuber
*/
class SipServerService implements SipServer, Service<SipServer> {
// FIXME: josemrecio - settle on using the proper name
private static final String JBOSS_SIP = "jboss.sip";
private static final String TEMP_DIR = "jboss.server.temp.dir";
// private final String defaultHost;
// private final boolean useNative;
private static final String FILE_PREFIX_PATH = "file:///";
private String sipAppRouterFile;
private String sipStackPropertiesFile;
final String sipPathName;
final String sipAppDispatcherClass;
final String additionalParameterableHeaders;
final int sipCongestionControlInterval;
final String congestionControlPolicy;
final String sipConcurrencyControlMode;
final boolean usePrettyEncoding;
final int baseTimerInterval;
final int t2Interval;
final int t4Interval;
final int timerDInterval;
final boolean dialogPendingRequestChecking;
final int canceledTimerTasksPurgePeriod;
final int memoryThreshold;
final int backToNormalMemoryThreshold;
final String outboundProxy;
private final String instanceId;
// private Engine engine;
private StandardServer server;
// private StandardService service;
private SipStandardEngine sipEngine;
private SipStandardService sipService;
private final InjectedValue<MBeanServer> mbeanServer = new InjectedValue<MBeanServer>();
private final InjectedValue<PathManager> pathManagerInjector = new InjectedValue<PathManager>();
public SipServerService(
final String sipAppRouterFile,
final String sipStackPropertiesFile,
final String sipPathName,
String sipAppDispatcherClass,
String additionalParameterableHeaders,
int sipCongestionControlInterval,
String congestionControlPolicy,
String sipConcurrencyControlMode,
boolean usePrettyEncoding,
int baseTimerInterval,
int t2Interval,
int t4Interval,
int timerDInterval,
boolean dialogPendingRequestChecking,
int canceledTimerTasksPurgePeriod,
int memoryThreshold,
int backToNormalMemoryThreshold,
String outboundProxy,
String instanceId) {
// this.defaultHost = defaultHost;
// this.useNative = useNative;
this.sipAppRouterFile = sipAppRouterFile;
this.sipStackPropertiesFile = sipStackPropertiesFile;
this.sipPathName = sipPathName;
this.sipAppDispatcherClass = sipAppDispatcherClass;
this.additionalParameterableHeaders = additionalParameterableHeaders;
this.sipCongestionControlInterval = sipCongestionControlInterval;
this.congestionControlPolicy = congestionControlPolicy;
this.sipConcurrencyControlMode = sipConcurrencyControlMode;
this.instanceId = instanceId;
this.usePrettyEncoding = usePrettyEncoding;
this.baseTimerInterval = baseTimerInterval;
this.t2Interval = t2Interval;
this.t4Interval = t4Interval;
this.timerDInterval = timerDInterval;
this.dialogPendingRequestChecking = dialogPendingRequestChecking;
this.canceledTimerTasksPurgePeriod = canceledTimerTasksPurgePeriod;
this.memoryThreshold = memoryThreshold;
this.backToNormalMemoryThreshold = backToNormalMemoryThreshold;
this.outboundProxy = outboundProxy;
}
/** {@inheritDoc} */
public synchronized void start(StartContext context) throws StartException {
if (org.apache.tomcat.util.Constants.ENABLE_MODELER) {
// Set the MBeanServer
final MBeanServer mbeanServer = this.mbeanServer.getOptionalValue();
if(mbeanServer != null) {
Registry.getRegistry(null, null).setMBeanServer(mbeanServer);
}
}
System.setProperty("catalina.home", pathManagerInjector.getValue().getPathEntry(TEMP_DIR).resolvePath());
final StandardServer server = new StandardServer();
// final StandardService service = new StandardService();
// service.setName(JBOSS_SIP);
// service.setServer(server);
// server.addService(service);
// final Engine engine = new StandardEngine();
// engine.setName(JBOSS_SIP);
// engine.setService(service);
// engine.setDefaultHost(defaultHost);
// if (instanceId != null) {
// engine.setJvmRoute(instanceId);
// }
//
// service.setContainer(engine);
// if (useNative) {
// final AprLifecycleListener apr = new AprLifecycleListener();
// apr.setSSLEngine("on");
// server.addLifecycleListener(apr);
// }
// server.addLifecycleListener(new JasperListener());
final SipStandardService sipService = new SipStandardService();
if (sipAppDispatcherClass != null) {
sipService.setSipApplicationDispatcherClassName(sipAppDispatcherClass);
}
else {
sipService.setSipApplicationDispatcherClassName(SipApplicationDispatcherImpl.class.getName());
}
//
- final String configDir = System.getProperty("jboss.server.config.dir");
+ final String baseDir = System.getProperty("jboss.server.base.dir");
if(sipAppRouterFile != null) {
if(!sipAppRouterFile.startsWith(FILE_PREFIX_PATH)) {
- sipAppRouterFile = FILE_PREFIX_PATH.concat(configDir).concat("/").concat(sipAppRouterFile);
+ sipAppRouterFile = FILE_PREFIX_PATH.concat(baseDir).concat("/").concat(sipAppRouterFile);
}
System.setProperty("javax.servlet.sip.dar", sipAppRouterFile);
}
//
sipService.setSipPathName(sipPathName);
//
if(sipStackPropertiesFile != null) {
if(!sipStackPropertiesFile.startsWith(FILE_PREFIX_PATH)) {
- sipStackPropertiesFile = FILE_PREFIX_PATH.concat(configDir).concat("/").concat(sipStackPropertiesFile);
+ sipStackPropertiesFile = FILE_PREFIX_PATH.concat(baseDir).concat("/").concat(sipStackPropertiesFile);
}
}
sipService.setSipStackPropertiesFile(sipStackPropertiesFile);
//
if (sipConcurrencyControlMode != null) {
sipService.setConcurrencyControlMode(sipConcurrencyControlMode);
}
else {
sipService.setConcurrencyControlMode("None");
}
//
sipService.setCongestionControlCheckingInterval(sipCongestionControlInterval);
//
sipService.setUsePrettyEncoding(usePrettyEncoding);
//
sipService.setBaseTimerInterval(baseTimerInterval);
sipService.setT2Interval(t2Interval);
sipService.setT4Interval(t4Interval);
sipService.setTimerDInterval(timerDInterval);
if(additionalParameterableHeaders != null) {
sipService.setAdditionalParameterableHeaders(additionalParameterableHeaders);
}
sipService.setDialogPendingRequestChecking(dialogPendingRequestChecking);
sipService.setCanceledTimerTasksPurgePeriod(canceledTimerTasksPurgePeriod);
sipService.setMemoryThreshold(memoryThreshold);
sipService.setBackToNormalMemoryThreshold(backToNormalMemoryThreshold);
sipService.setCongestionControlPolicy(congestionControlPolicy);
sipService.setOutboundProxy(outboundProxy);
sipService.setName(JBOSS_SIP);
sipService.setServer(server);
server.addService(sipService);
final SipStandardEngine sipEngine = new SipStandardEngine();
sipEngine.setName(JBOSS_SIP);
sipEngine.setService(sipService);
// sipEngine.setDefaultHost(defaultHost);
if (instanceId != null) {
sipEngine.setJvmRoute(instanceId);
}
sipService.setContainer(sipEngine);
try {
server.init();
server.start();
} catch (Exception e) {
throw new StartException(MESSAGES.errorStartingSip(), e);
}
this.server = server;
// this.service = service;
// this.engine = engine;
this.sipService = sipService;
this.sipEngine = sipEngine;
}
/** {@inheritDoc} */
@Override
public synchronized void stop(StopContext context) {
try {
server.stop();
} catch (Exception e) {
}
// engine = null;
// service = null;
server = null;
sipEngine = null;
sipService = null;
}
/** {@inheritDoc} */
public synchronized SipServer getValue() throws IllegalStateException {
return this;
}
/** {@inheritDoc} */
public synchronized void addConnector(Connector connector) {
if (connector.getProtocolHandler() instanceof SipProtocolHandler) {
final SipStandardService sipService = this.sipService;
sipService.addConnector(connector);
}
}
/** {@inheritDoc} */
public synchronized void removeConnector(Connector connector) {
if (connector.getProtocolHandler() instanceof SipProtocolHandler) {
final StandardService service = this.sipService;
service.removeConnector(connector);
}
}
/** {@inheritDoc} */
public synchronized void addHost(Host host) {
// final Engine engine = this.engine;
// engine.addChild(host);
final SipStandardEngine sipEngine = this.sipEngine;
sipEngine.addChild(host);
}
/** {@inheritDoc} */
public synchronized void removeHost(Host host) {
// final Engine engine = this.engine;
// engine.removeChild(host);
final SipStandardEngine sipEngine = this.sipEngine;
sipEngine.removeChild(host);
}
InjectedValue<MBeanServer> getMbeanServer() {
return mbeanServer;
}
InjectedValue<PathManager> getPathManagerInjector() {
return pathManagerInjector;
}
public StandardServer getServer() {
return server;
}
public StandardService getService() {
return sipService;
}
public SipStandardService getSipService() {
return sipService;
}
}
| false | true | public synchronized void start(StartContext context) throws StartException {
if (org.apache.tomcat.util.Constants.ENABLE_MODELER) {
// Set the MBeanServer
final MBeanServer mbeanServer = this.mbeanServer.getOptionalValue();
if(mbeanServer != null) {
Registry.getRegistry(null, null).setMBeanServer(mbeanServer);
}
}
System.setProperty("catalina.home", pathManagerInjector.getValue().getPathEntry(TEMP_DIR).resolvePath());
final StandardServer server = new StandardServer();
// final StandardService service = new StandardService();
// service.setName(JBOSS_SIP);
// service.setServer(server);
// server.addService(service);
// final Engine engine = new StandardEngine();
// engine.setName(JBOSS_SIP);
// engine.setService(service);
// engine.setDefaultHost(defaultHost);
// if (instanceId != null) {
// engine.setJvmRoute(instanceId);
// }
//
// service.setContainer(engine);
// if (useNative) {
// final AprLifecycleListener apr = new AprLifecycleListener();
// apr.setSSLEngine("on");
// server.addLifecycleListener(apr);
// }
// server.addLifecycleListener(new JasperListener());
final SipStandardService sipService = new SipStandardService();
if (sipAppDispatcherClass != null) {
sipService.setSipApplicationDispatcherClassName(sipAppDispatcherClass);
}
else {
sipService.setSipApplicationDispatcherClassName(SipApplicationDispatcherImpl.class.getName());
}
//
final String configDir = System.getProperty("jboss.server.config.dir");
if(sipAppRouterFile != null) {
if(!sipAppRouterFile.startsWith(FILE_PREFIX_PATH)) {
sipAppRouterFile = FILE_PREFIX_PATH.concat(configDir).concat("/").concat(sipAppRouterFile);
}
System.setProperty("javax.servlet.sip.dar", sipAppRouterFile);
}
//
sipService.setSipPathName(sipPathName);
//
if(sipStackPropertiesFile != null) {
if(!sipStackPropertiesFile.startsWith(FILE_PREFIX_PATH)) {
sipStackPropertiesFile = FILE_PREFIX_PATH.concat(configDir).concat("/").concat(sipStackPropertiesFile);
}
}
sipService.setSipStackPropertiesFile(sipStackPropertiesFile);
//
if (sipConcurrencyControlMode != null) {
sipService.setConcurrencyControlMode(sipConcurrencyControlMode);
}
else {
sipService.setConcurrencyControlMode("None");
}
//
sipService.setCongestionControlCheckingInterval(sipCongestionControlInterval);
//
sipService.setUsePrettyEncoding(usePrettyEncoding);
//
sipService.setBaseTimerInterval(baseTimerInterval);
sipService.setT2Interval(t2Interval);
sipService.setT4Interval(t4Interval);
sipService.setTimerDInterval(timerDInterval);
if(additionalParameterableHeaders != null) {
sipService.setAdditionalParameterableHeaders(additionalParameterableHeaders);
}
sipService.setDialogPendingRequestChecking(dialogPendingRequestChecking);
sipService.setCanceledTimerTasksPurgePeriod(canceledTimerTasksPurgePeriod);
sipService.setMemoryThreshold(memoryThreshold);
sipService.setBackToNormalMemoryThreshold(backToNormalMemoryThreshold);
sipService.setCongestionControlPolicy(congestionControlPolicy);
sipService.setOutboundProxy(outboundProxy);
sipService.setName(JBOSS_SIP);
sipService.setServer(server);
server.addService(sipService);
final SipStandardEngine sipEngine = new SipStandardEngine();
sipEngine.setName(JBOSS_SIP);
sipEngine.setService(sipService);
// sipEngine.setDefaultHost(defaultHost);
if (instanceId != null) {
sipEngine.setJvmRoute(instanceId);
}
sipService.setContainer(sipEngine);
try {
server.init();
server.start();
} catch (Exception e) {
throw new StartException(MESSAGES.errorStartingSip(), e);
}
this.server = server;
// this.service = service;
// this.engine = engine;
this.sipService = sipService;
this.sipEngine = sipEngine;
}
| public synchronized void start(StartContext context) throws StartException {
if (org.apache.tomcat.util.Constants.ENABLE_MODELER) {
// Set the MBeanServer
final MBeanServer mbeanServer = this.mbeanServer.getOptionalValue();
if(mbeanServer != null) {
Registry.getRegistry(null, null).setMBeanServer(mbeanServer);
}
}
System.setProperty("catalina.home", pathManagerInjector.getValue().getPathEntry(TEMP_DIR).resolvePath());
final StandardServer server = new StandardServer();
// final StandardService service = new StandardService();
// service.setName(JBOSS_SIP);
// service.setServer(server);
// server.addService(service);
// final Engine engine = new StandardEngine();
// engine.setName(JBOSS_SIP);
// engine.setService(service);
// engine.setDefaultHost(defaultHost);
// if (instanceId != null) {
// engine.setJvmRoute(instanceId);
// }
//
// service.setContainer(engine);
// if (useNative) {
// final AprLifecycleListener apr = new AprLifecycleListener();
// apr.setSSLEngine("on");
// server.addLifecycleListener(apr);
// }
// server.addLifecycleListener(new JasperListener());
final SipStandardService sipService = new SipStandardService();
if (sipAppDispatcherClass != null) {
sipService.setSipApplicationDispatcherClassName(sipAppDispatcherClass);
}
else {
sipService.setSipApplicationDispatcherClassName(SipApplicationDispatcherImpl.class.getName());
}
//
final String baseDir = System.getProperty("jboss.server.base.dir");
if(sipAppRouterFile != null) {
if(!sipAppRouterFile.startsWith(FILE_PREFIX_PATH)) {
sipAppRouterFile = FILE_PREFIX_PATH.concat(baseDir).concat("/").concat(sipAppRouterFile);
}
System.setProperty("javax.servlet.sip.dar", sipAppRouterFile);
}
//
sipService.setSipPathName(sipPathName);
//
if(sipStackPropertiesFile != null) {
if(!sipStackPropertiesFile.startsWith(FILE_PREFIX_PATH)) {
sipStackPropertiesFile = FILE_PREFIX_PATH.concat(baseDir).concat("/").concat(sipStackPropertiesFile);
}
}
sipService.setSipStackPropertiesFile(sipStackPropertiesFile);
//
if (sipConcurrencyControlMode != null) {
sipService.setConcurrencyControlMode(sipConcurrencyControlMode);
}
else {
sipService.setConcurrencyControlMode("None");
}
//
sipService.setCongestionControlCheckingInterval(sipCongestionControlInterval);
//
sipService.setUsePrettyEncoding(usePrettyEncoding);
//
sipService.setBaseTimerInterval(baseTimerInterval);
sipService.setT2Interval(t2Interval);
sipService.setT4Interval(t4Interval);
sipService.setTimerDInterval(timerDInterval);
if(additionalParameterableHeaders != null) {
sipService.setAdditionalParameterableHeaders(additionalParameterableHeaders);
}
sipService.setDialogPendingRequestChecking(dialogPendingRequestChecking);
sipService.setCanceledTimerTasksPurgePeriod(canceledTimerTasksPurgePeriod);
sipService.setMemoryThreshold(memoryThreshold);
sipService.setBackToNormalMemoryThreshold(backToNormalMemoryThreshold);
sipService.setCongestionControlPolicy(congestionControlPolicy);
sipService.setOutboundProxy(outboundProxy);
sipService.setName(JBOSS_SIP);
sipService.setServer(server);
server.addService(sipService);
final SipStandardEngine sipEngine = new SipStandardEngine();
sipEngine.setName(JBOSS_SIP);
sipEngine.setService(sipService);
// sipEngine.setDefaultHost(defaultHost);
if (instanceId != null) {
sipEngine.setJvmRoute(instanceId);
}
sipService.setContainer(sipEngine);
try {
server.init();
server.start();
} catch (Exception e) {
throw new StartException(MESSAGES.errorStartingSip(), e);
}
this.server = server;
// this.service = service;
// this.engine = engine;
this.sipService = sipService;
this.sipEngine = sipEngine;
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/economy/commands/CommandPay.java b/src/FE_SRC_COMMON/com/ForgeEssentials/economy/commands/CommandPay.java
index 5a84d9b0b..88a717622 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/economy/commands/CommandPay.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/economy/commands/CommandPay.java
@@ -1,106 +1,106 @@
package com.ForgeEssentials.economy.commands;
import java.util.List;
import net.minecraft.command.ICommandSender;
import net.minecraft.command.PlayerSelector;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import com.ForgeEssentials.api.economy.EconManager;
import com.ForgeEssentials.core.commands.ForgeEssentialsCommandBase;
import com.ForgeEssentials.util.FunctionHelper;
import com.ForgeEssentials.util.Localization;
import com.ForgeEssentials.util.OutputHandler;
import cpw.mods.fml.common.FMLCommonHandler;
public class CommandPay extends ForgeEssentialsCommandBase
{
@Override
public String getCommandName()
{
return "pay";
}
@Override
public void processCommandPlayer(EntityPlayer sender, String[] args)
{
if (args.length == 2)
{
EntityPlayerMP player = FunctionHelper.getPlayerForName(sender, args[0]);
if (player == null)
{
sender.sendChatToPlayer(args[0] + " not found!");
}
else
{
int amount = parseIntWithMin(sender, args[1], 0);
if (EconManager.getWallet(sender.username) >= amount)
{
EconManager.removeFromWallet(amount, sender.username);
- EconManager.addToWallet(amount, sender.username);
+ EconManager.addToWallet(amount, player.username);
OutputHandler.chatConfirmation(sender, "You have payed " + player.username + " " + amount + " " + EconManager.currency(amount));
OutputHandler.chatConfirmation(player, "You have been payed " + amount + " " + EconManager.currency(amount) + " by " + sender.getCommandSenderName());
}
else
{
OutputHandler.chatError(sender, "You can't afford that!!");
}
}
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_BADSYNTAX) + getSyntaxPlayer(sender));
}
}
@Override
public void processCommandConsole(ICommandSender sender, String[] args)
{
if (args.length == 2)
{
EntityPlayerMP player = FunctionHelper.getPlayerForName(sender, args[0]);
if (PlayerSelector.hasArguments(args[0]))
{
player = FunctionHelper.getPlayerForName(sender, args[0]);
}
if (player == null)
{
sender.sendChatToPlayer(args[0] + " not found!");
}
else
{
int amount = parseIntWithMin(sender, args[1], 0);
EconManager.addToWallet(amount, player.username);
OutputHandler.chatConfirmation(sender, "You have payed " + player.username + " " + amount + " " + EconManager.currency(amount));
OutputHandler.chatConfirmation(player, "You have been payed " + amount + " " + EconManager.currency(amount) + " by " + sender.getCommandSenderName());
}
}
else
{
sender.sendChatToPlayer(Localization.get(Localization.ERROR_BADSYNTAX) + getSyntaxConsole());
}
}
@Override
public boolean canConsoleUseCommand()
{
return true;
}
@Override
public String getCommandPerm()
{
return "ForgeEssentials.Economy." + getCommandName();
}
@Override
public List<?> addTabCompletionOptions(ICommandSender sender, String[] args)
{
if (args.length == 1)
return getListOfStringsMatchingLastWord(args, FMLCommonHandler.instance().getMinecraftServerInstance().getAllUsernames());
else
return null;
}
}
| true | true | public void processCommandPlayer(EntityPlayer sender, String[] args)
{
if (args.length == 2)
{
EntityPlayerMP player = FunctionHelper.getPlayerForName(sender, args[0]);
if (player == null)
{
sender.sendChatToPlayer(args[0] + " not found!");
}
else
{
int amount = parseIntWithMin(sender, args[1], 0);
if (EconManager.getWallet(sender.username) >= amount)
{
EconManager.removeFromWallet(amount, sender.username);
EconManager.addToWallet(amount, sender.username);
OutputHandler.chatConfirmation(sender, "You have payed " + player.username + " " + amount + " " + EconManager.currency(amount));
OutputHandler.chatConfirmation(player, "You have been payed " + amount + " " + EconManager.currency(amount) + " by " + sender.getCommandSenderName());
}
else
{
OutputHandler.chatError(sender, "You can't afford that!!");
}
}
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_BADSYNTAX) + getSyntaxPlayer(sender));
}
}
| public void processCommandPlayer(EntityPlayer sender, String[] args)
{
if (args.length == 2)
{
EntityPlayerMP player = FunctionHelper.getPlayerForName(sender, args[0]);
if (player == null)
{
sender.sendChatToPlayer(args[0] + " not found!");
}
else
{
int amount = parseIntWithMin(sender, args[1], 0);
if (EconManager.getWallet(sender.username) >= amount)
{
EconManager.removeFromWallet(amount, sender.username);
EconManager.addToWallet(amount, player.username);
OutputHandler.chatConfirmation(sender, "You have payed " + player.username + " " + amount + " " + EconManager.currency(amount));
OutputHandler.chatConfirmation(player, "You have been payed " + amount + " " + EconManager.currency(amount) + " by " + sender.getCommandSenderName());
}
else
{
OutputHandler.chatError(sender, "You can't afford that!!");
}
}
}
else
{
OutputHandler.chatError(sender, Localization.get(Localization.ERROR_BADSYNTAX) + getSyntaxPlayer(sender));
}
}
|
diff --git a/spring-boot-samples/spring-boot-sample-integration/src/test/java/org/springframework/boot/sample/integration/consumer/SampleIntegrationApplicationTests.java b/spring-boot-samples/spring-boot-sample-integration/src/test/java/org/springframework/boot/sample/integration/consumer/SampleIntegrationApplicationTests.java
index 0b0c07138b..c9143c5610 100644
--- a/spring-boot-samples/spring-boot-sample-integration/src/test/java/org/springframework/boot/sample/integration/consumer/SampleIntegrationApplicationTests.java
+++ b/spring-boot-samples/spring-boot-sample-integration/src/test/java/org/springframework/boot/sample/integration/consumer/SampleIntegrationApplicationTests.java
@@ -1,89 +1,89 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.sample.integration.consumer;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.sample.integration.SampleIntegrationApplication;
import org.springframework.boot.sample.integration.producer.ProducerApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.util.StreamUtils;
import static org.junit.Assert.assertTrue;
/**
* Basic integration tests for service demo application.
*
* @author Dave Syer
*/
public class SampleIntegrationApplicationTests {
private static ConfigurableApplicationContext context;
@BeforeClass
public static void start() throws Exception {
context = (ConfigurableApplicationContext) SpringApplication
.run(SampleIntegrationApplication.class);
}
@AfterClass
public static void stop() {
if (context != null) {
context.close();
}
}
@Test
public void testVanillaExchange() throws Exception {
SpringApplication.run(ProducerApplication.class, "World");
String output = getOutput();
assertTrue("Wrong output: " + output, output.contains("Hello World"));
}
private String getOutput() throws Exception {
Future<String> future = Executors.newSingleThreadExecutor().submit(
new Callable<String>() {
@Override
public String call() throws Exception {
Resource[] resources = new Resource[0];
while (resources.length == 0) {
Thread.sleep(200);
resources = ResourcePatternUtils.getResourcePatternResolver(
new DefaultResourceLoader()).getResources(
"file:target/output/**");
}
StringBuilder builder = new StringBuilder();
for (Resource resource : resources) {
builder.append(new String(StreamUtils
.copyToByteArray(resource.getInputStream())));
}
return builder.toString();
}
});
- return future.get(10, TimeUnit.SECONDS);
+ return future.get(30, TimeUnit.SECONDS);
}
}
| true | true | private String getOutput() throws Exception {
Future<String> future = Executors.newSingleThreadExecutor().submit(
new Callable<String>() {
@Override
public String call() throws Exception {
Resource[] resources = new Resource[0];
while (resources.length == 0) {
Thread.sleep(200);
resources = ResourcePatternUtils.getResourcePatternResolver(
new DefaultResourceLoader()).getResources(
"file:target/output/**");
}
StringBuilder builder = new StringBuilder();
for (Resource resource : resources) {
builder.append(new String(StreamUtils
.copyToByteArray(resource.getInputStream())));
}
return builder.toString();
}
});
return future.get(10, TimeUnit.SECONDS);
}
| private String getOutput() throws Exception {
Future<String> future = Executors.newSingleThreadExecutor().submit(
new Callable<String>() {
@Override
public String call() throws Exception {
Resource[] resources = new Resource[0];
while (resources.length == 0) {
Thread.sleep(200);
resources = ResourcePatternUtils.getResourcePatternResolver(
new DefaultResourceLoader()).getResources(
"file:target/output/**");
}
StringBuilder builder = new StringBuilder();
for (Resource resource : resources) {
builder.append(new String(StreamUtils
.copyToByteArray(resource.getInputStream())));
}
return builder.toString();
}
});
return future.get(30, TimeUnit.SECONDS);
}
|
diff --git a/cadpage/src/net/anei/cadpage/SmsReceiver.java b/cadpage/src/net/anei/cadpage/SmsReceiver.java
index 1a87e412a..7d0930e77 100644
--- a/cadpage/src/net/anei/cadpage/SmsReceiver.java
+++ b/cadpage/src/net/anei/cadpage/SmsReceiver.java
@@ -1,99 +1,100 @@
package net.anei.cadpage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.telephony.SmsMessage.MessageClass;
public class SmsReceiver extends BroadcastReceiver {
private static String MSG_FILENAME = "last.msg";
@Override
public void onReceive(Context context, Intent intent) {
if (Log.DEBUG) Log.v("SMSReceiver: onReceive()");
intent.setClass(context, SmsReceiverService.class);
intent.putExtra("result", getResultCode());
SmsMmsMessage message = null;
// If repeat_last flag is set, this is a fake intent instructing us
// to reprocess the most recently recieved message (that passed the
// sender address filter
if (intent.getBooleanExtra("repeat_last", false)) {
ObjectInputStream is = null;
try {
is = new ObjectInputStream(
context.openFileInput(MSG_FILENAME));
message = SmsMmsMessage.readObject(context, is);
} catch (FileNotFoundException ex) {
} catch (Exception ex) {
Log.e(ex);
} finally {
if (is != null) try {is.close();} catch (IOException ex) {}
}
}
// Otherwise convert Intent into an SMS/MSS message
else {
SmsMessage[] messages = SmsPopupUtils.getMessagesFromIntent(intent);
+ if (messages == null) return;
message = new SmsMmsMessage(context, messages,System.currentTimeMillis());
}
// And determine if this is a CAD Page call
if (message != null && cadPageCall(context, message)){
// If it is, abort broadcast to any other receivers
// and launch the main page with this message
abortBroadcast();
CallHistoryActivity.launchActivity(context, message);
}
}
/**
* Determine if this intent message is a CAD page call
* @param context message context
* @param intent Intent
* @return true if message is a CAD page call that should be processed further
*/
private boolean cadPageCall(Context context, SmsMmsMessage message){
String strMessage = message.getMessageFull();
// Class 0 SMS, let the system handle this
if (message.getMessageType() == SmsMmsMessage.MESSAGE_TYPE_SMS &&
message.getMessageClass() == MessageClass.CLASS_0) return false;
// First look at from Filter.
String sFilter = ManagePreferences.filter();
String sAddress = message.getAddress();
if (! match(sAddress, sFilter)) return false;
if (Log.DEBUG) Log.v("SMSReceiver/CadPageCall: Filter Matches checking call Location -" + sFilter);
// Save message to file for future test use
ObjectOutputStream os = null;
try {
os = new ObjectOutputStream(
context.openFileOutput(MSG_FILENAME, Context.MODE_PRIVATE));
os.writeObject(message);
} catch (IOException ex) {
Log.e(ex);
} finally {
if (os != null) try {os.close();} catch (IOException ex) {}
}
return SmsMsgParser.isPageMsg(strMessage);
}
private boolean match(String address, String filter) {
return (filter == null || filter.length() == 0 ||
filter.equals("*") || address.contains(filter));
}
}
| true | true | public void onReceive(Context context, Intent intent) {
if (Log.DEBUG) Log.v("SMSReceiver: onReceive()");
intent.setClass(context, SmsReceiverService.class);
intent.putExtra("result", getResultCode());
SmsMmsMessage message = null;
// If repeat_last flag is set, this is a fake intent instructing us
// to reprocess the most recently recieved message (that passed the
// sender address filter
if (intent.getBooleanExtra("repeat_last", false)) {
ObjectInputStream is = null;
try {
is = new ObjectInputStream(
context.openFileInput(MSG_FILENAME));
message = SmsMmsMessage.readObject(context, is);
} catch (FileNotFoundException ex) {
} catch (Exception ex) {
Log.e(ex);
} finally {
if (is != null) try {is.close();} catch (IOException ex) {}
}
}
// Otherwise convert Intent into an SMS/MSS message
else {
SmsMessage[] messages = SmsPopupUtils.getMessagesFromIntent(intent);
message = new SmsMmsMessage(context, messages,System.currentTimeMillis());
}
// And determine if this is a CAD Page call
if (message != null && cadPageCall(context, message)){
// If it is, abort broadcast to any other receivers
// and launch the main page with this message
abortBroadcast();
CallHistoryActivity.launchActivity(context, message);
}
}
| public void onReceive(Context context, Intent intent) {
if (Log.DEBUG) Log.v("SMSReceiver: onReceive()");
intent.setClass(context, SmsReceiverService.class);
intent.putExtra("result", getResultCode());
SmsMmsMessage message = null;
// If repeat_last flag is set, this is a fake intent instructing us
// to reprocess the most recently recieved message (that passed the
// sender address filter
if (intent.getBooleanExtra("repeat_last", false)) {
ObjectInputStream is = null;
try {
is = new ObjectInputStream(
context.openFileInput(MSG_FILENAME));
message = SmsMmsMessage.readObject(context, is);
} catch (FileNotFoundException ex) {
} catch (Exception ex) {
Log.e(ex);
} finally {
if (is != null) try {is.close();} catch (IOException ex) {}
}
}
// Otherwise convert Intent into an SMS/MSS message
else {
SmsMessage[] messages = SmsPopupUtils.getMessagesFromIntent(intent);
if (messages == null) return;
message = new SmsMmsMessage(context, messages,System.currentTimeMillis());
}
// And determine if this is a CAD Page call
if (message != null && cadPageCall(context, message)){
// If it is, abort broadcast to any other receivers
// and launch the main page with this message
abortBroadcast();
CallHistoryActivity.launchActivity(context, message);
}
}
|
diff --git a/src/main/java/hudson/plugins/analysis/graph/DefaultGraphConfigurationView.java b/src/main/java/hudson/plugins/analysis/graph/DefaultGraphConfigurationView.java
index 7ce1d6e..7a93203 100644
--- a/src/main/java/hudson/plugins/analysis/graph/DefaultGraphConfigurationView.java
+++ b/src/main/java/hudson/plugins/analysis/graph/DefaultGraphConfigurationView.java
@@ -1,92 +1,92 @@
package hudson.plugins.analysis.graph;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import hudson.model.AbstractProject;
import hudson.plugins.analysis.Messages;
import hudson.plugins.analysis.core.BuildHistory;
/**
* Configures the default values for the trend graph of this plug-in.
*/
public class DefaultGraphConfigurationView extends GraphConfigurationView {
private final String url;
/**
* Creates a new instance of {@link DefaultGraphConfigurationView}.
*
* @param configuration
* the graph configuration
* @param project
* the owning project to configure the graphs for
* @param pluginName
* The URL of the project action (there might be a one to many mapping to this defaults view)
* @param buildHistory
* the build history for this project
* @param url
* The URL of this view
*/
public DefaultGraphConfigurationView(final GraphConfiguration configuration, final AbstractProject<?, ?> project,
final String pluginName, final BuildHistory buildHistory, final String url) {
super(configuration, project, pluginName, buildHistory);
this.url = url;
configuration.initializeFromFile(createDefaultsFile(project, pluginName));
}
/**
* Creates a new instance of {@link DefaultGraphConfigurationView}.
*
* @param configuration
* the graph configuration
* @param project
* the owning project to configure the graphs for
* @param pluginName
* The name of the plug-in.
* @param buildHistory
* the build history for this project
*/
public DefaultGraphConfigurationView(final GraphConfiguration configuration, final AbstractProject<?, ?> project,
final String pluginName, final BuildHistory buildHistory) {
this(configuration, project, pluginName, buildHistory,
project.getAbsoluteUrl() + pluginName + "/configureDefaults");
}
/** {@inheritDoc} */
public String getDisplayName() {
return Messages.DefaultGraphConfiguration_Name();
}
@Override
public String getDescription() {
return Messages.DefaultGraphConfiguration_Description();
}
/**
* Returns the URL of this object.
*
* @return the URL of this object
*/
public String getUrl() {
return url;
}
@Override
protected void persistValue(final String value, final String pluginName, final StaplerRequest request, final StaplerResponse response) throws FileNotFoundException, IOException {
- FileOutputStream output = new FileOutputStream(createDefaultsFile(getOwner(), getKey()));
+ FileOutputStream output = new FileOutputStream(createDefaultsFile(getOwner(), pluginName));
try {
IOUtils.write(value, output);
}
finally {
output.close();
}
}
}
| true | true | protected void persistValue(final String value, final String pluginName, final StaplerRequest request, final StaplerResponse response) throws FileNotFoundException, IOException {
FileOutputStream output = new FileOutputStream(createDefaultsFile(getOwner(), getKey()));
try {
IOUtils.write(value, output);
}
finally {
output.close();
}
}
| protected void persistValue(final String value, final String pluginName, final StaplerRequest request, final StaplerResponse response) throws FileNotFoundException, IOException {
FileOutputStream output = new FileOutputStream(createDefaultsFile(getOwner(), pluginName));
try {
IOUtils.write(value, output);
}
finally {
output.close();
}
}
|
diff --git a/testit/de/uni_koblenz/jgralabtest/greql2/SystemTest.java b/testit/de/uni_koblenz/jgralabtest/greql2/SystemTest.java
index bc16fb2d7..643f83640 100644
--- a/testit/de/uni_koblenz/jgralabtest/greql2/SystemTest.java
+++ b/testit/de/uni_koblenz/jgralabtest/greql2/SystemTest.java
@@ -1,167 +1,168 @@
/*
* JGraLab - The Java Graph Laboratory
*
* Copyright (C) 2006-2011 Institute for Software Technology
* University of Koblenz-Landau, Germany
* [email protected]
*
* For bug reports, documentation and further information, visit
*
* http://jgralab.uni-koblenz.de
*
* 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>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining
* it with Eclipse (or a modified version of that program or an Eclipse
* plugin), containing parts covered by the terms of the Eclipse Public
* License (EPL), the licensors of this Program grant you additional
* permission to convey the resulting work. Corresponding Source for a
* non-source form of such a combination shall include the source code for
* the parts of JGraLab used as well as that of the covered work.
*/
package de.uni_koblenz.jgralabtest.greql2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import de.uni_koblenz.jgralab.Edge;
import de.uni_koblenz.jgralab.EdgeDirection;
import de.uni_koblenz.jgralab.Graph;
import de.uni_koblenz.jgralab.Vertex;
import de.uni_koblenz.jgralab.greql2.jvalue.JValue;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueBag;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueCollection;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueImpl;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueList;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueTable;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueTuple;
import de.uni_koblenz.jgralab.greql2.parser.GreqlParser;
import de.uni_koblenz.jgralabtest.schemas.greqltestschema.connections.Way;
public class SystemTest extends GenericTest {
@Override
protected Graph createGreqlTestGraph() {
int count = 1;
String part1 = "from i:a report ";
String part2 = " end where q:=a, l:=a, m:=a, n:=a, o:=a, p:=a, k:= a, j:=a, h := a, g := a, f:= a, e := a, d:=a, c:=a, b:=a, a:=4";
StringBuilder queryString = new StringBuilder();
for (int i = 0; i < count; i++) { // 65
queryString.append(part1);
}
queryString
.append(" add(i, mul( a, sub(b, mod( c, sub( d, add( e)))))) ");
for (int i = 0; i < count; i++) {
queryString.append(part2);
}
return GreqlParser.parse(queryString.toString());
}
@Test
public void testFunctionArgumentsEvaluation() throws Exception {
String queryString = "from x:V{FunctionApplication}, y:V{Expression} with x <--{IsArgumentOf} y report tup( tup(\"Function: \", x ), tup(\"Argument: \", y )) end";
JValue result = evalTestQuery("FunctionArgumentsEvaluation",
queryString);
assertEquals(11, result.toCollection().size());
}
@Test
public void testFunctionAsFunctionArgumentEvaluation() throws Exception {
String queryString = "from x:V{FunctionApplication}, y:V{FunctionApplication} with x <--{IsArgumentOf} y report tup( tup(\"Function: \", x ), tup(\"Argument: \", y )) end";
JValue result = evalTestQuery("FunctionAsFunctionArgumentEvaluation",
queryString);
assertEquals(5, result.toCollection().size());
}
@Test
public void testFunctionAsFunctionArgumentAsFuntionArgumentEvaluation()
throws Exception {
String queryString = "from x:V{FunctionApplication}, y:V{FunctionApplication} with x <--{IsArgumentOf} <--{IsArgumentOf} y report tup( tup(\"Function: \", x ), tup(\"Argument: \", y )) end";
JValue result = evalTestQuery(
"FunctionAsFunctionAsFunctionArgumentEvaluation", queryString);
assertEquals(4, result.toCollection().size());
}
@Test
public void testFunctionAsArgumentInBagComprehensionEvaluation()
throws Exception {
String queryString = "from x:V{FunctionApplication}, y:V{BagComprehension} with x -->{IsArgumentOf}+ -->{IsCompResultDefOf} y report tup(tup(\"Function: \", x ), tup(\"BagComprehension: \", y )) end";
JValue result = evalTestQuery("FunctionAsArgumentInBagComprehension",
queryString);
assertEquals(5, result.toCollection().size());
}
@Test
public void test() throws Exception {
String X1 = "X1";
String X2 = "X2";
String queryString = "from x:V{junctions.Crossroad}, y:V{junctions.Crossroad} "
+ "with x -->{connections.Street} <--{connections.Footpath} y report id(x) as '"
+ X1 + "', id(y) as '" + X2 + "' end";
JValueTable result = evalTestQuery(queryString).toJValueTable();
checkHeader(result, X1, X2);
assertEquals(12, result.size());
}
private void checkHeader(JValueTable table, String... headerStrings) {
JValueList header = table.getHeader().toJValueList();
for (String headerString : headerStrings) {
assertTrue(header.remove(new JValueImpl(headerString)));
}
assertTrue(header.isEmpty());
}
@Test
public void testCrossroadWithUsage() throws Exception {
String VERTEX = "Vertex";
String IDENTIFIER = "Identifier";
String USAGE_COUNT = "UsageCount";
String USAGES = "Usages";
String queryString = "from c:V{junctions.Crossroad} report c as '"
+ VERTEX + "', id(c) as '" + IDENTIFIER + "', "
+ "outDegree{connections.Way}(c) as '" + USAGE_COUNT + "', "
+ "edgesFrom(c) as '" + USAGES + "' end";
JValueTable result = evalTestQuery(queryString).toJValueTable();
JValueBag data = result.getData().toJValueBag();
checkHeader(result, VERTEX, IDENTIFIER, USAGE_COUNT, USAGES);
for (JValue value : data) {
JValueTuple tuple = value.toJValueTuple();
Vertex vertex = tuple.get(0).toVertex();
int identifier = tuple.get(1).toInteger().intValue();
int usage_count = tuple.get(2).toInteger().intValue();
JValueCollection usages = tuple.get(3).toCollection();
assertEquals(vertex.getId(), identifier);
- assertEquals(vertex.getDegree(EdgeDirection.OUT), usage_count);
+ assertEquals(vertex.getDegree(Way.class, EdgeDirection.OUT),
+ usage_count);
for (Edge edge : vertex.incidences(Way.class, EdgeDirection.OUT)) {
assertTrue(usages.remove(new JValueImpl(edge)));
}
assertTrue(usages.isEmpty());
}
assertEquals(crossroadCount, result.size());
}
}
| true | true | public void testCrossroadWithUsage() throws Exception {
String VERTEX = "Vertex";
String IDENTIFIER = "Identifier";
String USAGE_COUNT = "UsageCount";
String USAGES = "Usages";
String queryString = "from c:V{junctions.Crossroad} report c as '"
+ VERTEX + "', id(c) as '" + IDENTIFIER + "', "
+ "outDegree{connections.Way}(c) as '" + USAGE_COUNT + "', "
+ "edgesFrom(c) as '" + USAGES + "' end";
JValueTable result = evalTestQuery(queryString).toJValueTable();
JValueBag data = result.getData().toJValueBag();
checkHeader(result, VERTEX, IDENTIFIER, USAGE_COUNT, USAGES);
for (JValue value : data) {
JValueTuple tuple = value.toJValueTuple();
Vertex vertex = tuple.get(0).toVertex();
int identifier = tuple.get(1).toInteger().intValue();
int usage_count = tuple.get(2).toInteger().intValue();
JValueCollection usages = tuple.get(3).toCollection();
assertEquals(vertex.getId(), identifier);
assertEquals(vertex.getDegree(EdgeDirection.OUT), usage_count);
for (Edge edge : vertex.incidences(Way.class, EdgeDirection.OUT)) {
assertTrue(usages.remove(new JValueImpl(edge)));
}
assertTrue(usages.isEmpty());
}
assertEquals(crossroadCount, result.size());
}
| public void testCrossroadWithUsage() throws Exception {
String VERTEX = "Vertex";
String IDENTIFIER = "Identifier";
String USAGE_COUNT = "UsageCount";
String USAGES = "Usages";
String queryString = "from c:V{junctions.Crossroad} report c as '"
+ VERTEX + "', id(c) as '" + IDENTIFIER + "', "
+ "outDegree{connections.Way}(c) as '" + USAGE_COUNT + "', "
+ "edgesFrom(c) as '" + USAGES + "' end";
JValueTable result = evalTestQuery(queryString).toJValueTable();
JValueBag data = result.getData().toJValueBag();
checkHeader(result, VERTEX, IDENTIFIER, USAGE_COUNT, USAGES);
for (JValue value : data) {
JValueTuple tuple = value.toJValueTuple();
Vertex vertex = tuple.get(0).toVertex();
int identifier = tuple.get(1).toInteger().intValue();
int usage_count = tuple.get(2).toInteger().intValue();
JValueCollection usages = tuple.get(3).toCollection();
assertEquals(vertex.getId(), identifier);
assertEquals(vertex.getDegree(Way.class, EdgeDirection.OUT),
usage_count);
for (Edge edge : vertex.incidences(Way.class, EdgeDirection.OUT)) {
assertTrue(usages.remove(new JValueImpl(edge)));
}
assertTrue(usages.isEmpty());
}
assertEquals(crossroadCount, result.size());
}
|
diff --git a/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/template/SelectStudyController.java b/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/template/SelectStudyController.java
index 1aa6e1568..9ff9c42df 100644
--- a/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/template/SelectStudyController.java
+++ b/web/src/main/java/edu/northwestern/bioinformatics/studycalendar/web/template/SelectStudyController.java
@@ -1,77 +1,78 @@
package edu.northwestern.bioinformatics.studycalendar.web.template;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Epoch;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySegment;
import edu.northwestern.bioinformatics.studycalendar.service.DeltaService;
import edu.northwestern.bioinformatics.studycalendar.web.accesscontrol.PscAuthorizedHandler;
import edu.northwestern.bioinformatics.studycalendar.web.accesscontrol.ResourceAuthorization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import static edu.northwestern.bioinformatics.studycalendar.security.authorization.PscRole.STUDY_CALENDAR_TEMPLATE_BUILDER;
/**
* @author Saurabh Agrawal
*/
public class SelectStudyController implements Controller, PscAuthorizedHandler {
private DeltaService deltaService;
private StudyDao studyDao;
private static final Logger log = LoggerFactory.getLogger(SelectStudyController.class.getName());
public Collection<ResourceAuthorization> authorizations(String httpMethod, Map<String, String[]> queryParameters) {
return ResourceAuthorization.createCollection(STUDY_CALENDAR_TEMPLATE_BUILDER);
}
@SuppressWarnings({"unchecked"})
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
int id = ServletRequestUtils.getRequiredIntParameter(request, "study");
Study study = studyDao.getById(id);
Study theRevisedStudy = null;
if (study.isReleased()) {
//user has selected the releaesd template so dont revise the study
theRevisedStudy = study;
} else if (study.isInDevelopment() && study.getDevelopmentAmendment() != null) {
theRevisedStudy = deltaService.revise(study, study.getDevelopmentAmendment());
} else {
theRevisedStudy = study;
}
List<Epoch> epochs = theRevisedStudy.getPlannedCalendar().getEpochs();
List<Epoch> displayEpochs = new LinkedList<Epoch>();
for (Epoch epoch : epochs) {
List<StudySegment> studySegments = epoch.getStudySegments();
for (StudySegment studySegment : studySegments) {
if (!studySegment.getPeriods().isEmpty()) {
displayEpochs.add(epoch);
break;
}
}
}
Map model = new HashMap();
+ model.put("study", theRevisedStudy);
model.put("epochs", displayEpochs);
return new ModelAndView("template/ajax/displayEpochs", model);
}
@Required
public void setDeltaService(DeltaService deltaService) {
this.deltaService = deltaService;
}
@Required
public void setStudyDao(final StudyDao studyDao) {
this.studyDao = studyDao;
}
}
| true | true | public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
int id = ServletRequestUtils.getRequiredIntParameter(request, "study");
Study study = studyDao.getById(id);
Study theRevisedStudy = null;
if (study.isReleased()) {
//user has selected the releaesd template so dont revise the study
theRevisedStudy = study;
} else if (study.isInDevelopment() && study.getDevelopmentAmendment() != null) {
theRevisedStudy = deltaService.revise(study, study.getDevelopmentAmendment());
} else {
theRevisedStudy = study;
}
List<Epoch> epochs = theRevisedStudy.getPlannedCalendar().getEpochs();
List<Epoch> displayEpochs = new LinkedList<Epoch>();
for (Epoch epoch : epochs) {
List<StudySegment> studySegments = epoch.getStudySegments();
for (StudySegment studySegment : studySegments) {
if (!studySegment.getPeriods().isEmpty()) {
displayEpochs.add(epoch);
break;
}
}
}
Map model = new HashMap();
model.put("epochs", displayEpochs);
return new ModelAndView("template/ajax/displayEpochs", model);
}
| public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
int id = ServletRequestUtils.getRequiredIntParameter(request, "study");
Study study = studyDao.getById(id);
Study theRevisedStudy = null;
if (study.isReleased()) {
//user has selected the releaesd template so dont revise the study
theRevisedStudy = study;
} else if (study.isInDevelopment() && study.getDevelopmentAmendment() != null) {
theRevisedStudy = deltaService.revise(study, study.getDevelopmentAmendment());
} else {
theRevisedStudy = study;
}
List<Epoch> epochs = theRevisedStudy.getPlannedCalendar().getEpochs();
List<Epoch> displayEpochs = new LinkedList<Epoch>();
for (Epoch epoch : epochs) {
List<StudySegment> studySegments = epoch.getStudySegments();
for (StudySegment studySegment : studySegments) {
if (!studySegment.getPeriods().isEmpty()) {
displayEpochs.add(epoch);
break;
}
}
}
Map model = new HashMap();
model.put("study", theRevisedStudy);
model.put("epochs", displayEpochs);
return new ModelAndView("template/ajax/displayEpochs", model);
}
|
diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/AnnotationScanningServletContainerInitializer.java b/modules/cpr/src/main/java/org/atmosphere/cpr/AnnotationScanningServletContainerInitializer.java
index 1649eddc0..c8b6557f6 100644
--- a/modules/cpr/src/main/java/org/atmosphere/cpr/AnnotationScanningServletContainerInitializer.java
+++ b/modules/cpr/src/main/java/org/atmosphere/cpr/AnnotationScanningServletContainerInitializer.java
@@ -1,72 +1,74 @@
package org.atmosphere.cpr;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import org.atmosphere.config.service.AsyncSupportListenerService;
import org.atmosphere.config.service.AsyncSupportService;
import org.atmosphere.config.service.AtmosphereHandlerService;
import org.atmosphere.config.service.AtmosphereInterceptorService;
import org.atmosphere.config.service.BroadcasterCacheInspectorService;
import org.atmosphere.config.service.BroadcasterCacheService;
import org.atmosphere.config.service.BroadcasterFactoryService;
import org.atmosphere.config.service.BroadcasterFilterService;
import org.atmosphere.config.service.BroadcasterListenerService;
import org.atmosphere.config.service.BroadcasterService;
import org.atmosphere.config.service.EndpoinMapperService;
import org.atmosphere.config.service.ManagedService;
import org.atmosphere.config.service.MeteorService;
import org.atmosphere.config.service.WebSocketHandlerService;
import org.atmosphere.config.service.WebSocketProcessorService;
import org.atmosphere.config.service.WebSocketProtocolService;
/**
* A ServletContainerInitializer that scans for annotations, and places them in a map keyed by annotation type in the
* servlet context.
*
* @author Stuart Douglas
*/
@HandlesTypes({
AtmosphereHandlerService.class,
BroadcasterCacheService.class,
BroadcasterFilterService.class,
BroadcasterFactoryService.class,
BroadcasterService.class,
MeteorService.class,
WebSocketHandlerService.class,
WebSocketProtocolService.class,
AtmosphereInterceptorService.class,
BroadcasterListenerService.class,
AsyncSupportService.class,
AsyncSupportListenerService.class,
WebSocketProcessorService.class,
BroadcasterCacheInspectorService.class,
ManagedService.class,
EndpoinMapperService.class,
})
public class AnnotationScanningServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(final Set<Class<?>> classes, final ServletContext servletContext) throws ServletException {
final Map<Class<? extends Annotation>, Set<Class<?>>> classesByAnnotation = new HashMap<Class<? extends Annotation>, Set<Class<?>>>();
- for(final Class<?> clazz : classes) {
- for(Annotation annotation : clazz.getAnnotations()) {
- Set<Class<?>> classSet = classesByAnnotation.get(annotation.annotationType());
- if(classSet == null) {
- classesByAnnotation.put(annotation.annotationType(), classSet = new HashSet<Class<?>>());
+ if (classes != null) {
+ for(final Class<?> clazz : classes) {
+ for(Annotation annotation : clazz.getAnnotations()) {
+ Set<Class<?>> classSet = classesByAnnotation.get(annotation.annotationType());
+ if(classSet == null) {
+ classesByAnnotation.put(annotation.annotationType(), classSet = new HashSet<Class<?>>());
+ }
+ classSet.add(clazz);
}
- classSet.add(clazz);
}
}
servletContext.setAttribute(DefaultAnnotationProcessor.ANNOTATION_ATTRIBUTE, Collections.unmodifiableMap(classesByAnnotation));
}
}
| false | true | public void onStartup(final Set<Class<?>> classes, final ServletContext servletContext) throws ServletException {
final Map<Class<? extends Annotation>, Set<Class<?>>> classesByAnnotation = new HashMap<Class<? extends Annotation>, Set<Class<?>>>();
for(final Class<?> clazz : classes) {
for(Annotation annotation : clazz.getAnnotations()) {
Set<Class<?>> classSet = classesByAnnotation.get(annotation.annotationType());
if(classSet == null) {
classesByAnnotation.put(annotation.annotationType(), classSet = new HashSet<Class<?>>());
}
classSet.add(clazz);
}
}
servletContext.setAttribute(DefaultAnnotationProcessor.ANNOTATION_ATTRIBUTE, Collections.unmodifiableMap(classesByAnnotation));
}
| public void onStartup(final Set<Class<?>> classes, final ServletContext servletContext) throws ServletException {
final Map<Class<? extends Annotation>, Set<Class<?>>> classesByAnnotation = new HashMap<Class<? extends Annotation>, Set<Class<?>>>();
if (classes != null) {
for(final Class<?> clazz : classes) {
for(Annotation annotation : clazz.getAnnotations()) {
Set<Class<?>> classSet = classesByAnnotation.get(annotation.annotationType());
if(classSet == null) {
classesByAnnotation.put(annotation.annotationType(), classSet = new HashSet<Class<?>>());
}
classSet.add(clazz);
}
}
}
servletContext.setAttribute(DefaultAnnotationProcessor.ANNOTATION_ATTRIBUTE, Collections.unmodifiableMap(classesByAnnotation));
}
|
diff --git a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/WebServiceConsumer1.java b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/WebServiceConsumer1.java
index a10d244..f29066a 100644
--- a/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/WebServiceConsumer1.java
+++ b/tests/org.jboss.tools.esb.ui.bot.test/src/org/jboss/tools/esb/ui/bot/tests/examples/WebServiceConsumer1.java
@@ -1,34 +1,34 @@
package org.jboss.tools.esb.ui.bot.tests.examples;
import org.jboss.tools.ui.bot.ext.config.Annotations.SWTBotTestRequires;
import org.jboss.tools.ui.bot.ext.config.Annotations.Server;
import org.jboss.tools.ui.bot.ext.config.Annotations.ServerState;
import org.jboss.tools.ui.bot.ext.config.Annotations.ServerType;
@SWTBotTestRequires(server=@Server(type=ServerType.SOA,state=ServerState.Running))
public class WebServiceConsumer1 extends ESBExampleTest {
@Override
public String getExampleName() {
return "JBoss ESB Web Service consumer1 Example";
}
@Override
public String getExampleProjectName() {
return "webservice_consumer1";
}
@Override
public String getExampleClientProjectName() {
return "webservice_consumer1_client";
}
@Override
protected void executeExample() {
super.executeExample();
String text = executeClientGetServerOutput(getExampleClientProjectName(),"src","org.jboss.soa.esb.samples.quickstart.webservice_consumer1.test","SendJMSMessage.java");
assertNotNull("Calling JMS Send message failed, nothing appened to server log",text);
- assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Hello World Greeting for 'JMS'"));
+ assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Hello World Greeting for"));
text = null;
text = executeClientGetServerOutput(getExampleClientProjectName(),"src","org.jboss.soa.esb.samples.quickstart.webservice_consumer1.test","SendEsbMessage.java");
assertNotNull("Calling ESB Send message failed, nothing appened to server log",text);
- assertTrue("Calling ESB Send message failed, unexpected server output :"+text,text.contains("Hello World Greeting for 'ESB'"));
+ assertTrue("Calling ESB Send message failed, unexpected server output :"+text,text.contains("Hello World Greeting for"));
}
}
| false | true | protected void executeExample() {
super.executeExample();
String text = executeClientGetServerOutput(getExampleClientProjectName(),"src","org.jboss.soa.esb.samples.quickstart.webservice_consumer1.test","SendJMSMessage.java");
assertNotNull("Calling JMS Send message failed, nothing appened to server log",text);
assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Hello World Greeting for 'JMS'"));
text = null;
text = executeClientGetServerOutput(getExampleClientProjectName(),"src","org.jboss.soa.esb.samples.quickstart.webservice_consumer1.test","SendEsbMessage.java");
assertNotNull("Calling ESB Send message failed, nothing appened to server log",text);
assertTrue("Calling ESB Send message failed, unexpected server output :"+text,text.contains("Hello World Greeting for 'ESB'"));
}
| protected void executeExample() {
super.executeExample();
String text = executeClientGetServerOutput(getExampleClientProjectName(),"src","org.jboss.soa.esb.samples.quickstart.webservice_consumer1.test","SendJMSMessage.java");
assertNotNull("Calling JMS Send message failed, nothing appened to server log",text);
assertTrue("Calling JMS Send message failed, unexpected server output :"+text,text.contains("Hello World Greeting for"));
text = null;
text = executeClientGetServerOutput(getExampleClientProjectName(),"src","org.jboss.soa.esb.samples.quickstart.webservice_consumer1.test","SendEsbMessage.java");
assertNotNull("Calling ESB Send message failed, nothing appened to server log",text);
assertTrue("Calling ESB Send message failed, unexpected server output :"+text,text.contains("Hello World Greeting for"));
}
|
diff --git a/src/GUI/MainWindow.java b/src/GUI/MainWindow.java
index d741791..de7aee0 100644
--- a/src/GUI/MainWindow.java
+++ b/src/GUI/MainWindow.java
@@ -1,701 +1,702 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import business.Output;
import java.awt.Color;
import java.awt.Event;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileReader;
import java.util.Scanner;
import javax.swing.JFileChooser;
import javax.swing.text.Document;
import javax.swing.undo.*;
import java.lang.Object;
import controller.Controller;
import deliver.Deliver;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.BadLocationException;
import javax.swing.undo.CannotUndoException;
/**
*
* @author Kiwi
*/
public class MainWindow extends javax.swing.JFrame {
//Colores para letras
public static final Color Red = new Color(255, 0, 0);
public static final Color Black = new Color(0, 0, 0);
public static final Color Gray = new Color(109, 109, 109);
Image icon = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons2/icon-kiwi.png"));
//<editor-fold defaultstate="collapsed" desc=" Undo & Redo part1 ">
private Document editorPaneDocument;
protected UndoHandler undoHandler = new UndoHandler();
protected UndoManager undoManager = new UndoManager();
private UndoAction undoAction = null;
private RedoAction redoAction = null;
//</editor-fold>
/**
* Creates new form NewJFrame
*/
public MainWindow() {
initComponents();
setExtendedState(JFrame.MAXIMIZED_BOTH);
setIconImage(icon);
editorPaneDocument = syntaxArea.getDocument();
editorPaneDocument.addUndoableEditListener(undoHandler);
KeyStroke undoKeystroke = KeyStroke.getKeyStroke("control Z");
KeyStroke redoKeystroke = KeyStroke.getKeyStroke("control Y");
undoAction = new UndoAction();
syntaxArea.getInputMap().put(undoKeystroke, "undoKeystroke");
syntaxArea.getActionMap().put("undoKeystroke", undoAction);
redoAction = new RedoAction();
syntaxArea.getInputMap().put(redoKeystroke, "redoKeystroke");
syntaxArea.getActionMap().put("redoKeystroke", redoAction);
// Edit menu
JMenu editMenu = new JMenu("Edit");
JMenuItem undoMenuItem = new JMenuItem(undoAction);
JMenuItem redoMenuItem = new JMenuItem(redoAction);
editMenu.add(undoMenuItem);
editMenu.add(redoMenuItem);
Deliver.setDestination(this);
}
public void setSyntaxText(String text) {
//syntaxArea.append(text);
insertText(syntaxArea, text);
}
public void setEventText(String text) {
insertText(eventArea, text);
}
//<editor-fold defaultstate="collapsed" desc=" Undo & Redo part2">
class UndoHandler implements UndoableEditListener {
/**
* Messaged when the Document has created an edit, the edit is added to
* <code>undoManager</code>, an instance of UndoManager.
*/
@Override
public void undoableEditHappened(UndoableEditEvent e) {
undoManager.addEdit(e.getEdit());
undoAction.update();
redoAction.update();
}
}
class UndoAction extends AbstractAction {
public UndoAction() {
super("Undo");
setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undoManager.undo();
} catch (CannotUndoException ex) {
// TODO deal with this
//ex.printStackTrace();
}
update();
redoAction.update();
}
protected void update() {
if (undoManager.canUndo()) {
setEnabled(true);
putValue(Action.NAME, undoManager.getUndoPresentationName());
} else {
setEnabled(false);
putValue(Action.NAME, "Undo");
}
}
}
class RedoAction extends AbstractAction {
public RedoAction() {
super("Redo");
setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
try {
undoManager.redo();
} catch (CannotRedoException ex) {
// TODO deal with this
ex.printStackTrace();
}
update();
undoAction.update();
}
protected void update() {
if (undoManager.canRedo()) {
setEnabled(true);
putValue(Action.NAME, undoManager.getRedoPresentationName());
} else {
setEnabled(false);
putValue(Action.NAME, "Redo");
}
}
}
//</editor-fold>
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jFileChooser1 = new javax.swing.JFileChooser();
jFrame1 = new javax.swing.JFrame();
jLabel1 = new javax.swing.JLabel();
jSplitPane1 = new javax.swing.JSplitPane();
jScrollPane2 = new javax.swing.JScrollPane();
syntaxArea = new javax.swing.JTextArea();
jScrollPane1 = new javax.swing.JScrollPane();
eventArea = new javax.swing.JTextArea();
LoadEvent = new javax.swing.JButton();
LoadSyntax = new javax.swing.JButton();
SaveSyntax = new javax.swing.JButton();
NVariable = new javax.swing.JButton();
NOperation = new javax.swing.JButton();
NDataBase = new javax.swing.JButton();
NTable = new javax.swing.JButton();
deshacer = new javax.swing.JButton();
editar = new javax.swing.JToggleButton();
rehacer = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jFrame1.setBounds(new java.awt.Rectangle(0, 0, 225, 206));
jFrame1.setLocationByPlatform(true);
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("<html><img src=\"http://farm4.staticflickr.com/3227/3115937621_650616f2b0.jpg\" width=210 height=180></html>");
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 15, Short.MAX_VALUE))
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(38, Short.MAX_VALUE))
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("KiwiSyntaxManager");
setFocusCycleRoot(false);
setLocationByPlatform(true);
jSplitPane1.setResizeWeight(0.5);
jScrollPane2.setToolTipText("");
syntaxArea.setColumns(20);
syntaxArea.setRows(5);
jScrollPane2.setViewportView(syntaxArea);
jSplitPane1.setRightComponent(jScrollPane2);
eventArea.setColumns(20);
eventArea.setRows(5);
jScrollPane1.setViewportView(eventArea);
jSplitPane1.setLeftComponent(jScrollPane1);
LoadEvent.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_lightning.png"))); // NOI18N
LoadEvent.setToolTipText("Load Event");
LoadEvent.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadEventActionPerformed(evt);
}
});
LoadSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_put.png"))); // NOI18N
LoadSyntax.setToolTipText("Load Syntax");
LoadSyntax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadSyntaxActionPerformed(evt);
}
});
SaveSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/disk.png"))); // NOI18N
SaveSyntax.setToolTipText("Save");
SaveSyntax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveSyntaxActionPerformed(evt);
}
});
NVariable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/tag_blue_add.png"))); // NOI18N
NVariable.setToolTipText("New Variable");
NVariable.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NVariableActionPerformed(evt);
}
});
NOperation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/cog_add.png"))); // NOI18N
NOperation.setToolTipText("New Operation");
NOperation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NOperationActionPerformed(evt);
}
});
NDataBase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/database_add.png"))); // NOI18N
NDataBase.setToolTipText("New DataBase");
NDataBase.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NDataBaseActionPerformed(evt);
}
});
NTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/table_add.png"))); // NOI18N
NTable.setToolTipText("New Table");
NTable.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NTableActionPerformed(evt);
}
});
deshacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_undo.png"))); // NOI18N
deshacer.setToolTipText("Undo");
deshacer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
undoActionPerformed(evt);
}
});
editar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_edit.png"))); // NOI18N
editar.setToolTipText("Edit Code");
editar.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_delete.png"))); // NOI18N
editar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
editarActionPerformed(evt);
}
});
rehacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_redo.png"))); // NOI18N
rehacer.setToolTipText("Redo");
rehacer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
redoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 20, Short.MAX_VALUE)
);
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/bug_edit.png"))); // NOI18N
+ jButton1.setToolTipText("Failure manager");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(LoadEvent, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(LoadSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(SaveSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NVariable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NOperation, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NDataBase, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NTable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(editar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(deshacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rehacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 906, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LoadEvent)
.addComponent(SaveSyntax)
.addComponent(NVariable)
.addComponent(NOperation)
.addComponent(NDataBase)
.addComponent(NTable)
.addComponent(editar)
.addComponent(deshacer)
.addComponent(rehacer)
.addComponent(LoadSyntax)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
deshacer.getAccessibleContext().setAccessibleDescription("");
pack();
}// </editor-fold>//GEN-END:initComponents
private void LoadEventActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadEventActionPerformed
// TODO add your handling code here:
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt format", "txt");
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setFileFilter(filter);
int seleccion = fileChooser.showOpenDialog(this);
if (seleccion == JFileChooser.APPROVE_OPTION) {
String storeAllString = "";
File fichero = fileChooser.getSelectedFile();
// Aquí debemos abrir y leer el fichero.
Object[] what;
what = new Object[1];
what[0] = fichero.toString();
try {
Controller.controller(Controller.readInput, what);
} catch (Exception e) {
}
eventArea.setCaretPosition(0);
}
}//GEN-LAST:event_LoadEventActionPerformed
private void LoadSyntaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LoadSyntaxActionPerformed
// TODO add your handling code here:
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(".txt and .stx format", "txt", "stx");
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setFileFilter(filter);
int seleccion = fileChooser.showOpenDialog(this);
fileChooser.setMultiSelectionEnabled(false);
if (seleccion == JFileChooser.APPROVE_OPTION) {
String storeAllString = "";
File fichero = fileChooser.getSelectedFile();
// Aquí debemos abrir y leer el fichero.
try {
FileReader readTextFile = new FileReader(fichero.toString());
Scanner fileReaderScan = new Scanner(readTextFile);
while (fileReaderScan.hasNextLine()) {
String temp = fileReaderScan.nextLine() + "\n";
storeAllString = storeAllString + temp;
}
} catch (Exception e) {
}
syntaxArea.setText(storeAllString);
syntaxArea.setCaretPosition(0);
}
}//GEN-LAST:event_LoadSyntaxActionPerformed
private void NVariableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NVariableActionPerformed
// TODO add your handling code here:
JDialog jd = new NewVariable();
jd.setLocationByPlatform(true);
jd.setModal(true);
jd.setLocationRelativeTo(this);
jd.setVisible(true);
}//GEN-LAST:event_NVariableActionPerformed
private void undoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_undoActionPerformed
try {
undoManager.undo();
} catch (CannotUndoException cre) {
JOptionPane op = new JOptionPane();
op.showMessageDialog(this, "Can't undo more", "ERROR MESSAGE", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_undoActionPerformed
private void editarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editarActionPerformed
// TODO add your handling code here:
if (syntaxArea.isEditable()) {
syntaxArea.setEditable(false);
syntaxArea.setForeground(Gray);
} else {
syntaxArea.setEditable(true);
syntaxArea.setForeground(Black);
}
}//GEN-LAST:event_editarActionPerformed
private void redoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_redoActionPerformed
try {
undoManager.redo();
} catch (CannotRedoException cre) {
JOptionPane op = new JOptionPane();
op.showMessageDialog(this, "Can't redo more", "ERROR MESSAGE", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_redoActionPerformed
private void NOperationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NOperationActionPerformed
JDialog no = new NewOperations(this);
no.setVisible(true);
}//GEN-LAST:event_NOperationActionPerformed
private void SaveSyntaxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveSyntaxActionPerformed
JFileChooser jfc = new JFileChooser();
jfc.setMultiSelectionEnabled(false);
jfc.setVisible(true);
if(JFileChooser.APPROVE_OPTION == jfc.showSaveDialog(this)){
Object[] what = new Object[2];
what[0] = syntaxArea.getText();
what[1] = jfc.getSelectedFile();
Controller.controller(Controller.writeOutput, what);
}
/*
f = new JFrame("Write a file name");
f.setLayout(new BorderLayout());
f.setVisible(true);
this.tf = new JTextField("syntax");
JButton confirmButton = new JButton("Ok");
JButton defaultButton = new JButton("Default: syntax");
JButton cancelButton = new JButton("Cancel");
f.add(tf, BorderLayout.NORTH);
f.add(confirmButton, BorderLayout.WEST);
f.add(defaultButton, BorderLayout.CENTER);
f.add(cancelButton, BorderLayout.SOUTH);
f.pack();
f.setLocation(this.getLocation().x + this.getWidth()/2 - f.getWidth()/2, this.getLocation().y + this.getHeight()/2 - f.getHeight()/2);
confirmButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
business.Output.publishOutput(syntaxArea.getText(), tf.getText());
f.dispose();
}
});
defaultButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
business.Output.publishOutput(syntaxArea.getText(), "");
f.dispose();
}
});
cancelButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
f.dispose();
}
});
*/
}//GEN-LAST:event_SaveSyntaxActionPerformed
private void NTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NTableActionPerformed
JDialog jd = new NewTable();
jd.setLocationByPlatform(true);
jd.setLocationRelativeTo(this);
jd.setModal(true);
jd.setVisible(true);
}//GEN-LAST:event_NTableActionPerformed
private void NDataBaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NDataBaseActionPerformed
JDialog jd = new NewBBDD(this, true);
jd.setLocationByPlatform(true);
jd.setLocationRelativeTo(this);
jd.setVisible(true);
}//GEN-LAST:event_NDataBaseActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private JTextField oldColName;
private JTextField newColName;
private JTextField tf;
private JFrame f;
//<editor-fold defaultstate="collapsed" desc=" Make's Room ">
private String preMakeRoom(javax.swing.JTextArea Area) {
String bs = "";
int act = Area.getCaretPosition();
try {
String sig = Area.getText(act - 1, 1);
if (!sig.equalsIgnoreCase("\n")) {
//Area.insert("\n", Area.getCaretPosition());
bs = "\n";
}
} catch (BadLocationException ex) {
}
return bs;
}
private String postMakeRoom(javax.swing.JTextArea Area) {
String bs = "";
int act = Area.getCaretPosition();
Area.setCaretPosition(Area.getDocument().getLength());
int fin = Area.getCaretPosition();
Area.setCaretPosition(act);
try {
String sig = Area.getText(act, 1);
if (act != fin && sig.equalsIgnoreCase("\n")) {
Area.setCaretPosition(Area.getCaretPosition() + 1);
} else {
//Area.insert("\n", Area.getCaretPosition());
bs = "\n";
}
} catch (BadLocationException ex) {
//Area.insert("\n", Area.getCaretPosition());
bs = "\n";
}
return bs;
}
/**
* Inserta el parametro String en el parametor JTextArea haciendo un "hueco"
* en el texto, si fuera necesario
*
* @param Area JTextArea
* @param str String
*/
private void insertText(javax.swing.JTextArea Area, String str) {
Area.insert(preMakeRoom(Area) + str
+ postMakeRoom(Area), Area.getCaretPosition());
}
//</editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton LoadEvent;
private javax.swing.JButton LoadSyntax;
private javax.swing.JButton NDataBase;
private javax.swing.JButton NOperation;
private javax.swing.JButton NTable;
private javax.swing.JButton NVariable;
private javax.swing.JButton SaveSyntax;
private javax.swing.JButton deshacer;
private javax.swing.JToggleButton editar;
private javax.swing.JTextArea eventArea;
private javax.swing.JButton jButton1;
private javax.swing.JFileChooser jFileChooser1;
private javax.swing.JFrame jFrame1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JButton rehacer;
private javax.swing.JTextArea syntaxArea;
// End of variables declaration//GEN-END:variables
}
| true | true | private void initComponents() {
jFileChooser1 = new javax.swing.JFileChooser();
jFrame1 = new javax.swing.JFrame();
jLabel1 = new javax.swing.JLabel();
jSplitPane1 = new javax.swing.JSplitPane();
jScrollPane2 = new javax.swing.JScrollPane();
syntaxArea = new javax.swing.JTextArea();
jScrollPane1 = new javax.swing.JScrollPane();
eventArea = new javax.swing.JTextArea();
LoadEvent = new javax.swing.JButton();
LoadSyntax = new javax.swing.JButton();
SaveSyntax = new javax.swing.JButton();
NVariable = new javax.swing.JButton();
NOperation = new javax.swing.JButton();
NDataBase = new javax.swing.JButton();
NTable = new javax.swing.JButton();
deshacer = new javax.swing.JButton();
editar = new javax.swing.JToggleButton();
rehacer = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jFrame1.setBounds(new java.awt.Rectangle(0, 0, 225, 206));
jFrame1.setLocationByPlatform(true);
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("<html><img src=\"http://farm4.staticflickr.com/3227/3115937621_650616f2b0.jpg\" width=210 height=180></html>");
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 15, Short.MAX_VALUE))
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(38, Short.MAX_VALUE))
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("KiwiSyntaxManager");
setFocusCycleRoot(false);
setLocationByPlatform(true);
jSplitPane1.setResizeWeight(0.5);
jScrollPane2.setToolTipText("");
syntaxArea.setColumns(20);
syntaxArea.setRows(5);
jScrollPane2.setViewportView(syntaxArea);
jSplitPane1.setRightComponent(jScrollPane2);
eventArea.setColumns(20);
eventArea.setRows(5);
jScrollPane1.setViewportView(eventArea);
jSplitPane1.setLeftComponent(jScrollPane1);
LoadEvent.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_lightning.png"))); // NOI18N
LoadEvent.setToolTipText("Load Event");
LoadEvent.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadEventActionPerformed(evt);
}
});
LoadSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_put.png"))); // NOI18N
LoadSyntax.setToolTipText("Load Syntax");
LoadSyntax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadSyntaxActionPerformed(evt);
}
});
SaveSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/disk.png"))); // NOI18N
SaveSyntax.setToolTipText("Save");
SaveSyntax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveSyntaxActionPerformed(evt);
}
});
NVariable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/tag_blue_add.png"))); // NOI18N
NVariable.setToolTipText("New Variable");
NVariable.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NVariableActionPerformed(evt);
}
});
NOperation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/cog_add.png"))); // NOI18N
NOperation.setToolTipText("New Operation");
NOperation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NOperationActionPerformed(evt);
}
});
NDataBase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/database_add.png"))); // NOI18N
NDataBase.setToolTipText("New DataBase");
NDataBase.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NDataBaseActionPerformed(evt);
}
});
NTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/table_add.png"))); // NOI18N
NTable.setToolTipText("New Table");
NTable.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NTableActionPerformed(evt);
}
});
deshacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_undo.png"))); // NOI18N
deshacer.setToolTipText("Undo");
deshacer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
undoActionPerformed(evt);
}
});
editar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_edit.png"))); // NOI18N
editar.setToolTipText("Edit Code");
editar.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_delete.png"))); // NOI18N
editar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
editarActionPerformed(evt);
}
});
rehacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_redo.png"))); // NOI18N
rehacer.setToolTipText("Redo");
rehacer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
redoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 20, Short.MAX_VALUE)
);
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/bug_edit.png"))); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(LoadEvent, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(LoadSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(SaveSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NVariable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NOperation, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NDataBase, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NTable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(editar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(deshacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rehacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 906, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LoadEvent)
.addComponent(SaveSyntax)
.addComponent(NVariable)
.addComponent(NOperation)
.addComponent(NDataBase)
.addComponent(NTable)
.addComponent(editar)
.addComponent(deshacer)
.addComponent(rehacer)
.addComponent(LoadSyntax)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
deshacer.getAccessibleContext().setAccessibleDescription("");
pack();
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
jFileChooser1 = new javax.swing.JFileChooser();
jFrame1 = new javax.swing.JFrame();
jLabel1 = new javax.swing.JLabel();
jSplitPane1 = new javax.swing.JSplitPane();
jScrollPane2 = new javax.swing.JScrollPane();
syntaxArea = new javax.swing.JTextArea();
jScrollPane1 = new javax.swing.JScrollPane();
eventArea = new javax.swing.JTextArea();
LoadEvent = new javax.swing.JButton();
LoadSyntax = new javax.swing.JButton();
SaveSyntax = new javax.swing.JButton();
NVariable = new javax.swing.JButton();
NOperation = new javax.swing.JButton();
NDataBase = new javax.swing.JButton();
NTable = new javax.swing.JButton();
deshacer = new javax.swing.JButton();
editar = new javax.swing.JToggleButton();
rehacer = new javax.swing.JButton();
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jFrame1.setBounds(new java.awt.Rectangle(0, 0, 225, 206));
jFrame1.setLocationByPlatform(true);
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("<html><img src=\"http://farm4.staticflickr.com/3227/3115937621_650616f2b0.jpg\" width=210 height=180></html>");
javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
jFrame1.getContentPane().setLayout(jFrame1Layout);
jFrame1Layout.setHorizontalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 15, Short.MAX_VALUE))
);
jFrame1Layout.setVerticalGroup(
jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jFrame1Layout.createSequentialGroup()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(38, Short.MAX_VALUE))
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("KiwiSyntaxManager");
setFocusCycleRoot(false);
setLocationByPlatform(true);
jSplitPane1.setResizeWeight(0.5);
jScrollPane2.setToolTipText("");
syntaxArea.setColumns(20);
syntaxArea.setRows(5);
jScrollPane2.setViewportView(syntaxArea);
jSplitPane1.setRightComponent(jScrollPane2);
eventArea.setColumns(20);
eventArea.setRows(5);
jScrollPane1.setViewportView(eventArea);
jSplitPane1.setLeftComponent(jScrollPane1);
LoadEvent.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_lightning.png"))); // NOI18N
LoadEvent.setToolTipText("Load Event");
LoadEvent.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadEventActionPerformed(evt);
}
});
LoadSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_put.png"))); // NOI18N
LoadSyntax.setToolTipText("Load Syntax");
LoadSyntax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
LoadSyntaxActionPerformed(evt);
}
});
SaveSyntax.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/disk.png"))); // NOI18N
SaveSyntax.setToolTipText("Save");
SaveSyntax.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SaveSyntaxActionPerformed(evt);
}
});
NVariable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/tag_blue_add.png"))); // NOI18N
NVariable.setToolTipText("New Variable");
NVariable.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NVariableActionPerformed(evt);
}
});
NOperation.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/cog_add.png"))); // NOI18N
NOperation.setToolTipText("New Operation");
NOperation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NOperationActionPerformed(evt);
}
});
NDataBase.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/database_add.png"))); // NOI18N
NDataBase.setToolTipText("New DataBase");
NDataBase.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NDataBaseActionPerformed(evt);
}
});
NTable.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/table_add.png"))); // NOI18N
NTable.setToolTipText("New Table");
NTable.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
NTableActionPerformed(evt);
}
});
deshacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_undo.png"))); // NOI18N
deshacer.setToolTipText("Undo");
deshacer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
undoActionPerformed(evt);
}
});
editar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_edit.png"))); // NOI18N
editar.setToolTipText("Edit Code");
editar.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/page_white_delete.png"))); // NOI18N
editar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
editarActionPerformed(evt);
}
});
rehacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/arrow_redo.png"))); // NOI18N
rehacer.setToolTipText("Redo");
rehacer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
redoActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 20, Short.MAX_VALUE)
);
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons2/bug_edit.png"))); // NOI18N
jButton1.setToolTipText("Failure manager");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(LoadEvent, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(LoadSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(SaveSyntax, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NVariable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NOperation, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NDataBase, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(NTable, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(editar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(deshacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(rehacer, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 906, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LoadEvent)
.addComponent(SaveSyntax)
.addComponent(NVariable)
.addComponent(NOperation)
.addComponent(NDataBase)
.addComponent(NTable)
.addComponent(editar)
.addComponent(deshacer)
.addComponent(rehacer)
.addComponent(LoadSyntax)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 395, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
deshacer.getAccessibleContext().setAccessibleDescription("");
pack();
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java b/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java
index bc22bac..dfbcacb 100644
--- a/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java
+++ b/src/uk/ac/gla/dcs/tp3/w/algorithm/Main.java
@@ -1,127 +1,127 @@
package uk.ac.gla.dcs.tp3.w.algorithm;
import java.util.LinkedList;
import uk.ac.gla.dcs.tp3.w.league.*;
import uk.ac.gla.dcs.tp3.w.algorithm.Graph;
/**
* @author gordon
*
*/
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Team atlanta = new Team();
atlanta.setName("Atlanta");
atlanta.setGamesPlayed(170 - 8);
atlanta.setPoints(83);
Team philadelphia = new Team();
philadelphia.setName("Philadelphia");
philadelphia.setGamesPlayed(170 - 4);
philadelphia.setPoints(79);
Team newYork = new Team();
newYork.setName("New York");
newYork.setGamesPlayed(170 - 7);
newYork.setPoints(78);
Team montreal = new Team();
montreal.setName("Montreal");
montreal.setGamesPlayed(170 - 7);
montreal.setPoints(76);
Match[] atlantaMatches = new Match[8];
Match[] philadelphiaMatches = new Match[4];
Match[] newYorkMatches = new Match[7];
Match[] montrealMatches = new Match[5];
Match[] allMatches = new Match[12];
int am = 0;
int pm = 0;
int nym = 0;
int mm = 0;
int all = 0;
Match atlVphil = new Match();
atlVphil.setHomeTeam(atlanta);
atlVphil.setAwayTeam(philadelphia);
atlantaMatches[am++] = atlVphil;
philadelphiaMatches[pm++] = atlVphil;
allMatches[all++] = atlVphil;
Match atlVny = new Match();
atlVny.setHomeTeam(atlanta);
atlVny.setAwayTeam(newYork);
for (int i = 0; i < 6; i++) {
atlantaMatches[am++] = atlVny;
newYorkMatches[nym++] = atlVny;
allMatches[all++] = atlVny;
}
Match atlVmon = new Match();
atlVmon.setHomeTeam(atlanta);
atlVmon.setAwayTeam(montreal);
atlantaMatches[am++] = atlVmon;
montrealMatches[mm++] = atlVmon;
allMatches[all++] = atlVmon;
Match philVmon = new Match();
philVmon.setHomeTeam(philadelphia);
philVmon.setAwayTeam(montreal);
for (int i = 0; i < 3; i++) {
philadelphiaMatches[pm++] = philVmon;
montrealMatches[mm++] = philVmon;
allMatches[all++] = philVmon;
}
Match nyVmon = new Match();
nyVmon.setHomeTeam(newYork);
nyVmon.setAwayTeam(montreal);
newYorkMatches[nym++] = nyVmon;
montrealMatches[mm++] = nyVmon;
allMatches[all++] = nyVmon;
atlanta.setUpcomingMatches(atlantaMatches);
philadelphia.setUpcomingMatches(philadelphiaMatches);
newYork.setUpcomingMatches(newYorkMatches);
montreal.setUpcomingMatches(montrealMatches);
Team[] teams = new Team[4];
teams[0] = atlanta;
teams[1] = philadelphia;
teams[2] = newYork;
teams[3] = montreal;
League l = new League(teams, allMatches);
Graph g = new Graph(l, atlanta);
LinkedList<AdjListNode> list = g.getSource().getAdjList();
for (AdjListNode n : list) {
PairVertex v = (PairVertex) n.getVertex();
- System.out.println("Sink to " + v.getTeamA().getName() + " and "
+ System.out.println("Source to " + v.getTeamA().getName() + " and "
+ v.getTeamB().getName() + " has capacity "
+ n.getCapacity());
for (AdjListNode m : v.getAdjList()) {
TeamVertex w = (TeamVertex) m.getVertex();
System.out.println("\t Pair Vertex to " + w.getTeam().getName()
+ " has capacity " + n.getCapacity());
for (AdjListNode b : w.getAdjList()) {
Vertex x = b.getVertex();
if (x != g.getSink()) {
System.out.println("Not adjacent to sink.");
}
System.out.println("\t\t Team vertex "
+ w.getTeam().getName() + " to sink has capacity "
+ b.getCapacity());
}
}
}
}
}
| true | true | public static void main(String[] args) {
Team atlanta = new Team();
atlanta.setName("Atlanta");
atlanta.setGamesPlayed(170 - 8);
atlanta.setPoints(83);
Team philadelphia = new Team();
philadelphia.setName("Philadelphia");
philadelphia.setGamesPlayed(170 - 4);
philadelphia.setPoints(79);
Team newYork = new Team();
newYork.setName("New York");
newYork.setGamesPlayed(170 - 7);
newYork.setPoints(78);
Team montreal = new Team();
montreal.setName("Montreal");
montreal.setGamesPlayed(170 - 7);
montreal.setPoints(76);
Match[] atlantaMatches = new Match[8];
Match[] philadelphiaMatches = new Match[4];
Match[] newYorkMatches = new Match[7];
Match[] montrealMatches = new Match[5];
Match[] allMatches = new Match[12];
int am = 0;
int pm = 0;
int nym = 0;
int mm = 0;
int all = 0;
Match atlVphil = new Match();
atlVphil.setHomeTeam(atlanta);
atlVphil.setAwayTeam(philadelphia);
atlantaMatches[am++] = atlVphil;
philadelphiaMatches[pm++] = atlVphil;
allMatches[all++] = atlVphil;
Match atlVny = new Match();
atlVny.setHomeTeam(atlanta);
atlVny.setAwayTeam(newYork);
for (int i = 0; i < 6; i++) {
atlantaMatches[am++] = atlVny;
newYorkMatches[nym++] = atlVny;
allMatches[all++] = atlVny;
}
Match atlVmon = new Match();
atlVmon.setHomeTeam(atlanta);
atlVmon.setAwayTeam(montreal);
atlantaMatches[am++] = atlVmon;
montrealMatches[mm++] = atlVmon;
allMatches[all++] = atlVmon;
Match philVmon = new Match();
philVmon.setHomeTeam(philadelphia);
philVmon.setAwayTeam(montreal);
for (int i = 0; i < 3; i++) {
philadelphiaMatches[pm++] = philVmon;
montrealMatches[mm++] = philVmon;
allMatches[all++] = philVmon;
}
Match nyVmon = new Match();
nyVmon.setHomeTeam(newYork);
nyVmon.setAwayTeam(montreal);
newYorkMatches[nym++] = nyVmon;
montrealMatches[mm++] = nyVmon;
allMatches[all++] = nyVmon;
atlanta.setUpcomingMatches(atlantaMatches);
philadelphia.setUpcomingMatches(philadelphiaMatches);
newYork.setUpcomingMatches(newYorkMatches);
montreal.setUpcomingMatches(montrealMatches);
Team[] teams = new Team[4];
teams[0] = atlanta;
teams[1] = philadelphia;
teams[2] = newYork;
teams[3] = montreal;
League l = new League(teams, allMatches);
Graph g = new Graph(l, atlanta);
LinkedList<AdjListNode> list = g.getSource().getAdjList();
for (AdjListNode n : list) {
PairVertex v = (PairVertex) n.getVertex();
System.out.println("Sink to " + v.getTeamA().getName() + " and "
+ v.getTeamB().getName() + " has capacity "
+ n.getCapacity());
for (AdjListNode m : v.getAdjList()) {
TeamVertex w = (TeamVertex) m.getVertex();
System.out.println("\t Pair Vertex to " + w.getTeam().getName()
+ " has capacity " + n.getCapacity());
for (AdjListNode b : w.getAdjList()) {
Vertex x = b.getVertex();
if (x != g.getSink()) {
System.out.println("Not adjacent to sink.");
}
System.out.println("\t\t Team vertex "
+ w.getTeam().getName() + " to sink has capacity "
+ b.getCapacity());
}
}
}
}
| public static void main(String[] args) {
Team atlanta = new Team();
atlanta.setName("Atlanta");
atlanta.setGamesPlayed(170 - 8);
atlanta.setPoints(83);
Team philadelphia = new Team();
philadelphia.setName("Philadelphia");
philadelphia.setGamesPlayed(170 - 4);
philadelphia.setPoints(79);
Team newYork = new Team();
newYork.setName("New York");
newYork.setGamesPlayed(170 - 7);
newYork.setPoints(78);
Team montreal = new Team();
montreal.setName("Montreal");
montreal.setGamesPlayed(170 - 7);
montreal.setPoints(76);
Match[] atlantaMatches = new Match[8];
Match[] philadelphiaMatches = new Match[4];
Match[] newYorkMatches = new Match[7];
Match[] montrealMatches = new Match[5];
Match[] allMatches = new Match[12];
int am = 0;
int pm = 0;
int nym = 0;
int mm = 0;
int all = 0;
Match atlVphil = new Match();
atlVphil.setHomeTeam(atlanta);
atlVphil.setAwayTeam(philadelphia);
atlantaMatches[am++] = atlVphil;
philadelphiaMatches[pm++] = atlVphil;
allMatches[all++] = atlVphil;
Match atlVny = new Match();
atlVny.setHomeTeam(atlanta);
atlVny.setAwayTeam(newYork);
for (int i = 0; i < 6; i++) {
atlantaMatches[am++] = atlVny;
newYorkMatches[nym++] = atlVny;
allMatches[all++] = atlVny;
}
Match atlVmon = new Match();
atlVmon.setHomeTeam(atlanta);
atlVmon.setAwayTeam(montreal);
atlantaMatches[am++] = atlVmon;
montrealMatches[mm++] = atlVmon;
allMatches[all++] = atlVmon;
Match philVmon = new Match();
philVmon.setHomeTeam(philadelphia);
philVmon.setAwayTeam(montreal);
for (int i = 0; i < 3; i++) {
philadelphiaMatches[pm++] = philVmon;
montrealMatches[mm++] = philVmon;
allMatches[all++] = philVmon;
}
Match nyVmon = new Match();
nyVmon.setHomeTeam(newYork);
nyVmon.setAwayTeam(montreal);
newYorkMatches[nym++] = nyVmon;
montrealMatches[mm++] = nyVmon;
allMatches[all++] = nyVmon;
atlanta.setUpcomingMatches(atlantaMatches);
philadelphia.setUpcomingMatches(philadelphiaMatches);
newYork.setUpcomingMatches(newYorkMatches);
montreal.setUpcomingMatches(montrealMatches);
Team[] teams = new Team[4];
teams[0] = atlanta;
teams[1] = philadelphia;
teams[2] = newYork;
teams[3] = montreal;
League l = new League(teams, allMatches);
Graph g = new Graph(l, atlanta);
LinkedList<AdjListNode> list = g.getSource().getAdjList();
for (AdjListNode n : list) {
PairVertex v = (PairVertex) n.getVertex();
System.out.println("Source to " + v.getTeamA().getName() + " and "
+ v.getTeamB().getName() + " has capacity "
+ n.getCapacity());
for (AdjListNode m : v.getAdjList()) {
TeamVertex w = (TeamVertex) m.getVertex();
System.out.println("\t Pair Vertex to " + w.getTeam().getName()
+ " has capacity " + n.getCapacity());
for (AdjListNode b : w.getAdjList()) {
Vertex x = b.getVertex();
if (x != g.getSink()) {
System.out.println("Not adjacent to sink.");
}
System.out.println("\t\t Team vertex "
+ w.getTeam().getName() + " to sink has capacity "
+ b.getCapacity());
}
}
}
}
|
diff --git a/src/com/bigpupdev/synodroid/ui/DetailActivity.java b/src/com/bigpupdev/synodroid/ui/DetailActivity.java
index 94fb44e..0552fe1 100644
--- a/src/com/bigpupdev/synodroid/ui/DetailActivity.java
+++ b/src/com/bigpupdev/synodroid/ui/DetailActivity.java
@@ -1,952 +1,955 @@
package com.bigpupdev.synodroid.ui;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import com.bigpupdev.synodroid.R;
import com.bigpupdev.synodroid.Synodroid;
import com.bigpupdev.synodroid.action.DeleteTaskAction;
import com.bigpupdev.synodroid.action.DownloadOriginalLinkAction;
import com.bigpupdev.synodroid.action.EnumShareAction;
import com.bigpupdev.synodroid.action.GetFilesAction;
import com.bigpupdev.synodroid.action.GetTaskPropertiesAction;
import com.bigpupdev.synodroid.action.PauseTaskAction;
import com.bigpupdev.synodroid.action.ResumeTaskAction;
import com.bigpupdev.synodroid.action.UpdateFilesAction;
import com.bigpupdev.synodroid.action.UpdateTaskAction;
import com.bigpupdev.synodroid.action.UpdateTaskPropertiesAction;
import com.bigpupdev.synodroid.adapter.Detail;
import com.bigpupdev.synodroid.adapter.Detail2Progress;
import com.bigpupdev.synodroid.adapter.Detail2Text;
import com.bigpupdev.synodroid.adapter.DetailAction;
import com.bigpupdev.synodroid.adapter.DetailProgress;
import com.bigpupdev.synodroid.adapter.DetailText;
import com.bigpupdev.synodroid.data.DSMVersion;
import com.bigpupdev.synodroid.data.OriginalFile;
import com.bigpupdev.synodroid.data.SharedDirectory;
import com.bigpupdev.synodroid.data.Task;
import com.bigpupdev.synodroid.data.TaskDetail;
import com.bigpupdev.synodroid.data.TaskFile;
import com.bigpupdev.synodroid.data.TaskProperties;
import com.bigpupdev.synodroid.data.TaskStatus;
import com.bigpupdev.synodroid.protocol.ResponseHandler;
import com.bigpupdev.synodroid.server.SynoServer;
import com.bigpupdev.synodroid.utils.ActivityHelper;
import com.bigpupdev.synodroid.utils.EulaHelper;
import com.bigpupdev.synodroid.utils.UIUtils;
import com.bigpupdev.synodroid.utils.Utils;
import com.bigpupdev.synodroid.utils.ViewPagerIndicator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class DetailActivity extends BaseActivity{
private static final String PREFERENCE_FULLSCREEN = "general_cat.fullscreen";
private static final String PREFERENCE_GENERAL = "general_cat";
MyAdapter mAdapter;
ViewPager mPager;
ViewPagerIndicator mIndicator;
Task task;
TaskStatus status;
// The seeding ratio
private int seedingRatio;
// The seeding time
private int seedingTime;
private int ul_rate;
private int dl_rate;
private int priority;
private int max_peers;
private String destination;
private int[] priorities;
private String[] destinations;
// Flag to know of the user changed seeding parameters
private boolean seedingChanged = false;
// The values of seeding time
private int[] seedingTimes;
private static final int MENU_PAUSE = 1;
private static final int MENU_DELETE = 2;
private static final int MENU_CANCEL = 3;
private static final int MENU_RESUME = 4;
private static final int MENU_RETRY = 5;
private static final int MENU_CLEAR = 6;
private static final int MENU_PARAMETERS = 7;
private static final int TASK_PARAMETERS_DIALOG = 3;
private static final int TASK_PROPERTIES_DIALOG = 4;
private static final int MAIN_ITEM = 0;
private static final int TRANSFER_ITEM = 1;
private static final int FILE_ITEM = 2;
public void setStatus(TaskStatus pStatus){
status = pStatus;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onPause()
*/
@Override
public void onPause() {
super.onPause();
// Try to update the details
updateTask(false);
Synodroid app = (Synodroid) getApplication();
app.pauseServer();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onResume()
*/
@Override
public void onResume() {
super.onResume();
// Check for fullscreen
SharedPreferences preferences = getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
if (preferences.getBoolean(PREFERENCE_FULLSCREEN, false)) {
// Set fullscreen or not
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
// Launch the gets task's details recurrent action
Synodroid app = (Synodroid) getApplication();
app.resumeServer();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getActivityHelper().setupSubActivity();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
SharedPreferences preferences = getSharedPreferences(PREFERENCE_GENERAL, Activity.MODE_PRIVATE);
if (preferences.getBoolean(PREFERENCE_FULLSCREEN, false)) {
// Set fullscreen or not
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
}
/**
* Return a sub detail list for the general's tab
*/
private List<Detail> buildTransferDetails(TaskDetail details) {
ArrayList<Detail> result = new ArrayList<Detail>();
// Set the result to be returned to the previous activity
Intent previous = new Intent();
previous.putExtra("com.bigpupdev.synodroid.ds.Details", details);
setResult(Activity.RESULT_OK, previous);
// ------------ Status
try {
result.add(new DetailText(getString(R.string.detail_status), TaskStatus.getLabel(this, details.status)));
} catch (NullPointerException e) {
result.add(new DetailText(getString(R.string.detail_status), getString(R.string.detail_unknown)));
} catch (IllegalArgumentException e) {
result.add(new DetailText(getString(R.string.detail_status), getString(R.string.detail_unknown)));
}
// ------------ Transfered
String transfered = getString(R.string.detail_progress_download) + " " + Utils.bytesToFileSize(details.bytesDownloaded, true, getString(R.string.detail_unknown));
if (details.isTorrent) {
String upload = getString(R.string.detail_progress_upload) + " " + Utils.bytesToFileSize(details.bytesUploaded, true, getString(R.string.detail_unknown)) + " (" + details.bytesRatio + " %)";
Detail2Text tr = new Detail2Text(getString(R.string.detail_transfered));
tr.setValue1(transfered);
tr.setValue2(upload);
result.add(tr);
} else {
result.add(new DetailText(getString(R.string.detail_transfered), transfered));
}
// ------------- Progress
long downloaded = details.bytesDownloaded;
long filesize = details.fileSize;
String downPerStr = getString(R.string.detail_unknown);
int downPer = 0;
if (filesize != -1) {
try {
downPer = (int) ((downloaded * 100) / filesize);
} catch (ArithmeticException e) {
downPer = 100;
}
+ if (downPer == 100 && downloaded != filesize){
+ downPer = 99;
+ }
downPerStr = "" + downPer + "%";
}
int upPerc = 0;
String upPercStr = getString(R.string.detail_unknown);
Integer uploadPercentage = Utils.computeUploadPercent(details);
if (uploadPercentage != null) {
upPerc = uploadPercentage.intValue();
upPercStr = "" + upPerc + "%";
}
// If it is a torrent
Detail proDetail = null;
if (details.isTorrent) {
Detail2Progress progDetail = new Detail2Progress(getString(R.string.detail_progress));
proDetail = progDetail;
progDetail.setProgress1(getString(R.string.detail_progress_download) + " " + downPerStr, downPer);
progDetail.setProgress2(getString(R.string.detail_progress_upload) + " " + upPercStr, upPerc);
} else {
DetailProgress progDetail = new DetailProgress(getString(R.string.detail_progress), R.layout.details_progress_template1);
proDetail = progDetail;
progDetail.setProgress(getString(R.string.detail_progress_download) + " " + downPerStr, downPer);
}
result.add(proDetail);
// ------------ Speed
String speed = getString(R.string.detail_progress_download) + " " + details.speedDownload + " KB/s";
if (details.isTorrent) {
speed = speed + " - " + getString(R.string.detail_progress_upload) + " " + details.speedUpload + " KB/s";
}
result.add(new DetailText(getString(R.string.detail_speed), speed));
// ------------ Peers
if (details.isTorrent) {
String peers = details.peersCurrent + " / " + details.peersTotal;
DetailProgress peersDetail = new DetailProgress(getString(R.string.detail_peers), R.layout.details_progress_template2);
int pProgress = 0;
if (details.peersTotal != 0) {
pProgress = (int) ((details.peersCurrent * 100) / details.peersTotal);
}
peersDetail.setProgress(peers, pProgress);
result.add(peersDetail);
}
// ------------ Seeders / Leechers
if (details.isTorrent) {
String seedStr = getString(R.string.detail_unvailable);
String leechStr = getString(R.string.detail_unvailable);
if (details.seeders != null)
seedStr = details.seeders.toString();
if (details.leechers != null)
leechStr = details.leechers.toString();
String seeders = seedStr + " - " + leechStr;
result.add(new DetailText(getString(R.string.detail_seeders_leechers), seeders));
}
// ------------ ETAs
String etaUpload = getString(R.string.detail_unknown);
String etaDownload = getString(R.string.detail_unknown);
if (details.speedDownload != 0) {
long sizeLeft = filesize - downloaded;
long timeLeft = (long) (sizeLeft / (details.speedDownload * 1000));
etaDownload = Utils.computeTimeLeft(timeLeft);
} else {
if (downPer == 100) {
etaDownload = getString(R.string.detail_finished);
}
}
Long timeLeftSize = null;
long uploaded = details.bytesUploaded;
double ratio = ((double) (details.seedingRatio)) / 100.0d;
if (details.speedUpload != 0 && details.seedingRatio != 0) {
long sizeLeft = (long) ((filesize * ratio) - uploaded);
timeLeftSize = (long) (sizeLeft / (details.speedUpload * 1000));
}
// If the user defined a minimum seeding time AND we are in seeding
// mode
TaskStatus tsk_status = details.getStatus();
Long timeLeftTime = null;
if (details.seedingInterval != 0 && tsk_status == TaskStatus.TASK_SEEDING) {
timeLeftTime = (details.seedingInterval * 60) - details.seedingElapsed;
if (timeLeftTime < 0) {
timeLeftTime = null;
}
}
// At least one time has been computed
if (timeLeftTime != null || timeLeftSize != null) {
// By default take the size time
Long time = timeLeftSize;
// Except if it is null
if (timeLeftSize == null) {
time = timeLeftTime;
} else {
// If time is not null
if (timeLeftTime != null) {
// Get the higher value
if (timeLeftTime > timeLeftSize) {
time = timeLeftTime;
}
}
}
etaUpload = Utils.computeTimeLeft(time);
} else if (upPerc == 100) {
etaUpload = getString(R.string.detail_finished);
}
// In case the user set the seedin time to forever
if (details.seedingInterval == -1) {
etaUpload = getString(R.string.detail_forever);
}
Detail etaDet = null;
// If it is a torrent then show the upload ETA
if (details.isTorrent) {
Detail2Text etaDetail = new Detail2Text(getString(R.string.detail_eta));
etaDet = etaDetail;
etaDetail.setValue1(getString(R.string.detail_progress_download) + " " + etaDownload);
etaDetail.setValue2(getString(R.string.detail_progress_upload) + " " + etaUpload);
}
// Otherwise only show the download ETA
else {
DetailText etaDetail = new DetailText(getString(R.string.detail_eta));
etaDet = etaDetail;
etaDetail.setValue(getString(R.string.detail_progress_download) + " " + etaDownload);
}
result.add(etaDet);
// ------------ Pieces
if (details.isTorrent) {
String pieces = details.piecesCurrent + " / " + details.piecesTotal;
DetailProgress piecesDetail = new DetailProgress(getString(R.string.detail_pieces), R.layout.details_progress_template2);
int piProgress = 0;
if (details.piecesTotal != 0) {
piProgress = (int) ((details.piecesCurrent * 100) / details.piecesTotal);
}
piecesDetail.setProgress(pieces, piProgress);
result.add(piecesDetail);
}
// Update seeding parameters
seedingRatio = details.seedingRatio;
seedingTime = details.seedingInterval;
return result;
}
/**
* Return a sub detail list for the general's tab
*/
private List<Detail> buildGeneralDetails(TaskDetail details) {
ArrayList<Detail> result = new ArrayList<Detail>();
// FileName
result.add(new DetailText(getString(R.string.detail_filename), details.fileName));
setTitle(details.fileName);
// Destination
DetailText destDetail = new DetailText(getString(R.string.detail_destination), details.destination);
result.add(destDetail);
// File size
result.add(new DetailText(getString(R.string.detail_filesize), Utils.bytesToFileSize(details.fileSize, true, getString(R.string.detail_unknown))));
// Creation time
result.add(new DetailText(getString(R.string.detail_creationtime), Utils.computeDate(details.creationDate)));
// URL
final String originalLink = details.url;
DetailText urlDetail = new DetailText(getString(R.string.detail_url), originalLink);
urlDetail.setAction(new DetailAction() {
public void execute(Detail detailsP) {
if ((task.isTorrent || task.isNZB)) {
Synodroid app = (Synodroid) getApplication();
task.originalLink = originalLink;
app.executeAsynchronousAction((DetailMain)mAdapter.getItem(MAIN_ITEM), new DownloadOriginalLinkAction(task), false);
}
}
});
result.add(urlDetail);
// Username
result.add(new DetailText(getString(R.string.detail_username), details.userName));
return result;
}
public void updateActionBarTitle(String title){
ActivityHelper ah = getActivityHelper();
if (ah != null) ah.setActionBarTitle(title, false);
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onPrepareDialog(int, android.app.Dialog)
*/
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
// Prepare the task's parameters dialog
case TASK_PARAMETERS_DIALOG:
final EditText seedRatio = (EditText) dialog.findViewById(R.id.seedingPercentage);
final Spinner seedTime = (Spinner) dialog.findViewById(R.id.seedingTime);
seedRatio.setText("" + seedingRatio);
// Try to find the right value
int pos = 0;
for (int iLoop = 0; iLoop < seedingTimes.length; iLoop++) {
if (seedingTimes[iLoop] == seedingTime) {
pos = iLoop;
break;
}
}
seedTime.setSelection(pos);
break;
case TASK_PROPERTIES_DIALOG:
final EditText seedRatioP = (EditText) dialog.findViewById(R.id.seedingPercentage);
final Spinner seedTimeP = (Spinner) dialog.findViewById(R.id.seedingTime);
final EditText ul_rateP = (EditText) dialog.findViewById(R.id.ul_rate);
final EditText dl_rateP = (EditText) dialog.findViewById(R.id.dl_rate);
final EditText max_peersP = (EditText) dialog.findViewById(R.id.max_peers);
final Spinner destinationP = (Spinner) dialog.findViewById(R.id.destination);
final Spinner priorityP = (Spinner) dialog.findViewById(R.id.priority);
ul_rateP.setText("" + ul_rate);
dl_rateP.setText("" + dl_rate);
max_peersP.setText("" + max_peers);
seedRatioP.setText("" + seedingRatio);
// Try to find the right value
int position = 0;
for (int iLoop = 0; iLoop < seedingTimes.length; iLoop++) {
if (seedingTimes[iLoop] == seedingTime) {
position = iLoop;
break;
}
}
seedTimeP.setSelection(position);
// Try to find the right value
position = 0;
for (int iLoop = 0; iLoop < priorities.length; iLoop++) {
if (priorities[iLoop] == priority) {
position = iLoop;
break;
}
}
priorityP.setSelection(position);
// Try to find the right value
position = 0;
ArrayAdapter<String> sa = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, destinations);
sa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
for (int iLoop = 0; iLoop < destinations.length; iLoop++) {
if (destinations[iLoop] == destination) {
position = iLoop;
}
}
destinationP.setAdapter(sa);
destinationP.setSelection(position);
break;
}
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch (id) {
// Create the task's parameters dialog
case TASK_PARAMETERS_DIALOG:
// Create the view
View container = inflater.inflate(R.layout.seeding_parameters, null, false);
final EditText seedRatio = (EditText) container.findViewById(R.id.seedingPercentage);
final Spinner seedTime = (Spinner) container.findViewById(R.id.seedingTime);
// Create the dialog
builder.setTitle(getString(R.string.seeding_parameters_time));
builder.setView(container);
builder.setPositiveButton(getString(R.string.button_ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogP, int whichP) {
seedingChanged = true;
try {
int seedR = Integer.parseInt(seedRatio.getText().toString());
seedingRatio = seedR;
int pos = seedTime.getSelectedItemPosition();
seedingTime = seedingTimes[pos];
// At the end, update the task.
updateTask(true);
}
// The ratio is not an integer
catch (NumberFormatException ex) {
// NTD: the input method does not allow to set a float or
// a string
}
}
});
builder.setNegativeButton(getString(R.string.button_cancel), null);
return builder.create();
case TASK_PROPERTIES_DIALOG:
// Create the view
View containerP = inflater.inflate(R.layout.task_properties, null, false);
final EditText seedRatioP = (EditText) containerP.findViewById(R.id.seedingPercentage);
final EditText ul_rateP = (EditText) containerP.findViewById(R.id.ul_rate);
final EditText dl_rateP = (EditText) containerP.findViewById(R.id.dl_rate);
final EditText max_peersP = (EditText) containerP.findViewById(R.id.max_peers);
final Spinner destinationP = (Spinner) containerP.findViewById(R.id.destination);
final Spinner priorityP = (Spinner) containerP.findViewById(R.id.priority);
final Spinner seedTimeP = (Spinner) containerP.findViewById(R.id.seedingTime);
// Create the dialog
builder.setTitle(getString(R.string.task_parameters));
builder.setView(containerP);
builder.setPositiveButton(getString(R.string.button_ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogP, int whichP) {
seedingChanged = true;
try {
ul_rate = Integer.parseInt(ul_rateP.getText().toString());
dl_rate = Integer.parseInt(dl_rateP.getText().toString());
max_peers = Integer.parseInt(max_peersP.getText().toString());
destination = destinations[destinationP.getSelectedItemPosition()];
priority = priorities[priorityP.getSelectedItemPosition()];
int seedR = Integer.parseInt(seedRatioP.getText().toString());
seedingRatio = seedR;
int pos = seedTimeP.getSelectedItemPosition();
seedingTime = seedingTimes[pos];
// At the end, update the task.
updateTask(true);
}
// The ratio is not an integer
catch (NumberFormatException ex) {
// NTD: the input method does not allow to set a float or
// a string
}
}
});
builder.setNegativeButton(getString(R.string.button_cancel), null);
return builder.create();
default:
return null;
}
}
@SuppressWarnings("unchecked")
public void handleMessage(Message msgP) {
Synodroid app = (Synodroid) getApplication();
DetailMain main = (DetailMain) mAdapter.getItem(MAIN_ITEM);
DetailFiles files = (DetailFiles)mAdapter.getItem(FILE_ITEM);
if (((Synodroid)getApplication()).DEBUG) Log.d(Synodroid.DS_TAG, "DetailActivity: Message received with ID = "+ msgP.what);
switch (msgP.what) {
case ResponseHandler.MSG_DETAILS_FILES_RETRIEVED:
List<TaskFile> tfile = (List<TaskFile>) msgP.obj;
try{
files.fileAdapter.updateFiles(tfile);
} catch (Exception e) {
Log.e(Synodroid.DS_TAG, "An error occured while trying to update files list:", e);
}
break;
case ResponseHandler.MSG_PROPERTIES_RECEIVED:
TaskProperties tp = (TaskProperties) msgP.obj;
ul_rate = tp.ul_rate;
dl_rate = tp.dl_rate;
max_peers = tp.max_peers;
priority = tp.priority;
seedingRatio = tp.seeding_ratio;
seedingTime = tp.seeding_interval;
destination = tp.destination;
try {
showDialog(TASK_PROPERTIES_DIALOG);
} catch (Exception e) {
}
break;
case ResponseHandler.MSG_SHARED_DIRECTORIES_RETRIEVED:
List<SharedDirectory> newDirs = (List<SharedDirectory>) msgP.obj;
destinations = new String[newDirs.size()];
for (int iLoop = 0; iLoop < newDirs.size(); iLoop++) {
SharedDirectory sharedDir = newDirs.get(iLoop);
destinations[iLoop] = sharedDir.name;
if (sharedDir.isCurrent) {
destination = sharedDir.name;
}
}
app.executeAsynchronousAction(main, new GetTaskPropertiesAction(task), false, false);
break;
// Details updated
case ResponseHandler.MSG_DETAILS_RETRIEVED:
TaskDetail details = (TaskDetail) msgP.obj;
if (!task.isTorrent && !task.isNZB && files != null){
files.updateEmptyValues(getString(R.string.empty_file_list_wrong_type), false);
}
if (!task.status.equals(details.status) && files != null && (task.isTorrent || task.isNZB)){
if (details.status.equals(TaskStatus.TASK_DOWNLOADING.name())) {
files.updateEmptyValues(getString(R.string.empty_list_loading), true);
app.executeAsynchronousAction(main, new GetFilesAction(task), false);
}
else{
files.updateEmptyValues(getString(R.string.empty_file_list), false);
files.resetList();
}
}
task.status = details.status;
task.isTorrent = details.isTorrent;
task.isNZB = details.isNZB;
if (main != null){
main.genAdapter.updateDetails(buildGeneralDetails(details));
((DetailTransfer)mAdapter.getItem(TRANSFER_ITEM)).transAdapter.updateDetails(buildTransferDetails(details));
}
getIntent().putExtra("com.bigpupdev.synodroid.ds.Details", task);
setStatus(details.getStatus());
updateActionBarTitle(details.fileName);
if (UIUtils.isICS()){
invalidateOptionsMenu();
}
break;
case ResponseHandler.MSG_ERROR:
SynoServer server = ((Synodroid) getApplication()).getServer();
if (server != null)
server.setLastError((String) msgP.obj);
main.showError(server.getLastError(), null);
break;
case ResponseHandler.MSG_ORIGINAL_FILE_RETRIEVED:
OriginalFile oriFile = (OriginalFile) msgP.obj;
File path = Environment.getExternalStorageDirectory();
path = new File(path, "download");
File file = new File(path, oriFile.fileName);
try {
// Make sure the Pictures directory exists.
path.mkdirs();
StringBuffer rawData = oriFile.rawData;
OutputStream os = new FileOutputStream(file);
os.write(rawData.toString().getBytes());
os.close();
Toast toast = Toast.makeText(this, getString(R.string.action_download_original_saved), Toast.LENGTH_SHORT);
toast.show();
} catch (Exception e) {
// Unable to create file, likely because external storage is
// not currently mounted.
if (((Synodroid)getApplication()).DEBUG) Log.w(Synodroid.DS_TAG, "Error writing " + file + " to SDCard.", e);
Toast toast = Toast.makeText(this, getString(R.string.action_download_original_failed), Toast.LENGTH_LONG);
toast.show();
}
break;
default:
if (((Synodroid)getApplication()).DEBUG) Log.d(Synodroid.DS_TAG, "DetailActivity: Ignored message ID = "+ msgP.what);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!UIUtils.isHoneycomb()){
getMenuInflater().inflate(R.menu.refresh_menu_items, menu);
}
super.onCreateOptionsMenu(menu);
return true;
}
/**
* Create the option menu of this activity
*/
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if (UIUtils.isHoneycomb()){
getMenuInflater().inflate(R.menu.refresh_menu_items, menu);
}
if (status != null) {
switch (status) {
case TASK_DOWNLOADING:
menu.add(0, MENU_PAUSE, 0, getString(R.string.action_pause)).setIcon(R.drawable.ic_menu_pause);
menu.add(0, MENU_DELETE, 0, getString(R.string.action_delete)).setIcon(android.R.drawable.ic_menu_delete);
break;
case TASK_PRE_SEEDING:
case TASK_SEEDING:
menu.add(0, MENU_PAUSE, 0, getString(R.string.action_pause)).setIcon(R.drawable.ic_menu_pause);
menu.add(0, MENU_CANCEL, 0, getString(R.string.action_cancel)).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
break;
case TASK_PAUSED:
menu.add(0, MENU_RESUME, 0, getString(R.string.action_resume)).setIcon(android.R.drawable.ic_menu_revert);
menu.add(0, MENU_DELETE, 0, getString(R.string.action_delete)).setIcon(android.R.drawable.ic_menu_delete);
break;
case TASK_ERROR:
case TASK_ERROR_DEST_NO_EXIST:
case TASK_ERROR_DEST_DENY:
case TASK_ERROR_QUOTA_REACHED:
case TASK_ERROR_TIMEOUT:
case TASK_ERROR_EXCEED_MAX_FS_SIZE:
case TASK_ERROR_BROKEN_LINK:
case TASK_ERROR_DISK_FULL:
case TASK_ERROR_EXCEED_MAX_TEMP_FS_SIZE:
case TASK_UNKNOWN:
case TASK_ERROR_EXCEED_MAX_DEST_FS_SIZE:
menu.add(0, MENU_RETRY, 0, getString(R.string.action_retry)).setIcon(android.R.drawable.ic_menu_revert);
menu.add(0, MENU_DELETE, 0, getString(R.string.action_delete)).setIcon(android.R.drawable.ic_menu_delete);
break;
case TASK_FINISHED:
menu.add(0, MENU_RESUME, 0, getString(R.string.action_resume)).setIcon(android.R.drawable.ic_menu_revert);
case TASK_FINISHING:
menu.add(0, MENU_CLEAR, 0, getString(R.string.action_clear)).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
break;
case TASK_HASH_CHECKING:
case TASK_WAITING:
menu.add(0, MENU_PAUSE, 0, getString(R.string.action_pause)).setIcon(R.drawable.ic_menu_pause);
menu.add(0, MENU_DELETE, 0, getString(R.string.action_delete)).setIcon(android.R.drawable.ic_menu_delete);
break;
}
}
if (task.isTorrent) {
if (task.getStatus() == TaskStatus.TASK_DOWNLOADING || task.getStatus() == TaskStatus.TASK_SEEDING) {
menu.add(0, MENU_PARAMETERS, 0, getString(R.string.task_parameters)).setIcon(android.R.drawable.ic_menu_preferences).setEnabled(true);
} else {
menu.add(0, MENU_PARAMETERS, 0, getString(R.string.task_parameters)).setIcon(android.R.drawable.ic_menu_preferences).setEnabled(false);
}
}
return super.onPrepareOptionsMenu(menu);
}
/**
* Interact with the user when a menu is selected
*/
public boolean onOptionsItemSelected(MenuItem item) {
Synodroid app = (Synodroid) getApplication();
DetailMain main = (DetailMain)mAdapter.getItem(MAIN_ITEM);
if (item.getItemId() == R.id.menu_refresh) {
((Synodroid) getApplication()).forceRefresh();
return true;
}
else if (item.getItemId() == MENU_PAUSE){
app.executeAction(main, new PauseTaskAction(task), true);
return true;
}
else if (item.getItemId() == MENU_DELETE || item.getItemId() == MENU_CANCEL || item.getItemId() == MENU_CLEAR){
app.executeAction(main, new DeleteTaskAction(task), true);
return true;
}
else if (item.getItemId() == MENU_RESUME || item.getItemId() == MENU_RETRY){
app.executeAction(main, new ResumeTaskAction(task), true);
return true;
}
else if (item.getItemId() == MENU_PARAMETERS){
if (app.getServer().getDsmVersion() == DSMVersion.VERSION3_1 || app.getServer().getDsmVersion() == DSMVersion.VERSION3_2) {
app.executeAsynchronousAction(main, new EnumShareAction(), false, false);
} else {
try {
showDialog(TASK_PARAMETERS_DIALOG);
} catch (Exception e) {
// Dialog failed to display. Probably already displayed. Ignore!
}
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void updateRefreshStatus(boolean refreshing) {
getActivityHelper().setRefreshActionButtonCompatState(refreshing);
}
@Override
public boolean onSearchRequested() {
return false;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation change
super.onConfigurationChanged(newConfig);
}
/**
* Update the current task
*/
public void updateTask(boolean forceRefreshP) {
Synodroid app = (Synodroid) getApplication();
DetailMain main = (DetailMain)mAdapter.getItem(MAIN_ITEM);
DetailFiles files = (DetailFiles)mAdapter.getItem(FILE_ITEM);
List<TaskFile> modifiedTaskFiles = null;
SynoServer server = null;
try {
server = app.getServer();
} catch (Exception e) {
}
if (server != null) {
if (server.getDsmVersion() == DSMVersion.VERSION3_1 || server.getDsmVersion() == DSMVersion.VERSION3_2) {
if (files != null && files.fileAdapter != null){
modifiedTaskFiles = files.fileAdapter.getModifiedTaskList();
}
else{
modifiedTaskFiles = new ArrayList<TaskFile>();
}
if (modifiedTaskFiles != null && modifiedTaskFiles.size() > 0) {
UpdateFilesAction update = new UpdateFilesAction(task, modifiedTaskFiles);
app.getServer().executeAsynchronousAction(main, update, forceRefreshP);
seedingChanged = false;
} else if (seedingChanged) {
UpdateTaskPropertiesAction update = new UpdateTaskPropertiesAction(task, ul_rate, dl_rate, priority, max_peers, destination, seedingRatio, seedingTime);
app.getServer().executeAsynchronousAction(main, update, forceRefreshP);
seedingChanged = false;
}
} else {
if (files != null){
modifiedTaskFiles = files.fileAdapter.getModifiedTaskList();
}
else{
modifiedTaskFiles = new ArrayList<TaskFile>();
}
if ((modifiedTaskFiles != null && modifiedTaskFiles.size() > 0) || (seedingChanged)) {
UpdateTaskAction update = new UpdateTaskAction(task, modifiedTaskFiles, seedingRatio, seedingTime);
app.getServer().executeAsynchronousAction(main, update, forceRefreshP);
seedingChanged = false;
}
}
}
}
public static class MyAdapter extends FragmentPagerAdapter implements ViewPagerIndicator.PageInfoProvider{
int mItemsNum;
private DetailActivity mCurActivity;
private DetailMain main;
private DetailFiles files;
private DetailTransfer transfer;
public MyAdapter(FragmentManager pFm, int pItemNum, DetailActivity pCurActivity) {
super(pFm);
mItemsNum = pItemNum;
mCurActivity = pCurActivity;
}
/**
* This override prevents the pager to destroy non adjacent pages.
*/
@Override
public void destroyItem(View container, int position, Object object){
Log.d(Synodroid.DS_TAG, "View pager attemps to destroy pager number: "+position);
if (position == 2){
mCurActivity.updateTask(false);
}
}
@Override
public int getCount() {
return mItemsNum;
}
@Override
public Fragment getItem(int position) {
if (position == 0){
if (main == null)
main = new DetailMain();
return main;
}
else if (position == 1){
if (transfer == null)
transfer = new DetailTransfer();
return transfer;
}
else{
if (files == null)
files = new DetailFiles();
return files;
}
}
public String getTitle(int pos){
if (pos == 0)
return mCurActivity.getString(R.string.tab_main);
else if (pos == 1)
return mCurActivity.getString(R.string.tab_transfer);
else
return mCurActivity.getString(R.string.tab_file);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!EulaHelper.hasAcceptedEula(this)) {
EulaHelper.showEula(false, this);
}
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
task = (Task) intent.getSerializableExtra("com.bigpupdev.synodroid.ds.Details");
mAdapter = new MyAdapter(getSupportFragmentManager(), 3, this);
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
// Find the indicator from the layout
mIndicator = (ViewPagerIndicator)findViewById(R.id.indicator);
// Set the indicator as the pageChangeListener
mPager.setOnPageChangeListener(mIndicator);
// Initialize the indicator. We need some information here:
// * What page do we start on.
// * How many pages are there in total
// * A callback to get page titles
mIndicator.init(0, mAdapter.getCount(), mAdapter);
Resources res = getResources();
Drawable prev = res.getDrawable(R.drawable.indicator_prev_arrow);
Drawable next = res.getDrawable(R.drawable.indicator_next_arrow);
mIndicator.setFocusedTextColor(new int[]{255, 255, 255});
mIndicator.setUnfocusedTextColor(new int[]{120, 120, 120});
// Set images for previous and next arrows.
mIndicator.setArrows(prev, next);
mIndicator.setOnClickListener(new OnIndicatorClickListener());
// Create the seeding time int array
String[] timesArray = getResources().getStringArray(R.array.seeding_time_array_values);
seedingTimes = new int[timesArray.length];
for (int iLoop = 0; iLoop < timesArray.length; iLoop++) {
seedingTimes[iLoop] = Integer.parseInt(timesArray[iLoop]);
}
String[] priorityArray = getResources().getStringArray(R.array.priority_array_value);
priorities = new int[priorityArray.length];
for (int iLoop = 0; iLoop < priorityArray.length; iLoop++) {
priorities[iLoop] = Integer.parseInt(priorityArray[iLoop]);
}
getActivityHelper().setupActionBar(task.fileName, false);
}
class OnIndicatorClickListener implements ViewPagerIndicator.OnClickListener{
public void onCurrentClicked(View v) {}
public void onNextClicked(View v) {
mPager.setCurrentItem(Math.min(mAdapter.getCount() - 1, mIndicator.getCurrentPosition() + 1));
}
public void onPreviousClicked(View v) {
mPager.setCurrentItem(Math.max(0, mIndicator.getCurrentPosition() - 1));
}
}
}
| true | true | private List<Detail> buildTransferDetails(TaskDetail details) {
ArrayList<Detail> result = new ArrayList<Detail>();
// Set the result to be returned to the previous activity
Intent previous = new Intent();
previous.putExtra("com.bigpupdev.synodroid.ds.Details", details);
setResult(Activity.RESULT_OK, previous);
// ------------ Status
try {
result.add(new DetailText(getString(R.string.detail_status), TaskStatus.getLabel(this, details.status)));
} catch (NullPointerException e) {
result.add(new DetailText(getString(R.string.detail_status), getString(R.string.detail_unknown)));
} catch (IllegalArgumentException e) {
result.add(new DetailText(getString(R.string.detail_status), getString(R.string.detail_unknown)));
}
// ------------ Transfered
String transfered = getString(R.string.detail_progress_download) + " " + Utils.bytesToFileSize(details.bytesDownloaded, true, getString(R.string.detail_unknown));
if (details.isTorrent) {
String upload = getString(R.string.detail_progress_upload) + " " + Utils.bytesToFileSize(details.bytesUploaded, true, getString(R.string.detail_unknown)) + " (" + details.bytesRatio + " %)";
Detail2Text tr = new Detail2Text(getString(R.string.detail_transfered));
tr.setValue1(transfered);
tr.setValue2(upload);
result.add(tr);
} else {
result.add(new DetailText(getString(R.string.detail_transfered), transfered));
}
// ------------- Progress
long downloaded = details.bytesDownloaded;
long filesize = details.fileSize;
String downPerStr = getString(R.string.detail_unknown);
int downPer = 0;
if (filesize != -1) {
try {
downPer = (int) ((downloaded * 100) / filesize);
} catch (ArithmeticException e) {
downPer = 100;
}
downPerStr = "" + downPer + "%";
}
int upPerc = 0;
String upPercStr = getString(R.string.detail_unknown);
Integer uploadPercentage = Utils.computeUploadPercent(details);
if (uploadPercentage != null) {
upPerc = uploadPercentage.intValue();
upPercStr = "" + upPerc + "%";
}
// If it is a torrent
Detail proDetail = null;
if (details.isTorrent) {
Detail2Progress progDetail = new Detail2Progress(getString(R.string.detail_progress));
proDetail = progDetail;
progDetail.setProgress1(getString(R.string.detail_progress_download) + " " + downPerStr, downPer);
progDetail.setProgress2(getString(R.string.detail_progress_upload) + " " + upPercStr, upPerc);
} else {
DetailProgress progDetail = new DetailProgress(getString(R.string.detail_progress), R.layout.details_progress_template1);
proDetail = progDetail;
progDetail.setProgress(getString(R.string.detail_progress_download) + " " + downPerStr, downPer);
}
result.add(proDetail);
// ------------ Speed
String speed = getString(R.string.detail_progress_download) + " " + details.speedDownload + " KB/s";
if (details.isTorrent) {
speed = speed + " - " + getString(R.string.detail_progress_upload) + " " + details.speedUpload + " KB/s";
}
result.add(new DetailText(getString(R.string.detail_speed), speed));
// ------------ Peers
if (details.isTorrent) {
String peers = details.peersCurrent + " / " + details.peersTotal;
DetailProgress peersDetail = new DetailProgress(getString(R.string.detail_peers), R.layout.details_progress_template2);
int pProgress = 0;
if (details.peersTotal != 0) {
pProgress = (int) ((details.peersCurrent * 100) / details.peersTotal);
}
peersDetail.setProgress(peers, pProgress);
result.add(peersDetail);
}
// ------------ Seeders / Leechers
if (details.isTorrent) {
String seedStr = getString(R.string.detail_unvailable);
String leechStr = getString(R.string.detail_unvailable);
if (details.seeders != null)
seedStr = details.seeders.toString();
if (details.leechers != null)
leechStr = details.leechers.toString();
String seeders = seedStr + " - " + leechStr;
result.add(new DetailText(getString(R.string.detail_seeders_leechers), seeders));
}
// ------------ ETAs
String etaUpload = getString(R.string.detail_unknown);
String etaDownload = getString(R.string.detail_unknown);
if (details.speedDownload != 0) {
long sizeLeft = filesize - downloaded;
long timeLeft = (long) (sizeLeft / (details.speedDownload * 1000));
etaDownload = Utils.computeTimeLeft(timeLeft);
} else {
if (downPer == 100) {
etaDownload = getString(R.string.detail_finished);
}
}
Long timeLeftSize = null;
long uploaded = details.bytesUploaded;
double ratio = ((double) (details.seedingRatio)) / 100.0d;
if (details.speedUpload != 0 && details.seedingRatio != 0) {
long sizeLeft = (long) ((filesize * ratio) - uploaded);
timeLeftSize = (long) (sizeLeft / (details.speedUpload * 1000));
}
// If the user defined a minimum seeding time AND we are in seeding
// mode
TaskStatus tsk_status = details.getStatus();
Long timeLeftTime = null;
if (details.seedingInterval != 0 && tsk_status == TaskStatus.TASK_SEEDING) {
timeLeftTime = (details.seedingInterval * 60) - details.seedingElapsed;
if (timeLeftTime < 0) {
timeLeftTime = null;
}
}
// At least one time has been computed
if (timeLeftTime != null || timeLeftSize != null) {
// By default take the size time
Long time = timeLeftSize;
// Except if it is null
if (timeLeftSize == null) {
time = timeLeftTime;
} else {
// If time is not null
if (timeLeftTime != null) {
// Get the higher value
if (timeLeftTime > timeLeftSize) {
time = timeLeftTime;
}
}
}
etaUpload = Utils.computeTimeLeft(time);
} else if (upPerc == 100) {
etaUpload = getString(R.string.detail_finished);
}
// In case the user set the seedin time to forever
if (details.seedingInterval == -1) {
etaUpload = getString(R.string.detail_forever);
}
Detail etaDet = null;
// If it is a torrent then show the upload ETA
if (details.isTorrent) {
Detail2Text etaDetail = new Detail2Text(getString(R.string.detail_eta));
etaDet = etaDetail;
etaDetail.setValue1(getString(R.string.detail_progress_download) + " " + etaDownload);
etaDetail.setValue2(getString(R.string.detail_progress_upload) + " " + etaUpload);
}
// Otherwise only show the download ETA
else {
DetailText etaDetail = new DetailText(getString(R.string.detail_eta));
etaDet = etaDetail;
etaDetail.setValue(getString(R.string.detail_progress_download) + " " + etaDownload);
}
result.add(etaDet);
// ------------ Pieces
if (details.isTorrent) {
String pieces = details.piecesCurrent + " / " + details.piecesTotal;
DetailProgress piecesDetail = new DetailProgress(getString(R.string.detail_pieces), R.layout.details_progress_template2);
int piProgress = 0;
if (details.piecesTotal != 0) {
piProgress = (int) ((details.piecesCurrent * 100) / details.piecesTotal);
}
piecesDetail.setProgress(pieces, piProgress);
result.add(piecesDetail);
}
// Update seeding parameters
seedingRatio = details.seedingRatio;
seedingTime = details.seedingInterval;
return result;
}
| private List<Detail> buildTransferDetails(TaskDetail details) {
ArrayList<Detail> result = new ArrayList<Detail>();
// Set the result to be returned to the previous activity
Intent previous = new Intent();
previous.putExtra("com.bigpupdev.synodroid.ds.Details", details);
setResult(Activity.RESULT_OK, previous);
// ------------ Status
try {
result.add(new DetailText(getString(R.string.detail_status), TaskStatus.getLabel(this, details.status)));
} catch (NullPointerException e) {
result.add(new DetailText(getString(R.string.detail_status), getString(R.string.detail_unknown)));
} catch (IllegalArgumentException e) {
result.add(new DetailText(getString(R.string.detail_status), getString(R.string.detail_unknown)));
}
// ------------ Transfered
String transfered = getString(R.string.detail_progress_download) + " " + Utils.bytesToFileSize(details.bytesDownloaded, true, getString(R.string.detail_unknown));
if (details.isTorrent) {
String upload = getString(R.string.detail_progress_upload) + " " + Utils.bytesToFileSize(details.bytesUploaded, true, getString(R.string.detail_unknown)) + " (" + details.bytesRatio + " %)";
Detail2Text tr = new Detail2Text(getString(R.string.detail_transfered));
tr.setValue1(transfered);
tr.setValue2(upload);
result.add(tr);
} else {
result.add(new DetailText(getString(R.string.detail_transfered), transfered));
}
// ------------- Progress
long downloaded = details.bytesDownloaded;
long filesize = details.fileSize;
String downPerStr = getString(R.string.detail_unknown);
int downPer = 0;
if (filesize != -1) {
try {
downPer = (int) ((downloaded * 100) / filesize);
} catch (ArithmeticException e) {
downPer = 100;
}
if (downPer == 100 && downloaded != filesize){
downPer = 99;
}
downPerStr = "" + downPer + "%";
}
int upPerc = 0;
String upPercStr = getString(R.string.detail_unknown);
Integer uploadPercentage = Utils.computeUploadPercent(details);
if (uploadPercentage != null) {
upPerc = uploadPercentage.intValue();
upPercStr = "" + upPerc + "%";
}
// If it is a torrent
Detail proDetail = null;
if (details.isTorrent) {
Detail2Progress progDetail = new Detail2Progress(getString(R.string.detail_progress));
proDetail = progDetail;
progDetail.setProgress1(getString(R.string.detail_progress_download) + " " + downPerStr, downPer);
progDetail.setProgress2(getString(R.string.detail_progress_upload) + " " + upPercStr, upPerc);
} else {
DetailProgress progDetail = new DetailProgress(getString(R.string.detail_progress), R.layout.details_progress_template1);
proDetail = progDetail;
progDetail.setProgress(getString(R.string.detail_progress_download) + " " + downPerStr, downPer);
}
result.add(proDetail);
// ------------ Speed
String speed = getString(R.string.detail_progress_download) + " " + details.speedDownload + " KB/s";
if (details.isTorrent) {
speed = speed + " - " + getString(R.string.detail_progress_upload) + " " + details.speedUpload + " KB/s";
}
result.add(new DetailText(getString(R.string.detail_speed), speed));
// ------------ Peers
if (details.isTorrent) {
String peers = details.peersCurrent + " / " + details.peersTotal;
DetailProgress peersDetail = new DetailProgress(getString(R.string.detail_peers), R.layout.details_progress_template2);
int pProgress = 0;
if (details.peersTotal != 0) {
pProgress = (int) ((details.peersCurrent * 100) / details.peersTotal);
}
peersDetail.setProgress(peers, pProgress);
result.add(peersDetail);
}
// ------------ Seeders / Leechers
if (details.isTorrent) {
String seedStr = getString(R.string.detail_unvailable);
String leechStr = getString(R.string.detail_unvailable);
if (details.seeders != null)
seedStr = details.seeders.toString();
if (details.leechers != null)
leechStr = details.leechers.toString();
String seeders = seedStr + " - " + leechStr;
result.add(new DetailText(getString(R.string.detail_seeders_leechers), seeders));
}
// ------------ ETAs
String etaUpload = getString(R.string.detail_unknown);
String etaDownload = getString(R.string.detail_unknown);
if (details.speedDownload != 0) {
long sizeLeft = filesize - downloaded;
long timeLeft = (long) (sizeLeft / (details.speedDownload * 1000));
etaDownload = Utils.computeTimeLeft(timeLeft);
} else {
if (downPer == 100) {
etaDownload = getString(R.string.detail_finished);
}
}
Long timeLeftSize = null;
long uploaded = details.bytesUploaded;
double ratio = ((double) (details.seedingRatio)) / 100.0d;
if (details.speedUpload != 0 && details.seedingRatio != 0) {
long sizeLeft = (long) ((filesize * ratio) - uploaded);
timeLeftSize = (long) (sizeLeft / (details.speedUpload * 1000));
}
// If the user defined a minimum seeding time AND we are in seeding
// mode
TaskStatus tsk_status = details.getStatus();
Long timeLeftTime = null;
if (details.seedingInterval != 0 && tsk_status == TaskStatus.TASK_SEEDING) {
timeLeftTime = (details.seedingInterval * 60) - details.seedingElapsed;
if (timeLeftTime < 0) {
timeLeftTime = null;
}
}
// At least one time has been computed
if (timeLeftTime != null || timeLeftSize != null) {
// By default take the size time
Long time = timeLeftSize;
// Except if it is null
if (timeLeftSize == null) {
time = timeLeftTime;
} else {
// If time is not null
if (timeLeftTime != null) {
// Get the higher value
if (timeLeftTime > timeLeftSize) {
time = timeLeftTime;
}
}
}
etaUpload = Utils.computeTimeLeft(time);
} else if (upPerc == 100) {
etaUpload = getString(R.string.detail_finished);
}
// In case the user set the seedin time to forever
if (details.seedingInterval == -1) {
etaUpload = getString(R.string.detail_forever);
}
Detail etaDet = null;
// If it is a torrent then show the upload ETA
if (details.isTorrent) {
Detail2Text etaDetail = new Detail2Text(getString(R.string.detail_eta));
etaDet = etaDetail;
etaDetail.setValue1(getString(R.string.detail_progress_download) + " " + etaDownload);
etaDetail.setValue2(getString(R.string.detail_progress_upload) + " " + etaUpload);
}
// Otherwise only show the download ETA
else {
DetailText etaDetail = new DetailText(getString(R.string.detail_eta));
etaDet = etaDetail;
etaDetail.setValue(getString(R.string.detail_progress_download) + " " + etaDownload);
}
result.add(etaDet);
// ------------ Pieces
if (details.isTorrent) {
String pieces = details.piecesCurrent + " / " + details.piecesTotal;
DetailProgress piecesDetail = new DetailProgress(getString(R.string.detail_pieces), R.layout.details_progress_template2);
int piProgress = 0;
if (details.piecesTotal != 0) {
piProgress = (int) ((details.piecesCurrent * 100) / details.piecesTotal);
}
piecesDetail.setProgress(pieces, piProgress);
result.add(piecesDetail);
}
// Update seeding parameters
seedingRatio = details.seedingRatio;
seedingTime = details.seedingInterval;
return result;
}
|
diff --git a/src/com/android/calendar/month/MonthWeekEventsView.java b/src/com/android/calendar/month/MonthWeekEventsView.java
index 99c8f0e7..e1c78c67 100644
--- a/src/com/android/calendar/month/MonthWeekEventsView.java
+++ b/src/com/android/calendar/month/MonthWeekEventsView.java
@@ -1,1109 +1,1110 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.calendar.month;
import com.android.calendar.Event;
import com.android.calendar.R;
import com.android.calendar.Utils;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Service;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.provider.CalendarContract.Attendees;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
import android.text.format.Time;
import android.util.Log;
import android.view.MotionEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
public class MonthWeekEventsView extends SimpleWeekView {
private static final String TAG = "MonthView";
private static final boolean DEBUG_LAYOUT = false;
public static final String VIEW_PARAMS_ORIENTATION = "orientation";
public static final String VIEW_PARAMS_ANIMATE_TODAY = "animate_today";
/* NOTE: these are not constants, and may be multiplied by a scale factor */
private static int TEXT_SIZE_MONTH_NUMBER = 32;
private static int TEXT_SIZE_EVENT = 12;
private static int TEXT_SIZE_EVENT_TITLE = 14;
private static int TEXT_SIZE_MORE_EVENTS = 12;
private static int TEXT_SIZE_MONTH_NAME = 14;
private static int TEXT_SIZE_WEEK_NUM = 12;
private static int DNA_MARGIN = 4;
private static int DNA_ALL_DAY_HEIGHT = 4;
private static int DNA_MIN_SEGMENT_HEIGHT = 4;
private static int DNA_WIDTH = 8;
private static int DNA_ALL_DAY_WIDTH = 32;
private static int DNA_SIDE_PADDING = 6;
private static int CONFLICT_COLOR = Color.BLACK;
private static int EVENT_TEXT_COLOR = Color.WHITE;
private static int DEFAULT_EDGE_SPACING = 0;
private static int SIDE_PADDING_MONTH_NUMBER = 4;
private static int TOP_PADDING_MONTH_NUMBER = 4;
private static int TOP_PADDING_WEEK_NUMBER = 4;
private static int SIDE_PADDING_WEEK_NUMBER = 20;
private static int DAY_SEPARATOR_OUTER_WIDTH = 0;
private static int DAY_SEPARATOR_INNER_WIDTH = 1;
private static int DAY_SEPARATOR_VERTICAL_LENGTH = 53;
private static int DAY_SEPARATOR_VERTICAL_LENGHT_PORTRAIT = 64;
private static int MIN_WEEK_WIDTH = 50;
private static int EVENT_X_OFFSET_LANDSCAPE = 38;
private static int EVENT_Y_OFFSET_LANDSCAPE = 8;
private static int EVENT_Y_OFFSET_PORTRAIT = 7;
private static int EVENT_SQUARE_WIDTH = 10;
private static int EVENT_SQUARE_BORDER = 2;
private static int EVENT_LINE_PADDING = 2;
private static int EVENT_RIGHT_PADDING = 4;
private static int EVENT_BOTTOM_PADDING = 3;
private static int TODAY_HIGHLIGHT_WIDTH = 2;
private static int SPACING_WEEK_NUMBER = 24;
private static boolean mInitialized = false;
private static boolean mShowDetailsInMonth;
protected Time mToday = new Time();
protected boolean mHasToday = false;
protected int mTodayIndex = -1;
protected int mOrientation = Configuration.ORIENTATION_LANDSCAPE;
protected List<ArrayList<Event>> mEvents = null;
protected ArrayList<Event> mUnsortedEvents = null;
HashMap<Integer, Utils.DNAStrand> mDna = null;
// This is for drawing the outlines around event chips and supports up to 10
// events being drawn on each day. The code will expand this if necessary.
protected FloatRef mEventOutlines = new FloatRef(10 * 4 * 4 * 7);
protected static StringBuilder mStringBuilder = new StringBuilder(50);
// TODO recreate formatter when locale changes
protected static Formatter mFormatter = new Formatter(mStringBuilder, Locale.getDefault());
protected Paint mMonthNamePaint;
protected TextPaint mEventPaint;
protected TextPaint mSolidBackgroundEventPaint;
protected TextPaint mFramedEventPaint;
protected TextPaint mDeclinedEventPaint;
protected TextPaint mEventExtrasPaint;
protected TextPaint mEventDeclinedExtrasPaint;
protected Paint mWeekNumPaint;
protected Paint mDNAAllDayPaint;
protected Paint mDNATimePaint;
protected Paint mEventSquarePaint;
protected Drawable mTodayDrawable;
protected int mMonthNumHeight;
protected int mMonthNumAscentHeight;
protected int mEventHeight;
protected int mEventAscentHeight;
protected int mExtrasHeight;
protected int mExtrasAscentHeight;
protected int mExtrasDescent;
protected int mWeekNumAscentHeight;
protected int mMonthBGColor;
protected int mMonthBGOtherColor;
protected int mMonthBGTodayColor;
protected int mMonthNumColor;
protected int mMonthNumOtherColor;
protected int mMonthNumTodayColor;
protected int mMonthNameColor;
protected int mMonthNameOtherColor;
protected int mMonthEventColor;
protected int mMonthDeclinedEventColor;
protected int mMonthDeclinedExtrasColor;
protected int mMonthEventExtraColor;
protected int mMonthEventOtherColor;
protected int mMonthEventExtraOtherColor;
protected int mMonthWeekNumColor;
protected int mMonthBusyBitsBgColor;
protected int mMonthBusyBitsBusyTimeColor;
protected int mMonthBusyBitsConflictTimeColor;
private int mClickedDayIndex = -1;
private int mClickedDayColor;
private static final int mClickedAlpha = 128;
protected int mEventChipOutlineColor = 0xFFFFFFFF;
protected int mDaySeparatorInnerColor;
protected int mTodayAnimateColor;
private boolean mAnimateToday;
private int mAnimateTodayAlpha = 0;
private ObjectAnimator mTodayAnimator = null;
private final TodayAnimatorListener mAnimatorListener = new TodayAnimatorListener();
class TodayAnimatorListener extends AnimatorListenerAdapter {
private volatile Animator mAnimator = null;
private volatile boolean mFadingIn = false;
@Override
public void onAnimationEnd(Animator animation) {
synchronized (this) {
if (mAnimator != animation) {
animation.removeAllListeners();
animation.cancel();
return;
}
if (mFadingIn) {
if (mTodayAnimator != null) {
mTodayAnimator.removeAllListeners();
mTodayAnimator.cancel();
}
mTodayAnimator = ObjectAnimator.ofInt(MonthWeekEventsView.this,
"animateTodayAlpha", 255, 0);
mAnimator = mTodayAnimator;
mFadingIn = false;
mTodayAnimator.addListener(this);
mTodayAnimator.setDuration(600);
mTodayAnimator.start();
} else {
mAnimateToday = false;
mAnimateTodayAlpha = 0;
mAnimator.removeAllListeners();
mAnimator = null;
mTodayAnimator = null;
invalidate();
}
}
}
public void setAnimator(Animator animation) {
mAnimator = animation;
}
public void setFadingIn(boolean fadingIn) {
mFadingIn = fadingIn;
}
}
private int[] mDayXs;
/**
* This provides a reference to a float array which allows for easy size
* checking and reallocation. Used for drawing lines.
*/
private class FloatRef {
float[] array;
public FloatRef(int size) {
array = new float[size];
}
public void ensureSize(int newSize) {
if (newSize >= array.length) {
// Add enough space for 7 more boxes to be drawn
array = Arrays.copyOf(array, newSize + 16 * 7);
}
}
}
/**
* Shows up as an error if we don't include this.
*/
public MonthWeekEventsView(Context context) {
super(context);
}
// Sets the list of events for this week. Takes a sorted list of arrays
// divided up by day for generating the large month version and the full
// arraylist sorted by start time to generate the dna version.
public void setEvents(List<ArrayList<Event>> sortedEvents, ArrayList<Event> unsortedEvents) {
setEvents(sortedEvents);
// The MIN_WEEK_WIDTH is a hack to prevent the view from trying to
// generate dna bits before its width has been fixed.
createDna(unsortedEvents);
}
/**
* Sets up the dna bits for the view. This will return early if the view
* isn't in a state that will create a valid set of dna yet (such as the
* views width not being set correctly yet).
*/
public void createDna(ArrayList<Event> unsortedEvents) {
if (unsortedEvents == null || mWidth <= MIN_WEEK_WIDTH || getContext() == null) {
// Stash the list of events for use when this view is ready, or
// just clear it if a null set has been passed to this view
mUnsortedEvents = unsortedEvents;
mDna = null;
return;
} else {
// clear the cached set of events since we're ready to build it now
mUnsortedEvents = null;
}
// Create the drawing coordinates for dna
if (!mShowDetailsInMonth) {
int numDays = mEvents.size();
int effectiveWidth = mWidth - mPadding * 2;
if (mShowWeekNum) {
effectiveWidth -= SPACING_WEEK_NUMBER;
}
DNA_ALL_DAY_WIDTH = effectiveWidth / numDays - 2 * DNA_SIDE_PADDING;
mDNAAllDayPaint.setStrokeWidth(DNA_ALL_DAY_WIDTH);
mDayXs = new int[numDays];
for (int day = 0; day < numDays; day++) {
mDayXs[day] = computeDayLeftPosition(day) + DNA_WIDTH / 2 + DNA_SIDE_PADDING;
}
int top = DAY_SEPARATOR_INNER_WIDTH + DNA_MARGIN + DNA_ALL_DAY_HEIGHT + 1;
int bottom = mHeight - DNA_MARGIN;
mDna = Utils.createDNAStrands(mFirstJulianDay, unsortedEvents, top, bottom,
DNA_MIN_SEGMENT_HEIGHT, mDayXs, getContext());
}
}
public void setEvents(List<ArrayList<Event>> sortedEvents) {
mEvents = sortedEvents;
if (sortedEvents == null) {
return;
}
if (sortedEvents.size() != mNumDays) {
if (Log.isLoggable(TAG, Log.ERROR)) {
Log.wtf(TAG, "Events size must be same as days displayed: size="
+ sortedEvents.size() + " days=" + mNumDays);
}
mEvents = null;
return;
}
}
protected void loadColors(Context context) {
Resources res = context.getResources();
mMonthWeekNumColor = res.getColor(R.color.month_week_num_color);
mMonthNumColor = res.getColor(R.color.month_day_number);
mMonthNumOtherColor = res.getColor(R.color.month_day_number_other);
mMonthNumTodayColor = res.getColor(R.color.month_today_number);
mMonthNameColor = mMonthNumColor;
mMonthNameOtherColor = mMonthNumOtherColor;
mMonthEventColor = res.getColor(R.color.month_event_color);
mMonthDeclinedEventColor = res.getColor(R.color.agenda_item_declined_color);
mMonthDeclinedExtrasColor = res.getColor(R.color.agenda_item_where_declined_text_color);
mMonthEventExtraColor = res.getColor(R.color.month_event_extra_color);
mMonthEventOtherColor = res.getColor(R.color.month_event_other_color);
mMonthEventExtraOtherColor = res.getColor(R.color.month_event_extra_other_color);
mMonthBGTodayColor = res.getColor(R.color.month_today_bgcolor);
mMonthBGOtherColor = res.getColor(R.color.month_other_bgcolor);
mMonthBGColor = res.getColor(R.color.month_bgcolor);
mDaySeparatorInnerColor = res.getColor(R.color.month_grid_lines);
mTodayAnimateColor = res.getColor(R.color.today_highlight_color);
mClickedDayColor = res.getColor(R.color.day_clicked_background_color);
mTodayDrawable = res.getDrawable(R.drawable.today_blue_week_holo_light);
}
/**
* Sets up the text and style properties for painting. Override this if you
* want to use a different paint.
*/
@Override
protected void initView() {
super.initView();
if (!mInitialized) {
Resources resources = getContext().getResources();
mShowDetailsInMonth = Utils.getConfigBool(getContext(), R.bool.show_details_in_month);
+ TEXT_SIZE_EVENT_TITLE = resources.getInteger(R.integer.text_size_event_title);
TEXT_SIZE_MONTH_NUMBER = resources.getInteger(R.integer.text_size_month_number);
SIDE_PADDING_MONTH_NUMBER = resources.getInteger(R.integer.month_day_number_margin);
CONFLICT_COLOR = resources.getColor(R.color.month_dna_conflict_time_color);
EVENT_TEXT_COLOR = resources.getColor(R.color.calendar_event_text_color);
if (mScale != 1) {
TOP_PADDING_MONTH_NUMBER *= mScale;
TOP_PADDING_WEEK_NUMBER *= mScale;
SIDE_PADDING_MONTH_NUMBER *= mScale;
SIDE_PADDING_WEEK_NUMBER *= mScale;
SPACING_WEEK_NUMBER *= mScale;
TEXT_SIZE_MONTH_NUMBER *= mScale;
TEXT_SIZE_EVENT *= mScale;
TEXT_SIZE_EVENT_TITLE *= mScale;
TEXT_SIZE_MORE_EVENTS *= mScale;
TEXT_SIZE_MONTH_NAME *= mScale;
TEXT_SIZE_WEEK_NUM *= mScale;
DAY_SEPARATOR_OUTER_WIDTH *= mScale;
DAY_SEPARATOR_INNER_WIDTH *= mScale;
DAY_SEPARATOR_VERTICAL_LENGTH *= mScale;
DAY_SEPARATOR_VERTICAL_LENGHT_PORTRAIT *= mScale;
EVENT_X_OFFSET_LANDSCAPE *= mScale;
EVENT_Y_OFFSET_LANDSCAPE *= mScale;
EVENT_Y_OFFSET_PORTRAIT *= mScale;
EVENT_SQUARE_WIDTH *= mScale;
EVENT_SQUARE_BORDER *= mScale;
EVENT_LINE_PADDING *= mScale;
EVENT_BOTTOM_PADDING *= mScale;
EVENT_RIGHT_PADDING *= mScale;
DNA_MARGIN *= mScale;
DNA_WIDTH *= mScale;
DNA_ALL_DAY_HEIGHT *= mScale;
DNA_MIN_SEGMENT_HEIGHT *= mScale;
DNA_SIDE_PADDING *= mScale;
DEFAULT_EDGE_SPACING *= mScale;
DNA_ALL_DAY_WIDTH *= mScale;
TODAY_HIGHLIGHT_WIDTH *= mScale;
}
if (!mShowDetailsInMonth) {
TOP_PADDING_MONTH_NUMBER += DNA_ALL_DAY_HEIGHT + DNA_MARGIN;
}
mInitialized = true;
}
mPadding = DEFAULT_EDGE_SPACING;
loadColors(getContext());
// TODO modify paint properties depending on isMini
mMonthNumPaint = new Paint();
mMonthNumPaint.setFakeBoldText(false);
mMonthNumPaint.setAntiAlias(true);
mMonthNumPaint.setTextSize(TEXT_SIZE_MONTH_NUMBER);
mMonthNumPaint.setColor(mMonthNumColor);
mMonthNumPaint.setStyle(Style.FILL);
mMonthNumPaint.setTextAlign(Align.RIGHT);
mMonthNumPaint.setTypeface(Typeface.DEFAULT);
mMonthNumAscentHeight = (int) (-mMonthNumPaint.ascent() + 0.5f);
mMonthNumHeight = (int) (mMonthNumPaint.descent() - mMonthNumPaint.ascent() + 0.5f);
mEventPaint = new TextPaint();
mEventPaint.setFakeBoldText(true);
mEventPaint.setAntiAlias(true);
mEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE);
mEventPaint.setColor(mMonthEventColor);
mSolidBackgroundEventPaint = new TextPaint(mEventPaint);
mSolidBackgroundEventPaint.setColor(EVENT_TEXT_COLOR);
mFramedEventPaint = new TextPaint(mSolidBackgroundEventPaint);
mDeclinedEventPaint = new TextPaint();
mDeclinedEventPaint.setFakeBoldText(true);
mDeclinedEventPaint.setAntiAlias(true);
mDeclinedEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE);
mDeclinedEventPaint.setColor(mMonthDeclinedEventColor);
mEventAscentHeight = (int) (-mEventPaint.ascent() + 0.5f);
mEventHeight = (int) (mEventPaint.descent() - mEventPaint.ascent() + 0.5f);
mEventExtrasPaint = new TextPaint();
mEventExtrasPaint.setFakeBoldText(false);
mEventExtrasPaint.setAntiAlias(true);
mEventExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER);
mEventExtrasPaint.setTextSize(TEXT_SIZE_EVENT);
mEventExtrasPaint.setColor(mMonthEventExtraColor);
mEventExtrasPaint.setStyle(Style.FILL);
mEventExtrasPaint.setTextAlign(Align.LEFT);
mExtrasHeight = (int)(mEventExtrasPaint.descent() - mEventExtrasPaint.ascent() + 0.5f);
mExtrasAscentHeight = (int)(-mEventExtrasPaint.ascent() + 0.5f);
mExtrasDescent = (int)(mEventExtrasPaint.descent() + 0.5f);
mEventDeclinedExtrasPaint = new TextPaint();
mEventDeclinedExtrasPaint.setFakeBoldText(false);
mEventDeclinedExtrasPaint.setAntiAlias(true);
mEventDeclinedExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER);
mEventDeclinedExtrasPaint.setTextSize(TEXT_SIZE_EVENT);
mEventDeclinedExtrasPaint.setColor(mMonthDeclinedExtrasColor);
mEventDeclinedExtrasPaint.setStyle(Style.FILL);
mEventDeclinedExtrasPaint.setTextAlign(Align.LEFT);
mWeekNumPaint = new Paint();
mWeekNumPaint.setFakeBoldText(false);
mWeekNumPaint.setAntiAlias(true);
mWeekNumPaint.setTextSize(TEXT_SIZE_WEEK_NUM);
mWeekNumPaint.setColor(mWeekNumColor);
mWeekNumPaint.setStyle(Style.FILL);
mWeekNumPaint.setTextAlign(Align.RIGHT);
mWeekNumAscentHeight = (int) (-mWeekNumPaint.ascent() + 0.5f);
mDNAAllDayPaint = new Paint();
mDNATimePaint = new Paint();
mDNATimePaint.setColor(mMonthBusyBitsBusyTimeColor);
mDNATimePaint.setStyle(Style.FILL_AND_STROKE);
mDNATimePaint.setStrokeWidth(DNA_WIDTH);
mDNATimePaint.setAntiAlias(false);
mDNAAllDayPaint.setColor(mMonthBusyBitsConflictTimeColor);
mDNAAllDayPaint.setStyle(Style.FILL_AND_STROKE);
mDNAAllDayPaint.setStrokeWidth(DNA_ALL_DAY_WIDTH);
mDNAAllDayPaint.setAntiAlias(false);
mEventSquarePaint = new Paint();
mEventSquarePaint.setStrokeWidth(EVENT_SQUARE_BORDER);
mEventSquarePaint.setAntiAlias(false);
if (DEBUG_LAYOUT) {
Log.d("EXTRA", "mScale=" + mScale);
Log.d("EXTRA", "mMonthNumPaint ascent=" + mMonthNumPaint.ascent()
+ " descent=" + mMonthNumPaint.descent() + " int height=" + mMonthNumHeight);
Log.d("EXTRA", "mEventPaint ascent=" + mEventPaint.ascent()
+ " descent=" + mEventPaint.descent() + " int height=" + mEventHeight
+ " int ascent=" + mEventAscentHeight);
Log.d("EXTRA", "mEventExtrasPaint ascent=" + mEventExtrasPaint.ascent()
+ " descent=" + mEventExtrasPaint.descent() + " int height=" + mExtrasHeight);
Log.d("EXTRA", "mWeekNumPaint ascent=" + mWeekNumPaint.ascent()
+ " descent=" + mWeekNumPaint.descent());
}
}
@Override
public void setWeekParams(HashMap<String, Integer> params, String tz) {
super.setWeekParams(params, tz);
if (params.containsKey(VIEW_PARAMS_ORIENTATION)) {
mOrientation = params.get(VIEW_PARAMS_ORIENTATION);
}
updateToday(tz);
mNumCells = mNumDays + 1;
if (params.containsKey(VIEW_PARAMS_ANIMATE_TODAY) && mHasToday) {
synchronized (mAnimatorListener) {
if (mTodayAnimator != null) {
mTodayAnimator.removeAllListeners();
mTodayAnimator.cancel();
}
mTodayAnimator = ObjectAnimator.ofInt(this, "animateTodayAlpha",
Math.max(mAnimateTodayAlpha, 80), 255);
mTodayAnimator.setDuration(150);
mAnimatorListener.setAnimator(mTodayAnimator);
mAnimatorListener.setFadingIn(true);
mTodayAnimator.addListener(mAnimatorListener);
mAnimateToday = true;
mTodayAnimator.start();
}
}
}
/**
* @param tz
*/
public boolean updateToday(String tz) {
mToday.timezone = tz;
mToday.setToNow();
mToday.normalize(true);
int julianToday = Time.getJulianDay(mToday.toMillis(false), mToday.gmtoff);
if (julianToday >= mFirstJulianDay && julianToday < mFirstJulianDay + mNumDays) {
mHasToday = true;
mTodayIndex = julianToday - mFirstJulianDay;
} else {
mHasToday = false;
mTodayIndex = -1;
}
return mHasToday;
}
public void setAnimateTodayAlpha(int alpha) {
mAnimateTodayAlpha = alpha;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
drawBackground(canvas);
drawWeekNums(canvas);
drawDaySeparators(canvas);
if (mHasToday && mAnimateToday) {
drawToday(canvas);
}
if (mShowDetailsInMonth) {
drawEvents(canvas);
} else {
if (mDna == null && mUnsortedEvents != null) {
createDna(mUnsortedEvents);
}
drawDNA(canvas);
}
drawClick(canvas);
}
protected void drawToday(Canvas canvas) {
r.top = DAY_SEPARATOR_INNER_WIDTH + (TODAY_HIGHLIGHT_WIDTH / 2);
r.bottom = mHeight - (int) Math.ceil(TODAY_HIGHLIGHT_WIDTH / 2.0f);
p.setStyle(Style.STROKE);
p.setStrokeWidth(TODAY_HIGHLIGHT_WIDTH);
r.left = computeDayLeftPosition(mTodayIndex) + (TODAY_HIGHLIGHT_WIDTH / 2);
r.right = computeDayLeftPosition(mTodayIndex + 1)
- (int) Math.ceil(TODAY_HIGHLIGHT_WIDTH / 2.0f);
p.setColor(mTodayAnimateColor | (mAnimateTodayAlpha << 24));
canvas.drawRect(r, p);
p.setStyle(Style.FILL);
}
// TODO move into SimpleWeekView
// Computes the x position for the left side of the given day
private int computeDayLeftPosition(int day) {
int effectiveWidth = mWidth;
int x = 0;
int xOffset = 0;
if (mShowWeekNum) {
xOffset = SPACING_WEEK_NUMBER + mPadding;
effectiveWidth -= xOffset;
}
x = day * effectiveWidth / mNumDays + xOffset;
return x;
}
@Override
protected void drawDaySeparators(Canvas canvas) {
float lines[] = new float[8 * 4];
int count = 6 * 4;
int wkNumOffset = 0;
int i = 0;
if (mShowWeekNum) {
// This adds the first line separating the week number
int xOffset = SPACING_WEEK_NUMBER + mPadding;
count += 4;
lines[i++] = xOffset;
lines[i++] = 0;
lines[i++] = xOffset;
lines[i++] = mHeight;
wkNumOffset++;
}
count += 4;
lines[i++] = 0;
lines[i++] = 0;
lines[i++] = mWidth;
lines[i++] = 0;
int y0 = 0;
int y1 = mHeight;
while (i < count) {
int x = computeDayLeftPosition(i / 4 - wkNumOffset);
lines[i++] = x;
lines[i++] = y0;
lines[i++] = x;
lines[i++] = y1;
}
p.setColor(mDaySeparatorInnerColor);
p.setStrokeWidth(DAY_SEPARATOR_INNER_WIDTH);
canvas.drawLines(lines, 0, count, p);
}
@Override
protected void drawBackground(Canvas canvas) {
int i = 0;
int offset = 0;
r.top = DAY_SEPARATOR_INNER_WIDTH;
r.bottom = mHeight;
if (mShowWeekNum) {
i++;
offset++;
}
if (!mOddMonth[i]) {
while (++i < mOddMonth.length && !mOddMonth[i])
;
r.right = computeDayLeftPosition(i - offset);
r.left = 0;
p.setColor(mMonthBGOtherColor);
canvas.drawRect(r, p);
// compute left edge for i, set up r, draw
} else if (!mOddMonth[(i = mOddMonth.length - 1)]) {
while (--i >= offset && !mOddMonth[i])
;
i++;
// compute left edge for i, set up r, draw
r.right = mWidth;
r.left = computeDayLeftPosition(i - offset);
p.setColor(mMonthBGOtherColor);
canvas.drawRect(r, p);
}
if (mHasToday) {
p.setColor(mMonthBGTodayColor);
r.left = computeDayLeftPosition(mTodayIndex);
r.right = computeDayLeftPosition(mTodayIndex + 1);
canvas.drawRect(r, p);
}
}
// Draw the "clicked" color on the tapped day
private void drawClick(Canvas canvas) {
if (mClickedDayIndex != -1) {
int alpha = p.getAlpha();
p.setColor(mClickedDayColor);
p.setAlpha(mClickedAlpha);
r.left = computeDayLeftPosition(mClickedDayIndex);
r.right = computeDayLeftPosition(mClickedDayIndex + 1);
r.top = DAY_SEPARATOR_INNER_WIDTH;
r.bottom = mHeight;
canvas.drawRect(r, p);
p.setAlpha(alpha);
}
}
@Override
protected void drawWeekNums(Canvas canvas) {
int y;
int i = 0;
int offset = -1;
int todayIndex = mTodayIndex;
int x = 0;
int numCount = mNumDays;
if (mShowWeekNum) {
x = SIDE_PADDING_WEEK_NUMBER + mPadding;
y = mWeekNumAscentHeight + TOP_PADDING_WEEK_NUMBER;
canvas.drawText(mDayNumbers[0], x, y, mWeekNumPaint);
numCount++;
i++;
todayIndex++;
offset++;
}
y = mMonthNumAscentHeight + TOP_PADDING_MONTH_NUMBER;
boolean isFocusMonth = mFocusDay[i];
boolean isBold = false;
mMonthNumPaint.setColor(isFocusMonth ? mMonthNumColor : mMonthNumOtherColor);
for (; i < numCount; i++) {
if (mHasToday && todayIndex == i) {
mMonthNumPaint.setColor(mMonthNumTodayColor);
mMonthNumPaint.setFakeBoldText(isBold = true);
if (i + 1 < numCount) {
// Make sure the color will be set back on the next
// iteration
isFocusMonth = !mFocusDay[i + 1];
}
} else if (mFocusDay[i] != isFocusMonth) {
isFocusMonth = mFocusDay[i];
mMonthNumPaint.setColor(isFocusMonth ? mMonthNumColor : mMonthNumOtherColor);
}
x = computeDayLeftPosition(i - offset) - (SIDE_PADDING_MONTH_NUMBER);
canvas.drawText(mDayNumbers[i], x, y, mMonthNumPaint);
if (isBold) {
mMonthNumPaint.setFakeBoldText(isBold = false);
}
}
}
protected void drawEvents(Canvas canvas) {
if (mEvents == null) {
return;
}
int day = -1;
for (ArrayList<Event> eventDay : mEvents) {
day++;
if (eventDay == null || eventDay.size() == 0) {
continue;
}
int ySquare;
int xSquare = computeDayLeftPosition(day) + SIDE_PADDING_MONTH_NUMBER + 1;
int rightEdge = computeDayLeftPosition(day + 1);
if (mOrientation == Configuration.ORIENTATION_PORTRAIT) {
ySquare = EVENT_Y_OFFSET_PORTRAIT + mMonthNumHeight + TOP_PADDING_MONTH_NUMBER;
rightEdge -= SIDE_PADDING_MONTH_NUMBER + 1;
} else {
ySquare = EVENT_Y_OFFSET_LANDSCAPE;
rightEdge -= EVENT_X_OFFSET_LANDSCAPE;
}
// Determine if everything will fit when time ranges are shown.
boolean showTimes = true;
Iterator<Event> iter = eventDay.iterator();
int yTest = ySquare;
while (iter.hasNext()) {
Event event = iter.next();
int newY = drawEvent(canvas, event, xSquare, yTest, rightEdge, iter.hasNext(),
showTimes, /*doDraw*/ false);
if (newY == yTest) {
showTimes = false;
break;
}
yTest = newY;
}
int eventCount = 0;
iter = eventDay.iterator();
while (iter.hasNext()) {
Event event = iter.next();
int newY = drawEvent(canvas, event, xSquare, ySquare, rightEdge, iter.hasNext(),
showTimes, /*doDraw*/ true);
if (newY == ySquare) {
break;
}
eventCount++;
ySquare = newY;
}
int remaining = eventDay.size() - eventCount;
if (remaining > 0) {
drawMoreEvents(canvas, remaining, xSquare);
}
}
}
protected int addChipOutline(FloatRef lines, int count, int x, int y) {
lines.ensureSize(count + 16);
// top of box
lines.array[count++] = x;
lines.array[count++] = y;
lines.array[count++] = x + EVENT_SQUARE_WIDTH;
lines.array[count++] = y;
// right side of box
lines.array[count++] = x + EVENT_SQUARE_WIDTH;
lines.array[count++] = y;
lines.array[count++] = x + EVENT_SQUARE_WIDTH;
lines.array[count++] = y + EVENT_SQUARE_WIDTH;
// left side of box
lines.array[count++] = x;
lines.array[count++] = y;
lines.array[count++] = x;
lines.array[count++] = y + EVENT_SQUARE_WIDTH + 1;
// bottom of box
lines.array[count++] = x;
lines.array[count++] = y + EVENT_SQUARE_WIDTH;
lines.array[count++] = x + EVENT_SQUARE_WIDTH + 1;
lines.array[count++] = y + EVENT_SQUARE_WIDTH;
return count;
}
/**
* Attempts to draw the given event. Returns the y for the next event or the
* original y if the event will not fit. An event is considered to not fit
* if the event and its extras won't fit or if there are more events and the
* more events line would not fit after drawing this event.
*
* @param canvas the canvas to draw on
* @param event the event to draw
* @param x the top left corner for this event's color chip
* @param y the top left corner for this event's color chip
* @param rightEdge the rightmost point we're allowed to draw on (exclusive)
* @param moreEvents indicates whether additional events will follow this one
* @param showTimes if set, a second line with a time range will be displayed for non-all-day
* events
* @param doDraw if set, do the actual drawing; otherwise this just computes the height
* and returns
* @return the y for the next event or the original y if it won't fit
*/
protected int drawEvent(Canvas canvas, Event event, int x, int y, int rightEdge,
boolean moreEvents, boolean showTimes, boolean doDraw) {
/*
* Vertical layout:
* (top of box)
* a. EVENT_Y_OFFSET_LANDSCAPE or portrait equivalent
* b. Event title: mEventHeight for a normal event, + 2xBORDER_SPACE for all-day event
* c. [optional] Time range (mExtrasHeight)
* d. EVENT_LINE_PADDING
*
* Repeat (b,c,d) as needed and space allows. If we have more events than fit, we need
* to leave room for something like "+2" at the bottom:
*
* e. "+ more" line (mExtrasHeight)
*
* f. EVENT_BOTTOM_PADDING (overlaps EVENT_LINE_PADDING)
* (bottom of box)
*/
final int BORDER_SPACE = EVENT_SQUARE_BORDER + 1; // want a 1-pixel gap inside border
final int STROKE_WIDTH_ADJ = EVENT_SQUARE_BORDER / 2; // adjust bounds for stroke width
boolean allDay = event.allDay;
int eventRequiredSpace = mEventHeight;
if (allDay) {
// Add a few pixels for the box we draw around all-day events.
eventRequiredSpace += BORDER_SPACE * 2;
} else if (showTimes) {
// Need room for the "1pm - 2pm" line.
eventRequiredSpace += mExtrasHeight;
}
int reservedSpace = EVENT_BOTTOM_PADDING; // leave a bit of room at the bottom
if (moreEvents) {
// More events follow. Leave a bit of space between events.
eventRequiredSpace += EVENT_LINE_PADDING;
// Make sure we have room for the "+ more" line. (The "+ more" line is expected
// to be <= the height of an event line, so we won't show "+1" when we could be
// showing the event.)
reservedSpace += mExtrasHeight;
}
if (y + eventRequiredSpace + reservedSpace > mHeight) {
// Not enough space, return original y
return y;
} else if (!doDraw) {
return y + eventRequiredSpace;
}
boolean isDeclined = event.selfAttendeeStatus == Attendees.ATTENDEE_STATUS_DECLINED;
int color = event.color;
if (isDeclined) {
color = Utils.getDeclinedColorFromColor(color);
}
int textX, textY, textRightEdge;
if (allDay) {
// We shift the render offset "inward", because drawRect with a stroke width greater
// than 1 draws outside the specified bounds. (We don't adjust the left edge, since
// we want to match the existing appearance of the "event square".)
r.left = x;
r.right = rightEdge - STROKE_WIDTH_ADJ;
r.top = y + STROKE_WIDTH_ADJ;
r.bottom = y + mEventHeight + BORDER_SPACE * 2 - STROKE_WIDTH_ADJ;
textX = x + BORDER_SPACE;
textY = y + mEventAscentHeight + BORDER_SPACE;
textRightEdge = rightEdge - BORDER_SPACE;
} else {
r.left = x;
r.right = x + EVENT_SQUARE_WIDTH;
r.bottom = y + mEventAscentHeight;
r.top = r.bottom - EVENT_SQUARE_WIDTH;
textX = x + EVENT_SQUARE_WIDTH + EVENT_RIGHT_PADDING;
textY = y + mEventAscentHeight;
textRightEdge = rightEdge;
}
Style boxStyle = Style.STROKE;
boolean solidBackground = false;
if (event.selfAttendeeStatus != Attendees.ATTENDEE_STATUS_INVITED) {
boxStyle = Style.FILL_AND_STROKE;
if (allDay) {
solidBackground = true;
}
}
mEventSquarePaint.setStyle(boxStyle);
mEventSquarePaint.setColor(color);
canvas.drawRect(r, mEventSquarePaint);
float avail = textRightEdge - textX;
CharSequence text = TextUtils.ellipsize(
event.title, mEventPaint, avail, TextUtils.TruncateAt.END);
Paint textPaint;
if (solidBackground) {
// Text color needs to contrast with solid background.
textPaint = mSolidBackgroundEventPaint;
} else if (isDeclined) {
// Use "declined event" color.
textPaint = mDeclinedEventPaint;
} else if (allDay) {
// Text inside frame is same color as frame.
mFramedEventPaint.setColor(color);
textPaint = mFramedEventPaint;
} else {
// Use generic event text color.
textPaint = mEventPaint;
}
canvas.drawText(text.toString(), textX, textY, textPaint);
y += mEventHeight;
if (allDay) {
y += BORDER_SPACE * 2;
}
if (showTimes && !allDay) {
// show start/end time, e.g. "1pm - 2pm"
textY = y + mExtrasAscentHeight;
mStringBuilder.setLength(0);
text = DateUtils.formatDateRange(getContext(), mFormatter, event.startMillis,
event.endMillis, DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL,
Utils.getTimeZone(getContext(), null)).toString();
text = TextUtils.ellipsize(text, mEventExtrasPaint, avail, TextUtils.TruncateAt.END);
canvas.drawText(text.toString(), textX, textY, isDeclined ? mEventDeclinedExtrasPaint
: mEventExtrasPaint);
y += mExtrasHeight;
}
y += EVENT_LINE_PADDING;
return y;
}
protected void drawMoreEvents(Canvas canvas, int remainingEvents, int x) {
int y = mHeight - (mExtrasDescent + EVENT_BOTTOM_PADDING);
String text = getContext().getResources().getQuantityString(
R.plurals.month_more_events, remainingEvents);
mEventExtrasPaint.setAntiAlias(true);
mEventExtrasPaint.setFakeBoldText(true);
canvas.drawText(String.format(text, remainingEvents), x, y, mEventExtrasPaint);
mEventExtrasPaint.setFakeBoldText(false);
}
/**
* Draws a line showing busy times in each day of week The method draws
* non-conflicting times in the event color and times with conflicting
* events in the dna conflict color defined in colors.
*
* @param canvas
*/
protected void drawDNA(Canvas canvas) {
// Draw event and conflict times
if (mDna != null) {
for (Utils.DNAStrand strand : mDna.values()) {
if (strand.color == CONFLICT_COLOR || strand.points == null
|| strand.points.length == 0) {
continue;
}
mDNATimePaint.setColor(strand.color);
canvas.drawLines(strand.points, mDNATimePaint);
}
// Draw black last to make sure it's on top
Utils.DNAStrand strand = mDna.get(CONFLICT_COLOR);
if (strand != null && strand.points != null && strand.points.length != 0) {
mDNATimePaint.setColor(strand.color);
canvas.drawLines(strand.points, mDNATimePaint);
}
if (mDayXs == null) {
return;
}
int numDays = mDayXs.length;
int xOffset = (DNA_ALL_DAY_WIDTH - DNA_WIDTH) / 2;
if (strand != null && strand.allDays != null && strand.allDays.length == numDays) {
for (int i = 0; i < numDays; i++) {
// this adds at most 7 draws. We could sort it by color and
// build an array instead but this is easier.
if (strand.allDays[i] != 0) {
mDNAAllDayPaint.setColor(strand.allDays[i]);
canvas.drawLine(mDayXs[i] + xOffset, DNA_MARGIN, mDayXs[i] + xOffset,
DNA_MARGIN + DNA_ALL_DAY_HEIGHT, mDNAAllDayPaint);
}
}
}
}
}
@Override
protected void updateSelectionPositions() {
if (mHasSelectedDay) {
int selectedPosition = mSelectedDay - mWeekStart;
if (selectedPosition < 0) {
selectedPosition += 7;
}
int effectiveWidth = mWidth - mPadding * 2;
effectiveWidth -= SPACING_WEEK_NUMBER;
mSelectedLeft = selectedPosition * effectiveWidth / mNumDays + mPadding;
mSelectedRight = (selectedPosition + 1) * effectiveWidth / mNumDays + mPadding;
mSelectedLeft += SPACING_WEEK_NUMBER;
mSelectedRight += SPACING_WEEK_NUMBER;
}
}
public int getDayIndexFromLocation(float x) {
int dayStart = mShowWeekNum ? SPACING_WEEK_NUMBER + mPadding : mPadding;
if (x < dayStart || x > mWidth - mPadding) {
return -1;
}
// Selection is (x - start) / (pixels/day) == (x -s) * day / pixels
return ((int) ((x - dayStart) * mNumDays / (mWidth - dayStart - mPadding)));
}
@Override
public Time getDayFromLocation(float x) {
int dayPosition = getDayIndexFromLocation(x);
if (dayPosition == -1) {
return null;
}
int day = mFirstJulianDay + dayPosition;
Time time = new Time(mTimeZone);
if (mWeek == 0) {
// This week is weird...
if (day < Time.EPOCH_JULIAN_DAY) {
day++;
} else if (day == Time.EPOCH_JULIAN_DAY) {
time.set(1, 0, 1970);
time.normalize(true);
return time;
}
}
time.setJulianDay(day);
return time;
}
@Override
public boolean onHoverEvent(MotionEvent event) {
Context context = getContext();
// only send accessibility events if accessibility and exploration are
// on.
AccessibilityManager am = (AccessibilityManager) context
.getSystemService(Service.ACCESSIBILITY_SERVICE);
if (!am.isEnabled() || !am.isTouchExplorationEnabled()) {
return super.onHoverEvent(event);
}
if (event.getAction() != MotionEvent.ACTION_HOVER_EXIT) {
Time hover = getDayFromLocation(event.getX());
if (hover != null
&& (mLastHoverTime == null || Time.compare(hover, mLastHoverTime) != 0)) {
Long millis = hover.toMillis(true);
String date = Utils.formatDateRange(context, millis, millis,
DateUtils.FORMAT_SHOW_DATE);
AccessibilityEvent accessEvent = AccessibilityEvent
.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
accessEvent.getText().add(date);
if (mShowDetailsInMonth && mEvents != null) {
int dayStart = SPACING_WEEK_NUMBER + mPadding;
int dayPosition = (int) ((event.getX() - dayStart) * mNumDays / (mWidth
- dayStart - mPadding));
ArrayList<Event> events = mEvents.get(dayPosition);
List<CharSequence> text = accessEvent.getText();
for (Event e : events) {
text.add(e.getTitleAndLocation() + ". ");
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
if (!e.allDay) {
flags |= DateUtils.FORMAT_SHOW_TIME;
if (DateFormat.is24HourFormat(context)) {
flags |= DateUtils.FORMAT_24HOUR;
}
} else {
flags |= DateUtils.FORMAT_UTC;
}
text.add(Utils.formatDateRange(context, e.startMillis, e.endMillis,
flags) + ". ");
}
}
sendAccessibilityEventUnchecked(accessEvent);
mLastHoverTime = hover;
}
}
return true;
}
public void setClickedDay(float xLocation) {
mClickedDayIndex = getDayIndexFromLocation(xLocation);
invalidate();
}
public void clearClickedDay() {
mClickedDayIndex = -1;
invalidate();
}
}
| true | true | protected void initView() {
super.initView();
if (!mInitialized) {
Resources resources = getContext().getResources();
mShowDetailsInMonth = Utils.getConfigBool(getContext(), R.bool.show_details_in_month);
TEXT_SIZE_MONTH_NUMBER = resources.getInteger(R.integer.text_size_month_number);
SIDE_PADDING_MONTH_NUMBER = resources.getInteger(R.integer.month_day_number_margin);
CONFLICT_COLOR = resources.getColor(R.color.month_dna_conflict_time_color);
EVENT_TEXT_COLOR = resources.getColor(R.color.calendar_event_text_color);
if (mScale != 1) {
TOP_PADDING_MONTH_NUMBER *= mScale;
TOP_PADDING_WEEK_NUMBER *= mScale;
SIDE_PADDING_MONTH_NUMBER *= mScale;
SIDE_PADDING_WEEK_NUMBER *= mScale;
SPACING_WEEK_NUMBER *= mScale;
TEXT_SIZE_MONTH_NUMBER *= mScale;
TEXT_SIZE_EVENT *= mScale;
TEXT_SIZE_EVENT_TITLE *= mScale;
TEXT_SIZE_MORE_EVENTS *= mScale;
TEXT_SIZE_MONTH_NAME *= mScale;
TEXT_SIZE_WEEK_NUM *= mScale;
DAY_SEPARATOR_OUTER_WIDTH *= mScale;
DAY_SEPARATOR_INNER_WIDTH *= mScale;
DAY_SEPARATOR_VERTICAL_LENGTH *= mScale;
DAY_SEPARATOR_VERTICAL_LENGHT_PORTRAIT *= mScale;
EVENT_X_OFFSET_LANDSCAPE *= mScale;
EVENT_Y_OFFSET_LANDSCAPE *= mScale;
EVENT_Y_OFFSET_PORTRAIT *= mScale;
EVENT_SQUARE_WIDTH *= mScale;
EVENT_SQUARE_BORDER *= mScale;
EVENT_LINE_PADDING *= mScale;
EVENT_BOTTOM_PADDING *= mScale;
EVENT_RIGHT_PADDING *= mScale;
DNA_MARGIN *= mScale;
DNA_WIDTH *= mScale;
DNA_ALL_DAY_HEIGHT *= mScale;
DNA_MIN_SEGMENT_HEIGHT *= mScale;
DNA_SIDE_PADDING *= mScale;
DEFAULT_EDGE_SPACING *= mScale;
DNA_ALL_DAY_WIDTH *= mScale;
TODAY_HIGHLIGHT_WIDTH *= mScale;
}
if (!mShowDetailsInMonth) {
TOP_PADDING_MONTH_NUMBER += DNA_ALL_DAY_HEIGHT + DNA_MARGIN;
}
mInitialized = true;
}
mPadding = DEFAULT_EDGE_SPACING;
loadColors(getContext());
// TODO modify paint properties depending on isMini
mMonthNumPaint = new Paint();
mMonthNumPaint.setFakeBoldText(false);
mMonthNumPaint.setAntiAlias(true);
mMonthNumPaint.setTextSize(TEXT_SIZE_MONTH_NUMBER);
mMonthNumPaint.setColor(mMonthNumColor);
mMonthNumPaint.setStyle(Style.FILL);
mMonthNumPaint.setTextAlign(Align.RIGHT);
mMonthNumPaint.setTypeface(Typeface.DEFAULT);
mMonthNumAscentHeight = (int) (-mMonthNumPaint.ascent() + 0.5f);
mMonthNumHeight = (int) (mMonthNumPaint.descent() - mMonthNumPaint.ascent() + 0.5f);
mEventPaint = new TextPaint();
mEventPaint.setFakeBoldText(true);
mEventPaint.setAntiAlias(true);
mEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE);
mEventPaint.setColor(mMonthEventColor);
mSolidBackgroundEventPaint = new TextPaint(mEventPaint);
mSolidBackgroundEventPaint.setColor(EVENT_TEXT_COLOR);
mFramedEventPaint = new TextPaint(mSolidBackgroundEventPaint);
mDeclinedEventPaint = new TextPaint();
mDeclinedEventPaint.setFakeBoldText(true);
mDeclinedEventPaint.setAntiAlias(true);
mDeclinedEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE);
mDeclinedEventPaint.setColor(mMonthDeclinedEventColor);
mEventAscentHeight = (int) (-mEventPaint.ascent() + 0.5f);
mEventHeight = (int) (mEventPaint.descent() - mEventPaint.ascent() + 0.5f);
mEventExtrasPaint = new TextPaint();
mEventExtrasPaint.setFakeBoldText(false);
mEventExtrasPaint.setAntiAlias(true);
mEventExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER);
mEventExtrasPaint.setTextSize(TEXT_SIZE_EVENT);
mEventExtrasPaint.setColor(mMonthEventExtraColor);
mEventExtrasPaint.setStyle(Style.FILL);
mEventExtrasPaint.setTextAlign(Align.LEFT);
mExtrasHeight = (int)(mEventExtrasPaint.descent() - mEventExtrasPaint.ascent() + 0.5f);
mExtrasAscentHeight = (int)(-mEventExtrasPaint.ascent() + 0.5f);
mExtrasDescent = (int)(mEventExtrasPaint.descent() + 0.5f);
mEventDeclinedExtrasPaint = new TextPaint();
mEventDeclinedExtrasPaint.setFakeBoldText(false);
mEventDeclinedExtrasPaint.setAntiAlias(true);
mEventDeclinedExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER);
mEventDeclinedExtrasPaint.setTextSize(TEXT_SIZE_EVENT);
mEventDeclinedExtrasPaint.setColor(mMonthDeclinedExtrasColor);
mEventDeclinedExtrasPaint.setStyle(Style.FILL);
mEventDeclinedExtrasPaint.setTextAlign(Align.LEFT);
mWeekNumPaint = new Paint();
mWeekNumPaint.setFakeBoldText(false);
mWeekNumPaint.setAntiAlias(true);
mWeekNumPaint.setTextSize(TEXT_SIZE_WEEK_NUM);
mWeekNumPaint.setColor(mWeekNumColor);
mWeekNumPaint.setStyle(Style.FILL);
mWeekNumPaint.setTextAlign(Align.RIGHT);
mWeekNumAscentHeight = (int) (-mWeekNumPaint.ascent() + 0.5f);
mDNAAllDayPaint = new Paint();
mDNATimePaint = new Paint();
mDNATimePaint.setColor(mMonthBusyBitsBusyTimeColor);
mDNATimePaint.setStyle(Style.FILL_AND_STROKE);
mDNATimePaint.setStrokeWidth(DNA_WIDTH);
mDNATimePaint.setAntiAlias(false);
mDNAAllDayPaint.setColor(mMonthBusyBitsConflictTimeColor);
mDNAAllDayPaint.setStyle(Style.FILL_AND_STROKE);
mDNAAllDayPaint.setStrokeWidth(DNA_ALL_DAY_WIDTH);
mDNAAllDayPaint.setAntiAlias(false);
mEventSquarePaint = new Paint();
mEventSquarePaint.setStrokeWidth(EVENT_SQUARE_BORDER);
mEventSquarePaint.setAntiAlias(false);
if (DEBUG_LAYOUT) {
Log.d("EXTRA", "mScale=" + mScale);
Log.d("EXTRA", "mMonthNumPaint ascent=" + mMonthNumPaint.ascent()
+ " descent=" + mMonthNumPaint.descent() + " int height=" + mMonthNumHeight);
Log.d("EXTRA", "mEventPaint ascent=" + mEventPaint.ascent()
+ " descent=" + mEventPaint.descent() + " int height=" + mEventHeight
+ " int ascent=" + mEventAscentHeight);
Log.d("EXTRA", "mEventExtrasPaint ascent=" + mEventExtrasPaint.ascent()
+ " descent=" + mEventExtrasPaint.descent() + " int height=" + mExtrasHeight);
Log.d("EXTRA", "mWeekNumPaint ascent=" + mWeekNumPaint.ascent()
+ " descent=" + mWeekNumPaint.descent());
}
}
| protected void initView() {
super.initView();
if (!mInitialized) {
Resources resources = getContext().getResources();
mShowDetailsInMonth = Utils.getConfigBool(getContext(), R.bool.show_details_in_month);
TEXT_SIZE_EVENT_TITLE = resources.getInteger(R.integer.text_size_event_title);
TEXT_SIZE_MONTH_NUMBER = resources.getInteger(R.integer.text_size_month_number);
SIDE_PADDING_MONTH_NUMBER = resources.getInteger(R.integer.month_day_number_margin);
CONFLICT_COLOR = resources.getColor(R.color.month_dna_conflict_time_color);
EVENT_TEXT_COLOR = resources.getColor(R.color.calendar_event_text_color);
if (mScale != 1) {
TOP_PADDING_MONTH_NUMBER *= mScale;
TOP_PADDING_WEEK_NUMBER *= mScale;
SIDE_PADDING_MONTH_NUMBER *= mScale;
SIDE_PADDING_WEEK_NUMBER *= mScale;
SPACING_WEEK_NUMBER *= mScale;
TEXT_SIZE_MONTH_NUMBER *= mScale;
TEXT_SIZE_EVENT *= mScale;
TEXT_SIZE_EVENT_TITLE *= mScale;
TEXT_SIZE_MORE_EVENTS *= mScale;
TEXT_SIZE_MONTH_NAME *= mScale;
TEXT_SIZE_WEEK_NUM *= mScale;
DAY_SEPARATOR_OUTER_WIDTH *= mScale;
DAY_SEPARATOR_INNER_WIDTH *= mScale;
DAY_SEPARATOR_VERTICAL_LENGTH *= mScale;
DAY_SEPARATOR_VERTICAL_LENGHT_PORTRAIT *= mScale;
EVENT_X_OFFSET_LANDSCAPE *= mScale;
EVENT_Y_OFFSET_LANDSCAPE *= mScale;
EVENT_Y_OFFSET_PORTRAIT *= mScale;
EVENT_SQUARE_WIDTH *= mScale;
EVENT_SQUARE_BORDER *= mScale;
EVENT_LINE_PADDING *= mScale;
EVENT_BOTTOM_PADDING *= mScale;
EVENT_RIGHT_PADDING *= mScale;
DNA_MARGIN *= mScale;
DNA_WIDTH *= mScale;
DNA_ALL_DAY_HEIGHT *= mScale;
DNA_MIN_SEGMENT_HEIGHT *= mScale;
DNA_SIDE_PADDING *= mScale;
DEFAULT_EDGE_SPACING *= mScale;
DNA_ALL_DAY_WIDTH *= mScale;
TODAY_HIGHLIGHT_WIDTH *= mScale;
}
if (!mShowDetailsInMonth) {
TOP_PADDING_MONTH_NUMBER += DNA_ALL_DAY_HEIGHT + DNA_MARGIN;
}
mInitialized = true;
}
mPadding = DEFAULT_EDGE_SPACING;
loadColors(getContext());
// TODO modify paint properties depending on isMini
mMonthNumPaint = new Paint();
mMonthNumPaint.setFakeBoldText(false);
mMonthNumPaint.setAntiAlias(true);
mMonthNumPaint.setTextSize(TEXT_SIZE_MONTH_NUMBER);
mMonthNumPaint.setColor(mMonthNumColor);
mMonthNumPaint.setStyle(Style.FILL);
mMonthNumPaint.setTextAlign(Align.RIGHT);
mMonthNumPaint.setTypeface(Typeface.DEFAULT);
mMonthNumAscentHeight = (int) (-mMonthNumPaint.ascent() + 0.5f);
mMonthNumHeight = (int) (mMonthNumPaint.descent() - mMonthNumPaint.ascent() + 0.5f);
mEventPaint = new TextPaint();
mEventPaint.setFakeBoldText(true);
mEventPaint.setAntiAlias(true);
mEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE);
mEventPaint.setColor(mMonthEventColor);
mSolidBackgroundEventPaint = new TextPaint(mEventPaint);
mSolidBackgroundEventPaint.setColor(EVENT_TEXT_COLOR);
mFramedEventPaint = new TextPaint(mSolidBackgroundEventPaint);
mDeclinedEventPaint = new TextPaint();
mDeclinedEventPaint.setFakeBoldText(true);
mDeclinedEventPaint.setAntiAlias(true);
mDeclinedEventPaint.setTextSize(TEXT_SIZE_EVENT_TITLE);
mDeclinedEventPaint.setColor(mMonthDeclinedEventColor);
mEventAscentHeight = (int) (-mEventPaint.ascent() + 0.5f);
mEventHeight = (int) (mEventPaint.descent() - mEventPaint.ascent() + 0.5f);
mEventExtrasPaint = new TextPaint();
mEventExtrasPaint.setFakeBoldText(false);
mEventExtrasPaint.setAntiAlias(true);
mEventExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER);
mEventExtrasPaint.setTextSize(TEXT_SIZE_EVENT);
mEventExtrasPaint.setColor(mMonthEventExtraColor);
mEventExtrasPaint.setStyle(Style.FILL);
mEventExtrasPaint.setTextAlign(Align.LEFT);
mExtrasHeight = (int)(mEventExtrasPaint.descent() - mEventExtrasPaint.ascent() + 0.5f);
mExtrasAscentHeight = (int)(-mEventExtrasPaint.ascent() + 0.5f);
mExtrasDescent = (int)(mEventExtrasPaint.descent() + 0.5f);
mEventDeclinedExtrasPaint = new TextPaint();
mEventDeclinedExtrasPaint.setFakeBoldText(false);
mEventDeclinedExtrasPaint.setAntiAlias(true);
mEventDeclinedExtrasPaint.setStrokeWidth(EVENT_SQUARE_BORDER);
mEventDeclinedExtrasPaint.setTextSize(TEXT_SIZE_EVENT);
mEventDeclinedExtrasPaint.setColor(mMonthDeclinedExtrasColor);
mEventDeclinedExtrasPaint.setStyle(Style.FILL);
mEventDeclinedExtrasPaint.setTextAlign(Align.LEFT);
mWeekNumPaint = new Paint();
mWeekNumPaint.setFakeBoldText(false);
mWeekNumPaint.setAntiAlias(true);
mWeekNumPaint.setTextSize(TEXT_SIZE_WEEK_NUM);
mWeekNumPaint.setColor(mWeekNumColor);
mWeekNumPaint.setStyle(Style.FILL);
mWeekNumPaint.setTextAlign(Align.RIGHT);
mWeekNumAscentHeight = (int) (-mWeekNumPaint.ascent() + 0.5f);
mDNAAllDayPaint = new Paint();
mDNATimePaint = new Paint();
mDNATimePaint.setColor(mMonthBusyBitsBusyTimeColor);
mDNATimePaint.setStyle(Style.FILL_AND_STROKE);
mDNATimePaint.setStrokeWidth(DNA_WIDTH);
mDNATimePaint.setAntiAlias(false);
mDNAAllDayPaint.setColor(mMonthBusyBitsConflictTimeColor);
mDNAAllDayPaint.setStyle(Style.FILL_AND_STROKE);
mDNAAllDayPaint.setStrokeWidth(DNA_ALL_DAY_WIDTH);
mDNAAllDayPaint.setAntiAlias(false);
mEventSquarePaint = new Paint();
mEventSquarePaint.setStrokeWidth(EVENT_SQUARE_BORDER);
mEventSquarePaint.setAntiAlias(false);
if (DEBUG_LAYOUT) {
Log.d("EXTRA", "mScale=" + mScale);
Log.d("EXTRA", "mMonthNumPaint ascent=" + mMonthNumPaint.ascent()
+ " descent=" + mMonthNumPaint.descent() + " int height=" + mMonthNumHeight);
Log.d("EXTRA", "mEventPaint ascent=" + mEventPaint.ascent()
+ " descent=" + mEventPaint.descent() + " int height=" + mEventHeight
+ " int ascent=" + mEventAscentHeight);
Log.d("EXTRA", "mEventExtrasPaint ascent=" + mEventExtrasPaint.ascent()
+ " descent=" + mEventExtrasPaint.descent() + " int height=" + mExtrasHeight);
Log.d("EXTRA", "mWeekNumPaint ascent=" + mWeekNumPaint.ascent()
+ " descent=" + mWeekNumPaint.descent());
}
}
|
diff --git a/source/de/anomic/plasma/plasmaCrawlWorker.java b/source/de/anomic/plasma/plasmaCrawlWorker.java
index 2e2c3cb64..885bd83cd 100644
--- a/source/de/anomic/plasma/plasmaCrawlWorker.java
+++ b/source/de/anomic/plasma/plasmaCrawlWorker.java
@@ -1,498 +1,501 @@
//plasmaCrawlWorker.java
//------------------------
//part of YaCy
//(C) by Michael Peter Christen; [email protected]
//first published on http://www.anomic.de
//Frankfurt, Germany, 2004
//last major change: 21.04.2005 by Martin Thelian
//
//This program is free software; you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation; either version 2 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//Using this software in any meaning (reading, learning, copying, compiling,
//running) means that you agree that the Author(s) is (are) not responsible
//for cost, loss of data or any harm that may be caused directly or indirectly
//by usage of this softare or this documentation. The usage of this software
//is on your own risk. The installation and usage (starting/running) of this
//software may allow other people or application to access your computer and
//any attached devices and is highly dependent on the configuration of the
//software which must be done by the user of the software; the author(s) is
//(are) also not responsible for proper configuration and usage of the
//software, even if provoked by documentation provided together with
//the software.
//
//Any changes to this file according to the GPL as documented in the file
//gpl.txt aside this file in the shipment you received can be done to the
//lines that follows this copyright notice here, but changes must not be
//done inside the copyright notive above. A re-distribution must contain
//the intact and unchanged copyright notice.
//Contributions and changes to the program code must be marked as such.
package de.anomic.plasma;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.URL;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.anomic.http.httpHeader;
import de.anomic.http.httpc;
import de.anomic.http.httpdProxyHandler;
import de.anomic.server.serverCore;
import de.anomic.server.serverDate;
import de.anomic.server.logging.serverLog;
import de.anomic.server.logging.serverMiniLogFormatter;
public final class plasmaCrawlWorker extends Thread {
private static final int DEFAULT_CRAWLING_RETRY_COUNT = 5;
private static final String threadBaseName = "CrawlerWorker";
private final CrawlerPool myPool;
private final plasmaHTCache cacheManager;
private final int socketTimeout;
private final boolean remoteProxyUse;
private final String remoteProxyHost;
private final int remoteProxyPort;
private final serverLog log;
public plasmaCrawlLoaderMessage theMsg;
private URL url;
private String name;
private String referer;
private String initiator;
private int depth;
private long startdate;
private plasmaCrawlProfile.entry profile;
//private String error;
private boolean running = false;
private boolean stopped = false;
private boolean done = false;
private static boolean doAccessLogging = false;
/**
* Do logging configuration for special proxy access log file
*/
static {
try {
Logger crawlerLogger = Logger.getLogger("CRAWLER.access");
crawlerLogger.setUseParentHandlers(false);
FileHandler txtLog = new FileHandler("log/crawlerAccess%u%g.log",1024*1024, 20, true);
txtLog.setFormatter(new serverMiniLogFormatter());
txtLog.setLevel(Level.FINEST);
crawlerLogger.addHandler(txtLog);
doAccessLogging = true;
} catch (Exception e) {
System.err.println("PROXY: Unable to configure proxy access logging.");
}
}
public plasmaCrawlWorker(
ThreadGroup theTG,
CrawlerPool thePool,
plasmaHTCache cacheManager,
int socketTimeout,
boolean remoteProxyUse,
String remoteProxyHost,
int remoteProxyPort,
serverLog log) {
super(theTG,threadBaseName + "_inPool");
this.myPool = thePool;
this.cacheManager = cacheManager;
this.socketTimeout = socketTimeout;
this.remoteProxyUse = remoteProxyUse;
this.remoteProxyHost = remoteProxyHost;
this.remoteProxyPort = remoteProxyPort;
this.log = log;
}
public synchronized void execute(plasmaCrawlLoaderMessage theMsg) {
this.theMsg = theMsg;
this.url = theMsg.url;
this.name = theMsg.name;
this.referer = theMsg.referer;
this.initiator = theMsg.initiator;
this.depth = theMsg.depth;
this.profile = theMsg.profile;
this.startdate = System.currentTimeMillis();
//this.error = null;
this.done = false;
if (!this.running) {
// this.setDaemon(true);
this.start();
} else {
this.notifyAll();
}
}
public void reset() {
this.url = null;
this.referer = null;
this.initiator = null;
this.depth = 0;
this.startdate = 0;
this.profile = null;
//this.error = null;
}
public void run() {
this.running = true;
// The thread keeps running.
while (!this.stopped && !Thread.interrupted()) {
if (this.done) {
// We are waiting for a task now.
synchronized (this) {
try {
this.wait(); //Wait until we get a request to process.
}
catch (InterruptedException e) {
this.stopped = true;
// log.error("", e);
}
}
}
else
{
//There is a task....let us execute it.
try {
execute();
} catch (Exception e) {
// log.error("", e);
}
finally {
reset();
if (!this.stopped && !this.isInterrupted()) {
try {
this.myPool.returnObject(this);
this.setName(this.threadBaseName + "_inPool");
}
catch (Exception e1) {
log.logError("pool error", e1);
}
}
}
}
}
}
public void execute() throws IOException {
try {
this.setName(this.threadBaseName + "_" + this.url);
load(this.url, this.name, this.referer, this.initiator, this.depth, this.profile,
this.socketTimeout, this.remoteProxyHost, this.remoteProxyPort, this.remoteProxyUse,
this.cacheManager, this.log);
} catch (IOException e) {
//throw e;
}
finally {
this.done = true;
}
}
public void setStopped(boolean stopped) {
this.stopped = stopped;
}
public boolean isRunning() {
return this.running;
}
public void close() {
if (this.isAlive()) {
try {
// trying to close all still open httpc-Sockets first
int closedSockets = httpc.closeOpenSockets(this);
if (closedSockets > 0) {
this.log.logInfo(closedSockets + " HTTP-client sockets of thread '" + this.getName() + "' closed.");
}
} catch (Exception e) {}
}
}
public static void load(
URL url,
String name,
String referer,
String initiator,
int depth,
plasmaCrawlProfile.entry profile,
int socketTimeout,
String remoteProxyHost,
int remoteProxyPort,
boolean remoteProxyUse,
plasmaHTCache cacheManager,
serverLog log
) throws IOException {
load(url,
name,
referer,
initiator,
depth,
profile,
socketTimeout,
remoteProxyHost,
remoteProxyPort,
remoteProxyUse,
cacheManager,
log,
DEFAULT_CRAWLING_RETRY_COUNT,
true
);
}
private static void load(
URL url,
String name,
String referer,
String initiator,
int depth,
plasmaCrawlProfile.entry profile,
int socketTimeout,
String remoteProxyHost,
int remoteProxyPort,
boolean remoteProxyUse,
plasmaHTCache cacheManager,
serverLog log,
int crawlingRetryCount,
boolean useContentEncodingGzip
) throws IOException {
if (url == null) return;
// if the recrawling limit was exceeded we stop crawling now
if (crawlingRetryCount <= 0) return;
Date requestDate = new Date(); // remember the time...
String host = url.getHost();
String path = url.getPath();
int port = url.getPort();
boolean ssl = url.getProtocol().equals("https");
if (port < 0) port = (ssl) ? 443 : 80;
// set referrer; in some case advertise a little bit:
referer = (referer == null) ? "" : referer.trim();
if (referer.length() == 0) referer = "http://www.yacy.net/yacy/";
// take a file from the net
httpc remote = null;
try {
plasmaSwitchboard sb = plasmaCrawlLoader.switchboard;
// create a request header
httpHeader requestHeader = new httpHeader();
requestHeader.put(httpHeader.USER_AGENT, httpdProxyHandler.userAgent);
requestHeader.put(httpHeader.REFERER, referer);
requestHeader.put(httpHeader.ACCEPT_LANGUAGE, sb.getConfig("crawler.acceptLanguage","en-us,en;q=0.5"));
requestHeader.put(httpHeader.ACCEPT_CHARSET, sb.getConfig("crawler.acceptCharset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"));
if (useContentEncodingGzip) requestHeader.put(httpHeader.ACCEPT_ENCODING, "gzip,deflate");
//System.out.println("CRAWLER_REQUEST_HEADER=" + requestHeader.toString()); // DEBUG
// open the connection
remote = (remoteProxyUse) ? httpc.getInstance(host, port, socketTimeout, ssl, remoteProxyHost, remoteProxyPort)
: httpc.getInstance(host, port, socketTimeout, ssl);
// specifying if content encoding is allowed
remote.setAllowContentEncoding(useContentEncodingGzip);
// send request
httpc.response res = remote.GET(path, requestHeader);
if (res.status.startsWith("200") || res.status.startsWith("203")) {
// the transfer is ok
long contentLength = res.responseHeader.contentLength();
// reserve cache entry
plasmaHTCache.Entry htCache = cacheManager.newEntry(requestDate, depth, url, name, requestHeader, res.status, res.responseHeader, initiator, profile);
// request has been placed and result has been returned. work off response
File cacheFile = cacheManager.getCachePath(url);
try {
String error = null;
if ((!(plasmaParser.supportedMimeTypesContains(res.responseHeader.mime()))) &&
(!(plasmaParser.supportedFileExt(url)))) {
// if the response has not the right file type then reject file
remote.close();
log.logInfo("REJECTED WRONG MIME/EXT TYPE " + res.responseHeader.mime() + " for URL " + url.toString());
} else {
// we write the new cache entry to file system directly
cacheFile.getParentFile().mkdirs();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(cacheFile);
res.writeContent(fos); // superfluous write to array
htCache.cacheArray = null;
cacheManager.writeFileAnnouncement(cacheFile);
//htCache.cacheArray = res.writeContent(fos); // writes in cacheArray and cache file
} finally {
if (fos!=null)try{fos.close();}catch(Exception e){}
}
}
// enQueue new entry with response header
if (profile != null) {
cacheManager.push(htCache);
}
} catch (SocketException e) {
// this may happen if the client suddenly closes its connection
// maybe the user has stopped loading
// in that case, we are not responsible and just forget it
// but we clean the cache also, since it may be only partial
// and most possible corrupted
if (cacheFile.exists()) cacheFile.delete();
log.logError("CRAWLER LOADER ERROR1: with URL=" + url.toString() + ": " + e.toString());
}
} else if (res.status.startsWith("30")) {
if (crawlingRetryCount > 0) {
if (res.responseHeader.containsKey(httpHeader.LOCATION)) {
// getting redirection URL
String redirectionUrlString = (String) res.responseHeader.get(httpHeader.LOCATION);
redirectionUrlString = redirectionUrlString.trim();
// normalizing URL
redirectionUrlString = plasmaParser.urlNormalform(redirectionUrlString);
// generating the new URL object
URL redirectionUrl = new URL(url, redirectionUrlString);
// returning the used httpc
httpc.returnInstance(remote);
remote = null;
// restart crawling with new url
log.logInfo("CRAWLER Redirection detected ('" + res.status + "') for URL " + url.toString() +
"\nRedirecting request to: " + redirectionUrl);
// if we are already doing a shutdown we don't need to retry crawling
if (Thread.currentThread().isInterrupted()) {
log.logError("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown.");
return;
}
// generating url hash
String urlhash = plasmaURL.urlHash(redirectionUrl);
// removing url from loader queue
plasmaCrawlLoader.switchboard.urlPool.noticeURL.remove(urlhash);
// retry crawling with new url
load(redirectionUrl,
name,
referer,
initiator,
depth,
profile,
socketTimeout,
remoteProxyHost,
remoteProxyPort,
remoteProxyUse,
cacheManager,
log,
--crawlingRetryCount,
useContentEncodingGzip
);
}
} else {
log.logInfo("Redirection counter exceeded for URL " + url.toString() + ". Processing aborted.");
}
}else {
// if the response has not the right response type then reject file
log.logInfo("REJECTED WRONG STATUS TYPE '" + res.status + "' for URL " + url.toString());
// not processed any further
}
if (remote != null) remote.close();
} catch (Exception e) {
boolean retryCrawling = false;
String errorMsg = e.getMessage();
if (errorMsg != null) {
if (e instanceof java.net.BindException) {
log.logWarning("CRAWLER BindException detected while trying to download content from '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
} else if (errorMsg.indexOf("Corrupt GZIP trailer") >= 0) {
log.logWarning("CRAWLER Problems detected while receiving gzip encoded content from '" + url.toString() +
"'. Retrying request without using gzip content encoding.");
- retryCrawling = true;
-// java.net.SocketTimeoutException: connect timed out
+ retryCrawling = true;
} else if (errorMsg.indexOf("Socket time-out: Read timed out") >= 0) {
log.logWarning("CRAWLER Read timeout while receiving content from '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
+ } else if (errorMsg.indexOf("connect timed out") >= 0) {
+ log.logWarning("CRAWLER Timeout while trying to connect to '" + url.toString() +
+ "'. Retrying request.");
+ retryCrawling = true;
} else if (errorMsg.indexOf("Connection timed out") >= 0) {
log.logWarning("CRAWLER Connection timeout while receiving content from '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
} else if (errorMsg.indexOf("Connection refused") >= 0) {
log.logError("CRAWLER LOADER ERROR2 with URL=" + url.toString() + ": Connection refused");
}
if (retryCrawling) {
// if we are already doing a shutdown we don't need to retry crawling
if (Thread.currentThread().isInterrupted()) {
log.logError("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown.");
return;
}
// returning the used httpc
httpc.returnInstance(remote);
remote = null;
// setting the retry counter to 1
if (crawlingRetryCount > 2) crawlingRetryCount = 2;
// retry crawling
load(url,
name,
referer,
initiator,
depth,
profile,
socketTimeout,
remoteProxyHost,
remoteProxyPort,
remoteProxyUse,
cacheManager,
log,
--crawlingRetryCount,
false
);
} else {
log.logError("CRAWLER LOADER ERROR2 with URL=" + url.toString() + ": " + e.toString(),e);
}
} else {
// this may happen if the targeted host does not exist or anything with the
// remote server was wrong.
log.logError("CRAWLER LOADER ERROR2 with URL=" + url.toString() + ": " + e.toString(),e);
}
} finally {
if (remote != null) httpc.returnInstance(remote);
}
}
}
| false | true | private static void load(
URL url,
String name,
String referer,
String initiator,
int depth,
plasmaCrawlProfile.entry profile,
int socketTimeout,
String remoteProxyHost,
int remoteProxyPort,
boolean remoteProxyUse,
plasmaHTCache cacheManager,
serverLog log,
int crawlingRetryCount,
boolean useContentEncodingGzip
) throws IOException {
if (url == null) return;
// if the recrawling limit was exceeded we stop crawling now
if (crawlingRetryCount <= 0) return;
Date requestDate = new Date(); // remember the time...
String host = url.getHost();
String path = url.getPath();
int port = url.getPort();
boolean ssl = url.getProtocol().equals("https");
if (port < 0) port = (ssl) ? 443 : 80;
// set referrer; in some case advertise a little bit:
referer = (referer == null) ? "" : referer.trim();
if (referer.length() == 0) referer = "http://www.yacy.net/yacy/";
// take a file from the net
httpc remote = null;
try {
plasmaSwitchboard sb = plasmaCrawlLoader.switchboard;
// create a request header
httpHeader requestHeader = new httpHeader();
requestHeader.put(httpHeader.USER_AGENT, httpdProxyHandler.userAgent);
requestHeader.put(httpHeader.REFERER, referer);
requestHeader.put(httpHeader.ACCEPT_LANGUAGE, sb.getConfig("crawler.acceptLanguage","en-us,en;q=0.5"));
requestHeader.put(httpHeader.ACCEPT_CHARSET, sb.getConfig("crawler.acceptCharset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"));
if (useContentEncodingGzip) requestHeader.put(httpHeader.ACCEPT_ENCODING, "gzip,deflate");
//System.out.println("CRAWLER_REQUEST_HEADER=" + requestHeader.toString()); // DEBUG
// open the connection
remote = (remoteProxyUse) ? httpc.getInstance(host, port, socketTimeout, ssl, remoteProxyHost, remoteProxyPort)
: httpc.getInstance(host, port, socketTimeout, ssl);
// specifying if content encoding is allowed
remote.setAllowContentEncoding(useContentEncodingGzip);
// send request
httpc.response res = remote.GET(path, requestHeader);
if (res.status.startsWith("200") || res.status.startsWith("203")) {
// the transfer is ok
long contentLength = res.responseHeader.contentLength();
// reserve cache entry
plasmaHTCache.Entry htCache = cacheManager.newEntry(requestDate, depth, url, name, requestHeader, res.status, res.responseHeader, initiator, profile);
// request has been placed and result has been returned. work off response
File cacheFile = cacheManager.getCachePath(url);
try {
String error = null;
if ((!(plasmaParser.supportedMimeTypesContains(res.responseHeader.mime()))) &&
(!(plasmaParser.supportedFileExt(url)))) {
// if the response has not the right file type then reject file
remote.close();
log.logInfo("REJECTED WRONG MIME/EXT TYPE " + res.responseHeader.mime() + " for URL " + url.toString());
} else {
// we write the new cache entry to file system directly
cacheFile.getParentFile().mkdirs();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(cacheFile);
res.writeContent(fos); // superfluous write to array
htCache.cacheArray = null;
cacheManager.writeFileAnnouncement(cacheFile);
//htCache.cacheArray = res.writeContent(fos); // writes in cacheArray and cache file
} finally {
if (fos!=null)try{fos.close();}catch(Exception e){}
}
}
// enQueue new entry with response header
if (profile != null) {
cacheManager.push(htCache);
}
} catch (SocketException e) {
// this may happen if the client suddenly closes its connection
// maybe the user has stopped loading
// in that case, we are not responsible and just forget it
// but we clean the cache also, since it may be only partial
// and most possible corrupted
if (cacheFile.exists()) cacheFile.delete();
log.logError("CRAWLER LOADER ERROR1: with URL=" + url.toString() + ": " + e.toString());
}
} else if (res.status.startsWith("30")) {
if (crawlingRetryCount > 0) {
if (res.responseHeader.containsKey(httpHeader.LOCATION)) {
// getting redirection URL
String redirectionUrlString = (String) res.responseHeader.get(httpHeader.LOCATION);
redirectionUrlString = redirectionUrlString.trim();
// normalizing URL
redirectionUrlString = plasmaParser.urlNormalform(redirectionUrlString);
// generating the new URL object
URL redirectionUrl = new URL(url, redirectionUrlString);
// returning the used httpc
httpc.returnInstance(remote);
remote = null;
// restart crawling with new url
log.logInfo("CRAWLER Redirection detected ('" + res.status + "') for URL " + url.toString() +
"\nRedirecting request to: " + redirectionUrl);
// if we are already doing a shutdown we don't need to retry crawling
if (Thread.currentThread().isInterrupted()) {
log.logError("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown.");
return;
}
// generating url hash
String urlhash = plasmaURL.urlHash(redirectionUrl);
// removing url from loader queue
plasmaCrawlLoader.switchboard.urlPool.noticeURL.remove(urlhash);
// retry crawling with new url
load(redirectionUrl,
name,
referer,
initiator,
depth,
profile,
socketTimeout,
remoteProxyHost,
remoteProxyPort,
remoteProxyUse,
cacheManager,
log,
--crawlingRetryCount,
useContentEncodingGzip
);
}
} else {
log.logInfo("Redirection counter exceeded for URL " + url.toString() + ". Processing aborted.");
}
}else {
// if the response has not the right response type then reject file
log.logInfo("REJECTED WRONG STATUS TYPE '" + res.status + "' for URL " + url.toString());
// not processed any further
}
if (remote != null) remote.close();
} catch (Exception e) {
boolean retryCrawling = false;
String errorMsg = e.getMessage();
if (errorMsg != null) {
if (e instanceof java.net.BindException) {
log.logWarning("CRAWLER BindException detected while trying to download content from '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
} else if (errorMsg.indexOf("Corrupt GZIP trailer") >= 0) {
log.logWarning("CRAWLER Problems detected while receiving gzip encoded content from '" + url.toString() +
"'. Retrying request without using gzip content encoding.");
retryCrawling = true;
// java.net.SocketTimeoutException: connect timed out
} else if (errorMsg.indexOf("Socket time-out: Read timed out") >= 0) {
log.logWarning("CRAWLER Read timeout while receiving content from '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
} else if (errorMsg.indexOf("Connection timed out") >= 0) {
log.logWarning("CRAWLER Connection timeout while receiving content from '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
} else if (errorMsg.indexOf("Connection refused") >= 0) {
log.logError("CRAWLER LOADER ERROR2 with URL=" + url.toString() + ": Connection refused");
}
if (retryCrawling) {
// if we are already doing a shutdown we don't need to retry crawling
if (Thread.currentThread().isInterrupted()) {
log.logError("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown.");
return;
}
// returning the used httpc
httpc.returnInstance(remote);
remote = null;
// setting the retry counter to 1
if (crawlingRetryCount > 2) crawlingRetryCount = 2;
// retry crawling
load(url,
name,
referer,
initiator,
depth,
profile,
socketTimeout,
remoteProxyHost,
remoteProxyPort,
remoteProxyUse,
cacheManager,
log,
--crawlingRetryCount,
false
);
} else {
log.logError("CRAWLER LOADER ERROR2 with URL=" + url.toString() + ": " + e.toString(),e);
}
} else {
// this may happen if the targeted host does not exist or anything with the
// remote server was wrong.
log.logError("CRAWLER LOADER ERROR2 with URL=" + url.toString() + ": " + e.toString(),e);
}
} finally {
if (remote != null) httpc.returnInstance(remote);
}
}
| private static void load(
URL url,
String name,
String referer,
String initiator,
int depth,
plasmaCrawlProfile.entry profile,
int socketTimeout,
String remoteProxyHost,
int remoteProxyPort,
boolean remoteProxyUse,
plasmaHTCache cacheManager,
serverLog log,
int crawlingRetryCount,
boolean useContentEncodingGzip
) throws IOException {
if (url == null) return;
// if the recrawling limit was exceeded we stop crawling now
if (crawlingRetryCount <= 0) return;
Date requestDate = new Date(); // remember the time...
String host = url.getHost();
String path = url.getPath();
int port = url.getPort();
boolean ssl = url.getProtocol().equals("https");
if (port < 0) port = (ssl) ? 443 : 80;
// set referrer; in some case advertise a little bit:
referer = (referer == null) ? "" : referer.trim();
if (referer.length() == 0) referer = "http://www.yacy.net/yacy/";
// take a file from the net
httpc remote = null;
try {
plasmaSwitchboard sb = plasmaCrawlLoader.switchboard;
// create a request header
httpHeader requestHeader = new httpHeader();
requestHeader.put(httpHeader.USER_AGENT, httpdProxyHandler.userAgent);
requestHeader.put(httpHeader.REFERER, referer);
requestHeader.put(httpHeader.ACCEPT_LANGUAGE, sb.getConfig("crawler.acceptLanguage","en-us,en;q=0.5"));
requestHeader.put(httpHeader.ACCEPT_CHARSET, sb.getConfig("crawler.acceptCharset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"));
if (useContentEncodingGzip) requestHeader.put(httpHeader.ACCEPT_ENCODING, "gzip,deflate");
//System.out.println("CRAWLER_REQUEST_HEADER=" + requestHeader.toString()); // DEBUG
// open the connection
remote = (remoteProxyUse) ? httpc.getInstance(host, port, socketTimeout, ssl, remoteProxyHost, remoteProxyPort)
: httpc.getInstance(host, port, socketTimeout, ssl);
// specifying if content encoding is allowed
remote.setAllowContentEncoding(useContentEncodingGzip);
// send request
httpc.response res = remote.GET(path, requestHeader);
if (res.status.startsWith("200") || res.status.startsWith("203")) {
// the transfer is ok
long contentLength = res.responseHeader.contentLength();
// reserve cache entry
plasmaHTCache.Entry htCache = cacheManager.newEntry(requestDate, depth, url, name, requestHeader, res.status, res.responseHeader, initiator, profile);
// request has been placed and result has been returned. work off response
File cacheFile = cacheManager.getCachePath(url);
try {
String error = null;
if ((!(plasmaParser.supportedMimeTypesContains(res.responseHeader.mime()))) &&
(!(plasmaParser.supportedFileExt(url)))) {
// if the response has not the right file type then reject file
remote.close();
log.logInfo("REJECTED WRONG MIME/EXT TYPE " + res.responseHeader.mime() + " for URL " + url.toString());
} else {
// we write the new cache entry to file system directly
cacheFile.getParentFile().mkdirs();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(cacheFile);
res.writeContent(fos); // superfluous write to array
htCache.cacheArray = null;
cacheManager.writeFileAnnouncement(cacheFile);
//htCache.cacheArray = res.writeContent(fos); // writes in cacheArray and cache file
} finally {
if (fos!=null)try{fos.close();}catch(Exception e){}
}
}
// enQueue new entry with response header
if (profile != null) {
cacheManager.push(htCache);
}
} catch (SocketException e) {
// this may happen if the client suddenly closes its connection
// maybe the user has stopped loading
// in that case, we are not responsible and just forget it
// but we clean the cache also, since it may be only partial
// and most possible corrupted
if (cacheFile.exists()) cacheFile.delete();
log.logError("CRAWLER LOADER ERROR1: with URL=" + url.toString() + ": " + e.toString());
}
} else if (res.status.startsWith("30")) {
if (crawlingRetryCount > 0) {
if (res.responseHeader.containsKey(httpHeader.LOCATION)) {
// getting redirection URL
String redirectionUrlString = (String) res.responseHeader.get(httpHeader.LOCATION);
redirectionUrlString = redirectionUrlString.trim();
// normalizing URL
redirectionUrlString = plasmaParser.urlNormalform(redirectionUrlString);
// generating the new URL object
URL redirectionUrl = new URL(url, redirectionUrlString);
// returning the used httpc
httpc.returnInstance(remote);
remote = null;
// restart crawling with new url
log.logInfo("CRAWLER Redirection detected ('" + res.status + "') for URL " + url.toString() +
"\nRedirecting request to: " + redirectionUrl);
// if we are already doing a shutdown we don't need to retry crawling
if (Thread.currentThread().isInterrupted()) {
log.logError("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown.");
return;
}
// generating url hash
String urlhash = plasmaURL.urlHash(redirectionUrl);
// removing url from loader queue
plasmaCrawlLoader.switchboard.urlPool.noticeURL.remove(urlhash);
// retry crawling with new url
load(redirectionUrl,
name,
referer,
initiator,
depth,
profile,
socketTimeout,
remoteProxyHost,
remoteProxyPort,
remoteProxyUse,
cacheManager,
log,
--crawlingRetryCount,
useContentEncodingGzip
);
}
} else {
log.logInfo("Redirection counter exceeded for URL " + url.toString() + ". Processing aborted.");
}
}else {
// if the response has not the right response type then reject file
log.logInfo("REJECTED WRONG STATUS TYPE '" + res.status + "' for URL " + url.toString());
// not processed any further
}
if (remote != null) remote.close();
} catch (Exception e) {
boolean retryCrawling = false;
String errorMsg = e.getMessage();
if (errorMsg != null) {
if (e instanceof java.net.BindException) {
log.logWarning("CRAWLER BindException detected while trying to download content from '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
} else if (errorMsg.indexOf("Corrupt GZIP trailer") >= 0) {
log.logWarning("CRAWLER Problems detected while receiving gzip encoded content from '" + url.toString() +
"'. Retrying request without using gzip content encoding.");
retryCrawling = true;
} else if (errorMsg.indexOf("Socket time-out: Read timed out") >= 0) {
log.logWarning("CRAWLER Read timeout while receiving content from '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
} else if (errorMsg.indexOf("connect timed out") >= 0) {
log.logWarning("CRAWLER Timeout while trying to connect to '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
} else if (errorMsg.indexOf("Connection timed out") >= 0) {
log.logWarning("CRAWLER Connection timeout while receiving content from '" + url.toString() +
"'. Retrying request.");
retryCrawling = true;
} else if (errorMsg.indexOf("Connection refused") >= 0) {
log.logError("CRAWLER LOADER ERROR2 with URL=" + url.toString() + ": Connection refused");
}
if (retryCrawling) {
// if we are already doing a shutdown we don't need to retry crawling
if (Thread.currentThread().isInterrupted()) {
log.logError("CRAWLER Retry of URL=" + url.toString() + " aborted because of server shutdown.");
return;
}
// returning the used httpc
httpc.returnInstance(remote);
remote = null;
// setting the retry counter to 1
if (crawlingRetryCount > 2) crawlingRetryCount = 2;
// retry crawling
load(url,
name,
referer,
initiator,
depth,
profile,
socketTimeout,
remoteProxyHost,
remoteProxyPort,
remoteProxyUse,
cacheManager,
log,
--crawlingRetryCount,
false
);
} else {
log.logError("CRAWLER LOADER ERROR2 with URL=" + url.toString() + ": " + e.toString(),e);
}
} else {
// this may happen if the targeted host does not exist or anything with the
// remote server was wrong.
log.logError("CRAWLER LOADER ERROR2 with URL=" + url.toString() + ": " + e.toString(),e);
}
} finally {
if (remote != null) httpc.returnInstance(remote);
}
}
|
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java
index a0dfcbab..cb988cfa 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettingsController.java
@@ -1,351 +1,351 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.statusbar.phone;
import static com.android.internal.util.cm.QSConstants.TILES_DEFAULT;
import static com.android.internal.util.cm.QSConstants.TILE_AIRPLANE;
import static com.android.internal.util.cm.QSConstants.TILE_AUTOROTATE;
import static com.android.internal.util.cm.QSConstants.TILE_BATTERY;
import static com.android.internal.util.cm.QSConstants.TILE_BLUETOOTH;
import static com.android.internal.util.cm.QSConstants.TILE_BRIGHTNESS;
import static com.android.internal.util.cm.QSConstants.TILE_DELIMITER;
import static com.android.internal.util.cm.QSConstants.TILE_GPS;
import static com.android.internal.util.cm.QSConstants.TILE_HOLOBAM;
import static com.android.internal.util.cm.QSConstants.TILE_LOCKSCREEN;
import static com.android.internal.util.cm.QSConstants.TILE_MOBILEDATA;
import static com.android.internal.util.cm.QSConstants.TILE_NETWORKMODE;
import static com.android.internal.util.cm.QSConstants.TILE_NFC;
import static com.android.internal.util.cm.QSConstants.TILE_RINGER;
import static com.android.internal.util.cm.QSConstants.TILE_SCREENTIMEOUT;
import static com.android.internal.util.cm.QSConstants.TILE_SETTINGS;
import static com.android.internal.util.cm.QSConstants.TILE_SLEEP;
import static com.android.internal.util.cm.QSConstants.TILE_SYNC;
import static com.android.internal.util.cm.QSConstants.TILE_TORCH;
import static com.android.internal.util.cm.QSConstants.TILE_USER;
import static com.android.internal.util.cm.QSConstants.TILE_VOLUME;
import static com.android.internal.util.cm.QSConstants.TILE_WIFI;
import static com.android.internal.util.cm.QSConstants.TILE_WIFIAP;
import static com.android.internal.util.cm.QSConstants.TILE_DESKTOPMODE;
import static com.android.internal.util.cm.QSConstants.TILE_HYBRID;
import static com.android.internal.util.cm.QSConstants.TILE_REBOOT;
import static com.android.internal.util.cm.QSUtils.deviceSupportsBluetooth;
import static com.android.internal.util.cm.QSUtils.deviceSupportsTelephony;
import static com.android.internal.util.cm.QSUtils.deviceSupportsUsbTether;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import com.android.systemui.statusbar.BaseStatusBar;
import com.android.systemui.quicksettings.AirplaneModeTile;
import com.android.systemui.quicksettings.AlarmTile;
import com.android.systemui.quicksettings.AutoRotateTile;
import com.android.systemui.quicksettings.BatteryTile;
import com.android.systemui.quicksettings.BluetoothTile;
import com.android.systemui.quicksettings.BrightnessTile;
import com.android.systemui.quicksettings.BugReportTile;
import com.android.systemui.quicksettings.GPSTile;
import com.android.systemui.quicksettings.HolobamTile;
import com.android.systemui.quicksettings.InputMethodTile;
import com.android.systemui.quicksettings.MobileNetworkTile;
import com.android.systemui.quicksettings.MobileNetworkTypeTile;
import com.android.systemui.quicksettings.NfcTile;
import com.android.systemui.quicksettings.PreferencesTile;
import com.android.systemui.quicksettings.QuickSettingsTile;
import com.android.systemui.quicksettings.RingerModeTile;
import com.android.systemui.quicksettings.ScreenTimeoutTile;
import com.android.systemui.quicksettings.SleepScreenTile;
import com.android.systemui.quicksettings.SyncTile;
import com.android.systemui.quicksettings.ToggleLockscreenTile;
import com.android.systemui.quicksettings.TorchTile;
import com.android.systemui.quicksettings.UsbTetherTile;
import com.android.systemui.quicksettings.UserTile;
import com.android.systemui.quicksettings.VolumeTile;
import com.android.systemui.quicksettings.WiFiDisplayTile;
import com.android.systemui.quicksettings.WiFiTile;
import com.android.systemui.quicksettings.WifiAPTile;
import com.android.systemui.quicksettings.DesktopModeTile;
import com.android.systemui.quicksettings.HybridTile;
import com.android.systemui.quicksettings.RebootTile;
import com.android.systemui.statusbar.powerwidget.PowerButton;
import java.util.ArrayList;
import java.util.HashMap;
public class QuickSettingsController {
private static String TAG = "QuickSettingsController";
// Stores the broadcast receivers and content observers
// quick tiles register for.
public HashMap<String, ArrayList<QuickSettingsTile>> mReceiverMap
= new HashMap<String, ArrayList<QuickSettingsTile>>();
public HashMap<Uri, ArrayList<QuickSettingsTile>> mObserverMap
= new HashMap<Uri, ArrayList<QuickSettingsTile>>();
private final Context mContext;
private ArrayList<QuickSettingsTile> mQuickSettingsTiles;
public PanelBar mBar;
private final QuickSettingsContainerView mContainerView;
private final Handler mHandler;
private BroadcastReceiver mReceiver;
private ContentObserver mObserver;
public BaseStatusBar mStatusBarService;
private InputMethodTile mIMETile;
public QuickSettingsController(Context context, QuickSettingsContainerView container, BaseStatusBar statusBarService) {
mContext = context;
mContainerView = container;
mHandler = new Handler();
mStatusBarService = statusBarService;
mQuickSettingsTiles = new ArrayList<QuickSettingsTile>();
}
void loadTiles() {
// Reset reference tiles
mIMETile = null;
// Filter items not compatible with device
boolean bluetoothSupported = deviceSupportsBluetooth();
boolean telephonySupported = deviceSupportsTelephony(mContext);
if (!bluetoothSupported) {
TILES_DEFAULT.remove(TILE_BLUETOOTH);
}
if (!telephonySupported) {
TILES_DEFAULT.remove(TILE_WIFIAP);
TILES_DEFAULT.remove(TILE_MOBILEDATA);
TILES_DEFAULT.remove(TILE_NETWORKMODE);
}
// Read the stored list of tiles
ContentResolver resolver = mContext.getContentResolver();
LayoutInflater inflater = LayoutInflater.from(mContext);
String tiles = Settings.System.getString(resolver, Settings.System.QUICK_SETTINGS);
if (tiles == null) {
Log.i(TAG, "Default tiles being loaded");
tiles = TextUtils.join(TILE_DELIMITER, TILES_DEFAULT);
}
Log.i(TAG, "Tiles list: " + tiles);
// Split out the tile names and add to the list
for (String tile : tiles.split("\\|")) {
QuickSettingsTile qs = null;
if (tile.equals(TILE_USER)) {
qs = new UserTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BATTERY)) {
qs = new BatteryTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SETTINGS)) {
qs = new PreferencesTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFI)) {
qs = new WiFiTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_GPS)) {
qs = new GPSTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BLUETOOTH) && bluetoothSupported) {
qs = new BluetoothTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BRIGHTNESS)) {
qs = new BrightnessTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_RINGER)) {
qs = new RingerModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SYNC)) {
qs = new SyncTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFIAP) && telephonySupported) {
qs = new WifiAPTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SCREENTIMEOUT)) {
qs = new ScreenTimeoutTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_MOBILEDATA) && telephonySupported) {
qs = new MobileNetworkTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_LOCKSCREEN)) {
qs = new ToggleLockscreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_AUTOROTATE)) {
qs = new AutoRotateTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_AIRPLANE)) {
qs = new AirplaneModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_TORCH)) {
qs = new TorchTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_SLEEP)) {
qs = new SleepScreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_NFC)) {
// User cannot add the NFC tile if the device does not support it
// No need to check again here
qs = new NfcTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_DESKTOPMODE)) {
qs = new DesktopModeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HYBRID)) {
qs = new HybridTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_VOLUME)) {
qs = new VolumeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_REBOOT)) {
qs = new RebootTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HOLOBAM)) {
qs = new HolobamTile(mContext, inflater, mContainerView, this, mHandler);
- } else if (tile.equals(TILE_NETWORKMODE)) {
- qs = new MobileNetworkTypeTile(mContext, inflater, mContainerView, this, mHandler);
+ } else if (tile.equals(TILE_NETWORKMODE) && telephonySupported) {
+ qs = new MobileNetworkTypeTile(mContext, inflater, mContainerView, this);
}
if (qs != null) {
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
// Load the dynamic tiles
// These toggles must be the last ones added to the view, as they will show
// only when they are needed
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_ALARM, 1) == 1) {
QuickSettingsTile qs = new AlarmTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_BUGREPORT, 1) == 1) {
QuickSettingsTile qs = new BugReportTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_WIFI, 1) == 1) {
QuickSettingsTile qs = new WiFiDisplayTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
mIMETile = new InputMethodTile(mContext, inflater, mContainerView, this);
mIMETile.setupQuickSettingsTile();
mQuickSettingsTiles.add(mIMETile);
if (deviceSupportsUsbTether(mContext) && Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_USBTETHER, 1) == 1) {
QuickSettingsTile qs = new UsbTetherTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
public void setupQuickSettings() {
mQuickSettingsTiles.clear();
mContainerView.removeAllViews();
// Clear out old receiver
if (mReceiver != null) {
mContext.unregisterReceiver(mReceiver);
}
mReceiver = new QSBroadcastReceiver();
mReceiverMap.clear();
ContentResolver resolver = mContext.getContentResolver();
// Clear out old observer
if (mObserver != null) {
resolver.unregisterContentObserver(mObserver);
}
mObserver = new QuickSettingsObserver(mHandler);
mObserverMap.clear();
loadTiles();
setupBroadcastReceiver();
setupContentObserver();
}
void setupContentObserver() {
ContentResolver resolver = mContext.getContentResolver();
for (Uri uri : mObserverMap.keySet()) {
resolver.registerContentObserver(uri, false, mObserver);
}
}
private class QuickSettingsObserver extends ContentObserver {
public QuickSettingsObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange, Uri uri) {
ContentResolver resolver = mContext.getContentResolver();
for (QuickSettingsTile tile : mObserverMap.get(uri)) {
tile.onChangeUri(resolver, uri);
}
}
}
void setupBroadcastReceiver() {
IntentFilter filter = new IntentFilter();
for (String action : mReceiverMap.keySet()) {
filter.addAction(action);
}
mContext.registerReceiver(mReceiver, filter);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void registerInMap(Object item, QuickSettingsTile tile, HashMap map) {
if (map.keySet().contains(item)) {
ArrayList list = (ArrayList) map.get(item);
if (!list.contains(tile)) {
list.add(tile);
}
} else {
ArrayList<QuickSettingsTile> list = new ArrayList<QuickSettingsTile>();
list.add(tile);
map.put(item, list);
}
}
public void registerAction(Object action, QuickSettingsTile tile) {
registerInMap(action, tile, mReceiverMap);
}
public void registerObservedContent(Uri uri, QuickSettingsTile tile) {
registerInMap(uri, tile, mObserverMap);
}
private class QSBroadcastReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null) {
for (QuickSettingsTile t : mReceiverMap.get(action)) {
t.onReceive(context, intent);
}
}
}
};
public void setBar(PanelBar bar) {
mBar = bar;
}
public void setService(BaseStatusBar phoneStatusBar) {
mStatusBarService = phoneStatusBar;
}
public void setImeWindowStatus(boolean visible) {
if (mIMETile != null) {
mIMETile.toggleVisibility(visible);
}
}
public void updateResources() {
mContainerView.updateResources();
for (QuickSettingsTile t : mQuickSettingsTiles) {
t.updateResources();
}
}
}
| true | true | void loadTiles() {
// Reset reference tiles
mIMETile = null;
// Filter items not compatible with device
boolean bluetoothSupported = deviceSupportsBluetooth();
boolean telephonySupported = deviceSupportsTelephony(mContext);
if (!bluetoothSupported) {
TILES_DEFAULT.remove(TILE_BLUETOOTH);
}
if (!telephonySupported) {
TILES_DEFAULT.remove(TILE_WIFIAP);
TILES_DEFAULT.remove(TILE_MOBILEDATA);
TILES_DEFAULT.remove(TILE_NETWORKMODE);
}
// Read the stored list of tiles
ContentResolver resolver = mContext.getContentResolver();
LayoutInflater inflater = LayoutInflater.from(mContext);
String tiles = Settings.System.getString(resolver, Settings.System.QUICK_SETTINGS);
if (tiles == null) {
Log.i(TAG, "Default tiles being loaded");
tiles = TextUtils.join(TILE_DELIMITER, TILES_DEFAULT);
}
Log.i(TAG, "Tiles list: " + tiles);
// Split out the tile names and add to the list
for (String tile : tiles.split("\\|")) {
QuickSettingsTile qs = null;
if (tile.equals(TILE_USER)) {
qs = new UserTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BATTERY)) {
qs = new BatteryTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SETTINGS)) {
qs = new PreferencesTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFI)) {
qs = new WiFiTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_GPS)) {
qs = new GPSTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BLUETOOTH) && bluetoothSupported) {
qs = new BluetoothTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BRIGHTNESS)) {
qs = new BrightnessTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_RINGER)) {
qs = new RingerModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SYNC)) {
qs = new SyncTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFIAP) && telephonySupported) {
qs = new WifiAPTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SCREENTIMEOUT)) {
qs = new ScreenTimeoutTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_MOBILEDATA) && telephonySupported) {
qs = new MobileNetworkTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_LOCKSCREEN)) {
qs = new ToggleLockscreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_AUTOROTATE)) {
qs = new AutoRotateTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_AIRPLANE)) {
qs = new AirplaneModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_TORCH)) {
qs = new TorchTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_SLEEP)) {
qs = new SleepScreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_NFC)) {
// User cannot add the NFC tile if the device does not support it
// No need to check again here
qs = new NfcTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_DESKTOPMODE)) {
qs = new DesktopModeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HYBRID)) {
qs = new HybridTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_VOLUME)) {
qs = new VolumeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_REBOOT)) {
qs = new RebootTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HOLOBAM)) {
qs = new HolobamTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_NETWORKMODE)) {
qs = new MobileNetworkTypeTile(mContext, inflater, mContainerView, this, mHandler);
}
if (qs != null) {
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
// Load the dynamic tiles
// These toggles must be the last ones added to the view, as they will show
// only when they are needed
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_ALARM, 1) == 1) {
QuickSettingsTile qs = new AlarmTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_BUGREPORT, 1) == 1) {
QuickSettingsTile qs = new BugReportTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_WIFI, 1) == 1) {
QuickSettingsTile qs = new WiFiDisplayTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
mIMETile = new InputMethodTile(mContext, inflater, mContainerView, this);
mIMETile.setupQuickSettingsTile();
mQuickSettingsTiles.add(mIMETile);
if (deviceSupportsUsbTether(mContext) && Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_USBTETHER, 1) == 1) {
QuickSettingsTile qs = new UsbTetherTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
| void loadTiles() {
// Reset reference tiles
mIMETile = null;
// Filter items not compatible with device
boolean bluetoothSupported = deviceSupportsBluetooth();
boolean telephonySupported = deviceSupportsTelephony(mContext);
if (!bluetoothSupported) {
TILES_DEFAULT.remove(TILE_BLUETOOTH);
}
if (!telephonySupported) {
TILES_DEFAULT.remove(TILE_WIFIAP);
TILES_DEFAULT.remove(TILE_MOBILEDATA);
TILES_DEFAULT.remove(TILE_NETWORKMODE);
}
// Read the stored list of tiles
ContentResolver resolver = mContext.getContentResolver();
LayoutInflater inflater = LayoutInflater.from(mContext);
String tiles = Settings.System.getString(resolver, Settings.System.QUICK_SETTINGS);
if (tiles == null) {
Log.i(TAG, "Default tiles being loaded");
tiles = TextUtils.join(TILE_DELIMITER, TILES_DEFAULT);
}
Log.i(TAG, "Tiles list: " + tiles);
// Split out the tile names and add to the list
for (String tile : tiles.split("\\|")) {
QuickSettingsTile qs = null;
if (tile.equals(TILE_USER)) {
qs = new UserTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BATTERY)) {
qs = new BatteryTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SETTINGS)) {
qs = new PreferencesTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFI)) {
qs = new WiFiTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_GPS)) {
qs = new GPSTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BLUETOOTH) && bluetoothSupported) {
qs = new BluetoothTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_BRIGHTNESS)) {
qs = new BrightnessTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_RINGER)) {
qs = new RingerModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SYNC)) {
qs = new SyncTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_WIFIAP) && telephonySupported) {
qs = new WifiAPTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_SCREENTIMEOUT)) {
qs = new ScreenTimeoutTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_MOBILEDATA) && telephonySupported) {
qs = new MobileNetworkTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_LOCKSCREEN)) {
qs = new ToggleLockscreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_AUTOROTATE)) {
qs = new AutoRotateTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_AIRPLANE)) {
qs = new AirplaneModeTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_TORCH)) {
qs = new TorchTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_SLEEP)) {
qs = new SleepScreenTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_NFC)) {
// User cannot add the NFC tile if the device does not support it
// No need to check again here
qs = new NfcTile(mContext, inflater, mContainerView, this);
} else if (tile.equals(TILE_DESKTOPMODE)) {
qs = new DesktopModeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HYBRID)) {
qs = new HybridTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_VOLUME)) {
qs = new VolumeTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_REBOOT)) {
qs = new RebootTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_HOLOBAM)) {
qs = new HolobamTile(mContext, inflater, mContainerView, this, mHandler);
} else if (tile.equals(TILE_NETWORKMODE) && telephonySupported) {
qs = new MobileNetworkTypeTile(mContext, inflater, mContainerView, this);
}
if (qs != null) {
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
// Load the dynamic tiles
// These toggles must be the last ones added to the view, as they will show
// only when they are needed
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_ALARM, 1) == 1) {
QuickSettingsTile qs = new AlarmTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_BUGREPORT, 1) == 1) {
QuickSettingsTile qs = new BugReportTile(mContext, inflater, mContainerView, this, mHandler);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
if (Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_WIFI, 1) == 1) {
QuickSettingsTile qs = new WiFiDisplayTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
mIMETile = new InputMethodTile(mContext, inflater, mContainerView, this);
mIMETile.setupQuickSettingsTile();
mQuickSettingsTiles.add(mIMETile);
if (deviceSupportsUsbTether(mContext) && Settings.System.getInt(resolver, Settings.System.QS_DYNAMIC_USBTETHER, 1) == 1) {
QuickSettingsTile qs = new UsbTetherTile(mContext, inflater, mContainerView, this);
qs.setupQuickSettingsTile();
mQuickSettingsTiles.add(qs);
}
}
|
diff --git a/src/org/redbus/GeocodingHelper.java b/src/org/redbus/GeocodingHelper.java
index 9ff0596..1f2a76d 100644
--- a/src/org/redbus/GeocodingHelper.java
+++ b/src/org/redbus/GeocodingHelper.java
@@ -1,86 +1,86 @@
/*
* Copyright 2010 Andrew De Quincey - [email protected]
* This file is part of rEdBus.
*
* rEdBus 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.
*
* rEdBus 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 rEdBus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.redbus;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.util.Log;
public class GeocodingHelper {
private static Integer RequestId = new Integer(0);
public static int geocode(Context ctx, String location, GeocodingResponseListener callback)
{
int requestId = RequestId++;
new AsyncGeocodeRequestTask().execute(new GeocodingRequest(requestId, ctx, location, callback));
return requestId;
}
private static class AsyncGeocodeRequestTask extends AsyncTask<GeocodingRequest, Integer, GeocodingRequest> {
protected GeocodingRequest doInBackground(GeocodingRequest... params) {
GeocodingRequest gr = params[0];
gr.addresses = null;
PointTree pt = PointTree.getPointTree(gr.ctx);
try {
Geocoder geocoder = new Geocoder(gr.ctx, Locale.UK);
- gr.addresses = geocoder.getFromLocationName(gr.location, 5, pt.lowerLeftLat, pt.lowerLeftLon, pt.upperRightLat, pt.upperRightLon);
+ gr.addresses = geocoder.getFromLocationName(gr.location, 5, pt.lowerLeftLat / 1E6, pt.lowerLeftLon / 1E6, pt.upperRightLat / 1E6, pt.upperRightLon / 1E6);
} catch (Throwable t) {
Log.e("AsyncHttpRequestTask.doInBackGround", "Throwable", t);
}
return gr;
}
protected void onPostExecute(GeocodingRequest request) {
if ((request.addresses == null) || (request.addresses.size() == 0)) {
request.callback.geocodeResponseError(request.requestId, "Could not find address...");
} else {
request.callback.geocodeResponseSucccess(request.requestId, request.addresses);
}
}
}
private static class GeocodingRequest {
public GeocodingRequest(int requestId, Context ctx, String location, GeocodingResponseListener callback)
{
this.requestId = requestId;
this.ctx = ctx;
this.location = location;
this.callback = callback;
}
public int requestId;
public Context ctx;
public String location;
public GeocodingResponseListener callback;
public List<Address> addresses = null;
}
}
| true | true | protected GeocodingRequest doInBackground(GeocodingRequest... params) {
GeocodingRequest gr = params[0];
gr.addresses = null;
PointTree pt = PointTree.getPointTree(gr.ctx);
try {
Geocoder geocoder = new Geocoder(gr.ctx, Locale.UK);
gr.addresses = geocoder.getFromLocationName(gr.location, 5, pt.lowerLeftLat, pt.lowerLeftLon, pt.upperRightLat, pt.upperRightLon);
} catch (Throwable t) {
Log.e("AsyncHttpRequestTask.doInBackGround", "Throwable", t);
}
return gr;
}
| protected GeocodingRequest doInBackground(GeocodingRequest... params) {
GeocodingRequest gr = params[0];
gr.addresses = null;
PointTree pt = PointTree.getPointTree(gr.ctx);
try {
Geocoder geocoder = new Geocoder(gr.ctx, Locale.UK);
gr.addresses = geocoder.getFromLocationName(gr.location, 5, pt.lowerLeftLat / 1E6, pt.lowerLeftLon / 1E6, pt.upperRightLat / 1E6, pt.upperRightLon / 1E6);
} catch (Throwable t) {
Log.e("AsyncHttpRequestTask.doInBackGround", "Throwable", t);
}
return gr;
}
|
diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestRunnable.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestRunnable.java
index db920c5a..0812fa8c 100644
--- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestRunnable.java
+++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestRunnable.java
@@ -1,329 +1,333 @@
/*
* Copyright (C) 2012 - 2012 NHN Corporation
* All rights reserved.
*
* This file is part of The nGrinder software distribution. Refer to
* the file LICENSE which is part of The nGrinder distribution for
* licensing details. The nGrinder distribution is available on the
* Internet at http://nhnopensource.org/ngrinder
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.ngrinder.perftest.service;
import static org.ngrinder.perftest.model.Status.CANCELED;
import static org.ngrinder.perftest.model.Status.DISTRIBUTE_FILES;
import static org.ngrinder.perftest.model.Status.DISTRIBUTE_FILES_FINISHED;
import static org.ngrinder.perftest.model.Status.START_AGENTS;
import static org.ngrinder.perftest.model.Status.START_AGENTS_FINISHED;
import static org.ngrinder.perftest.model.Status.START_CONSOLE;
import static org.ngrinder.perftest.model.Status.START_CONSOLE_FINISHED;
import static org.ngrinder.perftest.model.Status.START_TESTING;
import static org.ngrinder.perftest.model.Status.TESTING;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.grinder.SingleConsole;
import net.grinder.SingleConsole.ConsoleShutdownListener;
import net.grinder.common.GrinderProperties;
import net.grinder.console.model.ConsoleProperties;
import org.ngrinder.agent.model.AgentInfo;
import org.ngrinder.chart.service.MonitorAgentService;
import org.ngrinder.common.constant.NGrinderConstants;
import org.ngrinder.monitor.MonitorConstants;
import org.ngrinder.perftest.model.PerfTest;
import org.ngrinder.perftest.model.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* {@link PerfTest} test running run scheduler.
*
* This class is responsible to execute the performance test which is ready to execute. Mostly this
* class is started from {@link #startTest()} method. This method is scheduled by Spring Task.
*
* @author JunHo Yoon
* @since 3.0
*/
@Component
public class PerfTestRunnable implements NGrinderConstants {
private static final Logger LOG = LoggerFactory.getLogger(PerfTestRunnable.class);
@Autowired
private PerfTestService perfTestService;
@Autowired
private ConsoleManager consoleManager;
@Autowired
private AgentManager agentManager;
@Autowired
private MonitorAgentService monitorDataService;
// wait 30 seconds until agents start the test running.
private static final int WAIT_TEST_START_SECOND = 30000;
/**
* Scheduled method for test execution.
*/
@Scheduled(fixedDelay = PERFTEST_RUN_FREQUENCY_MILLISECONDS)
public void startTest() {
+ //return if there is no available agents.
+ if (agentManager.getAllFreeAgents() == null || agentManager.getAllFreeAgents().size() ==0) {
+ return;
+ }
// Block if the count of testing exceed the limit
if (!perfTestService.canExecuteTestMore()) {
// LOG MORE
List<PerfTest> currentlyRunningTests = perfTestService.getCurrentlyRunningTest();
LOG.debug("current running test is {}. so no tests start to run", currentlyRunningTests.size());
for (PerfTest perfTest : currentlyRunningTests) {
LOG.trace("- " + perfTest);
}
return;
}
// Find out next ready perftest
PerfTest runCandidate = perfTestService.getPerfTestCandiate();
if (runCandidate == null) {
return;
}
// If agent is not enough...
if (runCandidate.getAgentCount() > agentManager.getAllFreeAgents().size()) {
return;
}
// In case of too many trial, cancel running.
if (runCandidate.getTestTrialCount() > PERFTEST_MAXIMUM_TRIAL_COUNT) {
LOG.error("The {} test is canceled because it has too many test execution errors",
runCandidate.getTestName());
runCandidate.setTestErrorCause(Status.READY);
runCandidate.setTestErrorStackTrace("The test is canceled because it has too many test execution errors");
perfTestService.savePerfTest(runCandidate, CANCELED);
return;
}
doTest(runCandidate);
}
/**
* Run given test.
*
* If fails, it marks STOP_ON_ERROR in the given {@link PerfTest} status
*
* @param perfTest
* perftest instance;
*/
public void doTest(PerfTest perfTest) {
SingleConsole singleConsole = null;
try {
singleConsole = startConsole(perfTest);
GrinderProperties grinderProperties = perfTestService.getGrinderProperties(perfTest);
startAgentsOn(perfTest, grinderProperties, singleConsole);
distributeFileOn(perfTest, grinderProperties, singleConsole);
singleConsole.setReportPath(perfTestService.getReportFileDirectory(perfTest.getId()));
runTestOn(perfTest, grinderProperties, singleConsole);
} catch (Exception e) {
// In case of error, mark the occurs error on perftest.
markPerfTestError(perfTest, e);
}
}
/**
* Mark test error on {@link PerfTest} instance
*
* @param perfTest
* {@link PerfTest}
* @param e
* exception occurs.
*/
void markPerfTestError(PerfTest perfTest, Exception e) {
markPerfTestError(perfTest, e.getMessage());
}
/**
* Mark test error on {@link PerfTest} instance
*
* @param perfTest
* {@link PerfTest}
* @param reason
* error reason
*/
void markPerfTestError(PerfTest perfTest, String reason) {
// Leave last status as test error cause
perfTest.setTestErrorCause(perfTest.getStatus());
perfTest.setTestErrorStackTrace(reason);
perfTestService.savePerfTest(perfTest, Status.ABNORMAL_TESTING);
}
/**
* Mark test error on {@link PerfTest} instance
*
* @param perfTest
* {@link PerfTest}
* @param singleConsole
* console in use
* @param e
* exception occurs.
*/
void markAbromalTermination(PerfTest perfTest, String reason) {
// Leave last status as test error cause
perfTest.setTestErrorCause(perfTest.getStatus());
perfTest.setTestErrorStackTrace(reason);
perfTestService.savePerfTest(perfTest, Status.ABNORMAL_TESTING);
}
void runTestOn(final PerfTest perfTest, GrinderProperties grinderProperties,
final SingleConsole singleConsole) {
// start target monitor
Set<AgentInfo> agents = new HashSet<AgentInfo>();
List<String> targetIPList = perfTest.getTargetHostIP();
for (String targetIP : targetIPList) {
AgentInfo targetServer = new AgentInfo();
targetServer.setIp(targetIP);
targetServer.setPort(MonitorConstants.DEFAULT_AGENT_PORT);
agents.add(targetServer);
}
// use perf test id as key for the set of target server.
monitorDataService.addMonitorTarget("PerfTest-" + perfTest.getId(), agents);
// Run test
perfTestService.savePerfTest(perfTest, START_TESTING);
singleConsole.addListener(new ConsoleShutdownListener() {
@Override
public void readyToStop() {
markAbromalTermination(perfTest, "Too low TPS");
}
});
grinderProperties.setProperty(GRINDER_PROP_TEST_ID, "test_" + perfTest.getId());
long startTime = singleConsole.startTest(grinderProperties);
perfTest.setStartTime(new Date(startTime));
perfTestService.savePerfTest(perfTest, TESTING);
}
void distributeFileOn(PerfTest perfTest, GrinderProperties grinderProperties, SingleConsole singleConsole) {
// Distribute files
perfTestService.savePerfTest(perfTest, DISTRIBUTE_FILES);
singleConsole.distributeFiles(perfTestService.prepareDistribution(perfTest));
perfTestService.savePerfTest(perfTest, DISTRIBUTE_FILES_FINISHED);
}
void startAgentsOn(PerfTest perfTest, GrinderProperties grinderProperties, SingleConsole singleConsole) {
perfTestService.savePerfTest(perfTest, START_AGENTS);
agentManager.runAgent(singleConsole, grinderProperties, perfTest.getAgentCount());
singleConsole.waitUntilAgentConnected(perfTest.getAgentCount());
perfTestService.savePerfTest(perfTest, START_AGENTS_FINISHED);
}
SingleConsole startConsole(PerfTest perfTest) {
perfTestService.savePerfTest(perfTest, START_CONSOLE);
// get available consoles.
ConsoleProperties consoleProperty = perfTestService.createConsoleProperties(perfTest);
SingleConsole singleConsole = consoleManager.getAvailableConsole(consoleProperty);
// increase trial count
perfTest.setTestTrialCount(perfTest.getTestTrialCount() + 1);
perfTest.setPort(singleConsole.getConsolePort());
singleConsole.start();
perfTestService.savePerfTest(perfTest, START_CONSOLE_FINISHED);
return singleConsole;
}
/**
* Scheduled method for test finish.
*/
@Scheduled(fixedDelay = PERFTEST_RUN_FREQUENCY_MILLISECONDS)
public void finishTest() {
List<PerfTest> abnoramlTestingPerfTest = perfTestService.getAbnoramlTestingPerfTest();
for (PerfTest each : abnoramlTestingPerfTest) {
SingleConsole consoleUsingPort = consoleManager.getConsoleUsingPort(each.getPort());
doTerminate(each, consoleUsingPort);
}
List<PerfTest> finishCandiate = perfTestService.getTestingPerfTest();
for (PerfTest each : finishCandiate) {
SingleConsole consoleUsingPort = consoleManager.getConsoleUsingPort(each.getPort());
doFinish(each, consoleUsingPort);
}
}
/**
* Terminate test.
*
* @param perfTest
* {@link PerfTest} to be finished
* @param singleConsoleInUse
* {@link SingleConsole} which is being using for {@link PerfTest}
*/
public void doTerminate(PerfTest perfTest, SingleConsole singleConsoleInUse) {
markPerfTestError(perfTest, perfTest.getTestErrorStackTrace());
monitorDataService.removeMonitorAgents("PerfTest-" + perfTest.getId());
if (singleConsoleInUse != null) {
// need to finish test as error
consoleManager.returnBackConsole(singleConsoleInUse);
return;
}
}
/**
* Finish test.
*
* @param perfTest
* {@link PerfTest} to be finished
* @param singleConsoleInUse
* {@link SingleConsole} which is being using for {@link PerfTest}
*/
public void doFinish(PerfTest perfTest, SingleConsole singleConsoleInUse) {
// FIXME... it should found abnormal test status..
if (singleConsoleInUse == null) {
LOG.error("There is no console found for test:{}", perfTest);
// need to finish test as error
perfTestService.savePerfTest(perfTest, Status.STOP_ON_ERROR);
monitorDataService.removeMonitorAgents("PerfTest-" + perfTest.getId());
return;
}
long finishTime = System.currentTimeMillis();
long startLastingTime = finishTime - singleConsoleInUse.getStartTime();
// because It will take some seconds to start testing sometimes , if the
// test is not started
// after some seconds, will set it as finished.
if (singleConsoleInUse.isAllTestFinished() && startLastingTime > WAIT_TEST_START_SECOND) {
// stop target host monitor
monitorDataService.removeMonitorAgents("PerfTest-" + perfTest.getId());
perfTest.setFinishTime(new Date(finishTime));
PerfTest resultTest = perfTestService.updatePerfTestAfterTestFinish(perfTest);
consoleManager.returnBackConsole(singleConsoleInUse);
if (isAbormalFinishing(perfTest)) {
perfTestService.savePerfTest(resultTest, Status.STOP_ON_ERROR);
} else {
perfTestService.savePerfTest(resultTest, Status.FINISHED);
}
}
}
public boolean isAbormalFinishing(PerfTest perfTest) {
if ("D".equals(perfTest.getThreshold())) {
if ((new Date().getTime() - perfTest.getStartTime().getTime()) < perfTest.getDuration()) {
return true;
}
}
return false;
}
}
| true | true | public void startTest() {
// Block if the count of testing exceed the limit
if (!perfTestService.canExecuteTestMore()) {
// LOG MORE
List<PerfTest> currentlyRunningTests = perfTestService.getCurrentlyRunningTest();
LOG.debug("current running test is {}. so no tests start to run", currentlyRunningTests.size());
for (PerfTest perfTest : currentlyRunningTests) {
LOG.trace("- " + perfTest);
}
return;
}
// Find out next ready perftest
PerfTest runCandidate = perfTestService.getPerfTestCandiate();
if (runCandidate == null) {
return;
}
// If agent is not enough...
if (runCandidate.getAgentCount() > agentManager.getAllFreeAgents().size()) {
return;
}
// In case of too many trial, cancel running.
if (runCandidate.getTestTrialCount() > PERFTEST_MAXIMUM_TRIAL_COUNT) {
LOG.error("The {} test is canceled because it has too many test execution errors",
runCandidate.getTestName());
runCandidate.setTestErrorCause(Status.READY);
runCandidate.setTestErrorStackTrace("The test is canceled because it has too many test execution errors");
perfTestService.savePerfTest(runCandidate, CANCELED);
return;
}
doTest(runCandidate);
}
| public void startTest() {
//return if there is no available agents.
if (agentManager.getAllFreeAgents() == null || agentManager.getAllFreeAgents().size() ==0) {
return;
}
// Block if the count of testing exceed the limit
if (!perfTestService.canExecuteTestMore()) {
// LOG MORE
List<PerfTest> currentlyRunningTests = perfTestService.getCurrentlyRunningTest();
LOG.debug("current running test is {}. so no tests start to run", currentlyRunningTests.size());
for (PerfTest perfTest : currentlyRunningTests) {
LOG.trace("- " + perfTest);
}
return;
}
// Find out next ready perftest
PerfTest runCandidate = perfTestService.getPerfTestCandiate();
if (runCandidate == null) {
return;
}
// If agent is not enough...
if (runCandidate.getAgentCount() > agentManager.getAllFreeAgents().size()) {
return;
}
// In case of too many trial, cancel running.
if (runCandidate.getTestTrialCount() > PERFTEST_MAXIMUM_TRIAL_COUNT) {
LOG.error("The {} test is canceled because it has too many test execution errors",
runCandidate.getTestName());
runCandidate.setTestErrorCause(Status.READY);
runCandidate.setTestErrorStackTrace("The test is canceled because it has too many test execution errors");
perfTestService.savePerfTest(runCandidate, CANCELED);
return;
}
doTest(runCandidate);
}
|
diff --git a/android/ibrdtn/src/de/tubs/ibr/dtn/service/DaemonService.java b/android/ibrdtn/src/de/tubs/ibr/dtn/service/DaemonService.java
index 2d13714f..ea7fa760 100644
--- a/android/ibrdtn/src/de/tubs/ibr/dtn/service/DaemonService.java
+++ b/android/ibrdtn/src/de/tubs/ibr/dtn/service/DaemonService.java
@@ -1,447 +1,447 @@
/*
* DaemonService.java
*
* Copyright (C) 2013 IBR, TU Braunschweig
*
* Written-by: Dominik Schürmann <[email protected]>
* Johannes Morgenroth <[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 de.tubs.ibr.dtn.service;
import java.util.LinkedList;
import java.util.List;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import de.tubs.ibr.dtn.DTNService;
import de.tubs.ibr.dtn.DaemonState;
import de.tubs.ibr.dtn.R;
import de.tubs.ibr.dtn.api.DTNSession;
import de.tubs.ibr.dtn.api.Registration;
import de.tubs.ibr.dtn.api.SingletonEndpoint;
import de.tubs.ibr.dtn.daemon.Preferences;
import de.tubs.ibr.dtn.p2p.P2PManager;
import de.tubs.ibr.dtn.swig.StringVec;
public class DaemonService extends Service {
public static final String ACTION_STARTUP = "de.tubs.ibr.dtn.action.STARTUP";
public static final String ACTION_SHUTDOWN = "de.tubs.ibr.dtn.action.SHUTDOWN";
public static final String ACTION_CLOUD_UPLINK = "de.tubs.ibr.dtn.action.CLOUD_UPLINK";
public static final String UPDATE_NOTIFICATION = "de.tubs.ibr.dtn.action.UPDATE_NOTIFICATION";
// CloudUplink Parameter
private static final SingletonEndpoint __CLOUD_EID__ = new SingletonEndpoint(
"dtn://cloud.dtnbone.dtn");
private static final String __CLOUD_PROTOCOL__ = "tcp";
private static final String __CLOUD_ADDRESS__ = "134.169.35.130"; // quorra.ibr.cs.tu-bs.de";
private static final String __CLOUD_PORT__ = "4559";
private final String TAG = "DaemonService";
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
// session manager for all active sessions
private SessionManager mSessionManager = null;
// the P2P manager used for wifi direct control
private P2PManager _p2p_manager = null;
private DaemonProcess mDaemonProcess = null;
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final DTNService.Stub mBinder = new DTNService.Stub() {
public DaemonState getState() throws RemoteException {
return DaemonService.this.mDaemonProcess.getState();
}
public boolean isRunning() throws RemoteException {
return DaemonService.this.mDaemonProcess.getState().equals(DaemonState.ONLINE);
}
public List<String> getNeighbors() throws RemoteException {
if (mDaemonProcess == null)
return new LinkedList<String>();
List<String> ret = new LinkedList<String>();
StringVec neighbors = mDaemonProcess.getNative().getNeighbors();
for (int i = 0; i < neighbors.size(); i++) {
ret.add(neighbors.get(i));
}
return ret;
}
public void clearStorage() throws RemoteException {
DaemonStorageUtils.clearStorage();
}
public DTNSession getSession(String packageName) throws RemoteException {
ClientSession cs = mSessionManager.getSession(packageName);
if (cs == null)
return null;
return cs.getBinder();
}
@Override
public String[] getVersion() throws RemoteException {
StringVec version = mDaemonProcess.getNative().getVersion();
return new String[] { version.get(0), version.get(1) };
}
};
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
Intent intent = (Intent) msg.obj;
onHandleIntent(intent);
}
}
/**
* Incoming Intents are handled here
*
* @param intent
*/
public void onHandleIntent(Intent intent) {
String action = intent.getAction();
if (ACTION_STARTUP.equals(action)) {
// create initial notification
Notification n = buildNotification(R.drawable.ic_notification, getResources()
.getString(R.string.notify_pending));
// turn this to a foreground service (kill-proof)
startForeground(1, n);
mDaemonProcess.start();
} else if (ACTION_SHUTDOWN.equals(action)) {
// stop main loop
mDaemonProcess.stop();
// stop foreground service
stopForeground(true);
} else if (ACTION_CLOUD_UPLINK.equals(action)) {
if (DaemonState.ONLINE.equals(mDaemonProcess.getState())) {
setCloudUplink(intent.getBooleanExtra("enabled", false));
}
} else if (UPDATE_NOTIFICATION.equals(action)) {
// update state text in the notification
updateNotification();
} else if (de.tubs.ibr.dtn.Intent.REGISTER.equals(action)) {
final Registration reg = (Registration) intent.getParcelableExtra("registration");
final PendingIntent pi = (PendingIntent) intent.getParcelableExtra("app");
mSessionManager.register(pi.getTargetPackage(), reg);
} else if (de.tubs.ibr.dtn.Intent.UNREGISTER.equals(action)) {
final PendingIntent pi = (PendingIntent) intent.getParcelableExtra("app");
mSessionManager.unregister(pi.getTargetPackage());
}
}
public DaemonService() {
super();
}
@Override
public void onCreate() {
super.onCreate();
// create daemon main thread
mDaemonProcess = new DaemonProcess(this, mProcessHandler);
/*
* incoming Intents will be processed by ServiceHandler and queued in
* HandlerThread
*/
HandlerThread thread = new HandlerThread("DaemonService_IntentThread");
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
// create a session manager
mSessionManager = new SessionManager(this);
// create P2P Manager
// _p2p_manager = new P2PManager(this, _p2p_listener, "my address");
if (Log.isLoggable(TAG, Log.DEBUG))
Log.d(TAG, "DaemonService created");
// restore sessions
mSessionManager.restoreRegistrations();
}
/**
* Called on stopSelf() or stopService()
*/
@Override
public void onDestroy() {
// stop looper that handles incoming intents
mServiceLooper.quit();
// close all sessions
mSessionManager.saveRegistrations();
// remove notification
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(1);
// dereference P2P Manager
_p2p_manager = null;
// call super method
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
/*
* If no explicit intent is given start as ACTION_STARTUP. When this
* service crashes, Android restarts it without an Intent. Thus
* ACTION_STARTUP is executed!
*/
if (intent == null || intent.getAction() == null) {
Log.d(TAG, "intent == null or intent.getAction() == null -> default to ACTION_STARTUP");
intent = new Intent(ACTION_STARTUP);
}
String action = intent.getAction();
if (Log.isLoggable(TAG, Log.DEBUG))
Log.d(TAG, "Received start id " + startId + ": " + intent);
if (Log.isLoggable(TAG, Log.DEBUG))
Log.d(TAG, "Intent Action: " + action);
if (ACTION_STARTUP.equals(action)) {
// handle startup intent directly without queuing
if (mDaemonProcess.getState().equals(DaemonState.OFFLINE))
{
onHandleIntent(intent);
}
} else {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
msg.obj = intent;
mServiceHandler.sendMessage(msg);
}
return START_STICKY;
}
private DaemonProcessHandler mProcessHandler = new DaemonProcessHandler() {
@Override
public void onStateChanged(DaemonState state) {
Log.d(TAG, "mDaemonStateReceiver: DaemonState: " + state);
switch (state) {
case ERROR:
break;
case OFFLINE:
// close all sessions
mSessionManager.terminate();
// TODO: disable P2P manager
// _p2p_manager.destroy();
// stop service
stopSelf();
break;
case ONLINE:
// update notification text
updateNotification();
// restore registrations
mSessionManager.initialize();
// request notification update
requestNotificationUpdate();
// TODO: enable P2P manager
// _p2p_manager.initialize();
// enable cloud uplink if enabled
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(DaemonService.this);
- setCloudUplink(prefs.getBoolean("enabledSwitch", false));
+ setCloudUplink(prefs.getBoolean("cloud_uplink", false));
break;
case SUSPENDED:
break;
case UNKOWN:
break;
default:
break;
}
// broadcast state change
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(de.tubs.ibr.dtn.Intent.STATE);
broadcastIntent.putExtra("state", state.name());
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
sendBroadcast(broadcastIntent);
}
@Override
public void onNeighborhoodChanged() {
requestNotificationUpdate();
}
@Override
public void onEvent(Intent intent) {
sendBroadcast(intent);
}
};
private void setCloudUplink(Boolean mode) {
if (mode) {
mDaemonProcess.getNative().addConnection(__CLOUD_EID__.toString(),
__CLOUD_PROTOCOL__, __CLOUD_ADDRESS__, __CLOUD_PORT__);
} else {
mDaemonProcess.getNative().removeConnection(__CLOUD_EID__.toString(),
__CLOUD_PROTOCOL__, __CLOUD_ADDRESS__, __CLOUD_PORT__);
}
}
private void requestNotificationUpdate() {
// request notification update
final Intent neighborIntent = new Intent(DaemonService.this, DaemonService.class);
neighborIntent.setAction(UPDATE_NOTIFICATION);
startService(neighborIntent);
}
private void updateNotification() {
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String stateText = "";
// check state and display daemon state instead of neighbors
switch (this.mDaemonProcess.getState()) {
case PENDING:
stateText = getResources().getString(R.string.notify_pending) + " ...";
break;
case ERROR:
stateText = getResources().getString(R.string.notify_error);
break;
case OFFLINE:
stateText = getResources().getString(R.string.notify_offline);
break;
case ONLINE:
// if the daemon is online, query for the number of neighbors and display it
StringVec neighbors = mDaemonProcess.getNative().getNeighbors();
if (neighbors.size() > 0) {
stateText = getResources().getString(R.string.notify_neighbors) + ": " + neighbors.size();
} else {
stateText = getResources().getString(R.string.notify_no_neighbors);
}
break;
case SUSPENDED:
stateText = getResources().getString(R.string.notify_suspended);
break;
case UNKOWN:
break;
default:
break;
}
nm.notify(1, buildNotification(R.drawable.ic_notification, stateText));
}
// private P2PManager.P2PNeighborListener _p2p_listener = new
// P2PManager.P2PNeighborListener() {
//
// public void onNeighborDisconnected(String name, String iface)
// {
// Log.d(TAG, "P2P neighbor has been disconnected");
// // TODO: put here the right code to control the dtnd
// }
//
// public void onNeighborDisappear(String name)
// {
// Log.d(TAG, "P2P neighbor has been disappeared");
// // TODO: put here the right code to control the dtnd
// }
//
// public void onNeighborDetected(String name)
// {
// Log.d(TAG, "P2P neighbor has been detected");
// // TODO: put here the right code to control the dtnd
// }
//
// public void onNeighborConnected(String name, String iface)
// {
// Log.d(TAG, "P2P neighbor has been connected");
// // TODO: put here the right code to control the dtnd
// }
// };
private Notification buildNotification(int icon, String text) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle(getResources().getString(R.string.service_name));
builder.setContentText(text);
builder.setSmallIcon(icon);
builder.setOngoing(true);
builder.setOnlyAlertOnce(true);
builder.setWhen(0);
Intent notifyIntent = new Intent(this, Preferences.class);
notifyIntent.setAction("android.intent.action.MAIN");
notifyIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notifyIntent, 0);
builder.setContentIntent(contentIntent);
return builder.getNotification();
}
}
| true | true | public void onStateChanged(DaemonState state) {
Log.d(TAG, "mDaemonStateReceiver: DaemonState: " + state);
switch (state) {
case ERROR:
break;
case OFFLINE:
// close all sessions
mSessionManager.terminate();
// TODO: disable P2P manager
// _p2p_manager.destroy();
// stop service
stopSelf();
break;
case ONLINE:
// update notification text
updateNotification();
// restore registrations
mSessionManager.initialize();
// request notification update
requestNotificationUpdate();
// TODO: enable P2P manager
// _p2p_manager.initialize();
// enable cloud uplink if enabled
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(DaemonService.this);
setCloudUplink(prefs.getBoolean("enabledSwitch", false));
break;
case SUSPENDED:
break;
case UNKOWN:
break;
default:
break;
}
// broadcast state change
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(de.tubs.ibr.dtn.Intent.STATE);
broadcastIntent.putExtra("state", state.name());
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
sendBroadcast(broadcastIntent);
}
| public void onStateChanged(DaemonState state) {
Log.d(TAG, "mDaemonStateReceiver: DaemonState: " + state);
switch (state) {
case ERROR:
break;
case OFFLINE:
// close all sessions
mSessionManager.terminate();
// TODO: disable P2P manager
// _p2p_manager.destroy();
// stop service
stopSelf();
break;
case ONLINE:
// update notification text
updateNotification();
// restore registrations
mSessionManager.initialize();
// request notification update
requestNotificationUpdate();
// TODO: enable P2P manager
// _p2p_manager.initialize();
// enable cloud uplink if enabled
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(DaemonService.this);
setCloudUplink(prefs.getBoolean("cloud_uplink", false));
break;
case SUSPENDED:
break;
case UNKOWN:
break;
default:
break;
}
// broadcast state change
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(de.tubs.ibr.dtn.Intent.STATE);
broadcastIntent.putExtra("state", state.name());
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
sendBroadcast(broadcastIntent);
}
|
diff --git a/src/main/groovy/org/elasticsearch/river/csv/CSVRiver.java b/src/main/groovy/org/elasticsearch/river/csv/CSVRiver.java
index 1e2651e..cceeeb2 100644
--- a/src/main/groovy/org/elasticsearch/river/csv/CSVRiver.java
+++ b/src/main/groovy/org/elasticsearch/river/csv/CSVRiver.java
@@ -1,155 +1,155 @@
package org.elasticsearch.river.csv;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.river.AbstractRiverComponent;
import org.elasticsearch.river.River;
import org.elasticsearch.river.RiverName;
import org.elasticsearch.river.RiverSettings;
import org.elasticsearch.threadpool.ThreadPool;
public class CSVRiver extends AbstractRiverComponent implements River, FileProcessorListener {
private final ThreadPool threadPool;
private final Client client;
private final OpenCSVFileProcessorFactory factory = new OpenCSVFileProcessorFactory();
private Thread thread;
private volatile BulkRequestBuilder currentRequest;
private volatile boolean closed = false;
private Configuration config;
@SuppressWarnings({"unchecked"})
@Inject
public CSVRiver(RiverName riverName, RiverSettings settings, Client client, ThreadPool threadPool) {
super(riverName, settings);
this.client = client;
this.threadPool = threadPool;
config = new Configuration(settings, riverName.name());
}
@Override
public void start() {
logger.info("starting csv stream");
currentRequest = client.prepareBulk();
thread = EsExecutors.daemonThreadFactory(settings.globalSettings(), "CSV processor").newThread(new CSVConnector(this, config, factory));
thread.start();
}
@Override
public void close() {
logger.info("closing csv stream river");
this.closed = true;
thread.interrupt();
}
public void delay() {
if (config.getPoll().millis() > 0L) {
logger.info("next run waiting for {}", config.getPoll());
try {
Thread.sleep(config.getPoll().millis());
} catch (InterruptedException e) {
logger.error("Error during waiting.", e, (Object) null);
}
}
}
public void processBulkIfNeeded(boolean force) {
- if (currentRequest.numberOfActions() >= config.getBulkSize() || force) {
+ if (currentRequest.numberOfActions() >= config.getBulkSize() || (currentRequest.numberOfActions() > 0 && force)) {
// execute the bulk operation
int currentOnGoingBulks = config.getOnGoingBulks().incrementAndGet();
if (currentOnGoingBulks > config.getBulkThreshold()) {
config.getOnGoingBulks().decrementAndGet();
logger.warn("ongoing bulk, {} crossed threshold {}, waiting", config.getOnGoingBulks(), config.getBulkThreshold());
try {
synchronized (this) {
wait();
}
} catch (InterruptedException e) {
logger.error("Error during wait", e);
}
}
try {
currentRequest.execute(new ActionListener<BulkResponse>() {
@Override
public void onResponse(BulkResponse bulkResponse) {
config.getOnGoingBulks().decrementAndGet();
notifyCSVRiver();
}
@Override
public void onFailure(Throwable e) {
config.getOnGoingBulks().decrementAndGet();
notifyCSVRiver();
logger.error("failed to execute bulk", e);
}
});
} catch (Exception e) {
config.getOnGoingBulks().decrementAndGet();
notifyCSVRiver();
logger.warn("failed to process bulk", e);
}
currentRequest = client.prepareBulk();
}
}
public void log(String message, Object... args) {
logger.info(message, args);
}
private void notifyCSVRiver() {
synchronized (CSVRiver.this) {
CSVRiver.this.notify();
}
}
@Override
public void onLineProcessed(IndexRequest request) {
logger.info("Adding request {}", request);
currentRequest.add(request);
processBulkIfNeeded(false);
}
@Override
public void onFileProcessed() {
processBulkIfNeeded(false);
}
@Override
public void onAllFileProcessed() {
processBulkIfNeeded(true);
delay();
}
@Override
public void onError(Exception e) {
logger.error(e.getMessage(), e, (Object) null);
closed = true;
}
@Override
public boolean listening() {
return !closed;
}
}
| true | true | public void processBulkIfNeeded(boolean force) {
if (currentRequest.numberOfActions() >= config.getBulkSize() || force) {
// execute the bulk operation
int currentOnGoingBulks = config.getOnGoingBulks().incrementAndGet();
if (currentOnGoingBulks > config.getBulkThreshold()) {
config.getOnGoingBulks().decrementAndGet();
logger.warn("ongoing bulk, {} crossed threshold {}, waiting", config.getOnGoingBulks(), config.getBulkThreshold());
try {
synchronized (this) {
wait();
}
} catch (InterruptedException e) {
logger.error("Error during wait", e);
}
}
try {
currentRequest.execute(new ActionListener<BulkResponse>() {
@Override
public void onResponse(BulkResponse bulkResponse) {
config.getOnGoingBulks().decrementAndGet();
notifyCSVRiver();
}
@Override
public void onFailure(Throwable e) {
config.getOnGoingBulks().decrementAndGet();
notifyCSVRiver();
logger.error("failed to execute bulk", e);
}
});
} catch (Exception e) {
config.getOnGoingBulks().decrementAndGet();
notifyCSVRiver();
logger.warn("failed to process bulk", e);
}
currentRequest = client.prepareBulk();
}
}
| public void processBulkIfNeeded(boolean force) {
if (currentRequest.numberOfActions() >= config.getBulkSize() || (currentRequest.numberOfActions() > 0 && force)) {
// execute the bulk operation
int currentOnGoingBulks = config.getOnGoingBulks().incrementAndGet();
if (currentOnGoingBulks > config.getBulkThreshold()) {
config.getOnGoingBulks().decrementAndGet();
logger.warn("ongoing bulk, {} crossed threshold {}, waiting", config.getOnGoingBulks(), config.getBulkThreshold());
try {
synchronized (this) {
wait();
}
} catch (InterruptedException e) {
logger.error("Error during wait", e);
}
}
try {
currentRequest.execute(new ActionListener<BulkResponse>() {
@Override
public void onResponse(BulkResponse bulkResponse) {
config.getOnGoingBulks().decrementAndGet();
notifyCSVRiver();
}
@Override
public void onFailure(Throwable e) {
config.getOnGoingBulks().decrementAndGet();
notifyCSVRiver();
logger.error("failed to execute bulk", e);
}
});
} catch (Exception e) {
config.getOnGoingBulks().decrementAndGet();
notifyCSVRiver();
logger.warn("failed to process bulk", e);
}
currentRequest = client.prepareBulk();
}
}
|
diff --git a/src/eu/livotov/labs/android/robotools/api/RTApiClient.java b/src/eu/livotov/labs/android/robotools/api/RTApiClient.java
index 70dd8f7..733428a 100644
--- a/src/eu/livotov/labs/android/robotools/api/RTApiClient.java
+++ b/src/eu/livotov/labs/android/robotools/api/RTApiClient.java
@@ -1,260 +1,265 @@
package eu.livotov.labs.android.robotools.api;
import android.util.Log;
import eu.livotov.labs.android.robotools.net.RTHTTPClient;
import eu.livotov.labs.android.robotools.net.RTHTTPError;
import eu.livotov.labs.android.robotools.net.RTPostParameter;
import org.apache.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
/**
* (c) Livotov Labs Ltd. 2012
* Date: 29.01.13
*/
public abstract class RTApiClient extends RTHTTPClient
{
private String transportEncoding = "utf-8";
private boolean debugMode = false;
protected RTApiClient()
{
super(true);
}
public boolean isDebugMode()
{
return debugMode;
}
public void setDebugMode(final boolean debugMode)
{
this.debugMode = debugMode;
}
public abstract String getEndpointUrlFor(RTApiCommand cmd);
public RTApiCommandResult execute(final RTApiCommand cmd)
{
final String url = String.format("%s%s", getEndpointUrlFor(cmd), secureSlash(cmd.buildRequestUri()));
final List<RTPostParameter> parameters = new ArrayList<RTPostParameter>();
final List<RTPostParameter> headers = new ArrayList<RTPostParameter>();
try
{
RTApiRequestType rtType = cmd.getRequestType();
cmd.buildRequestParameters(parameters);
onCommandPreExecute(cmd, url, parameters, headers);
boolean hasAttachments = false;
if (rtType == RTApiRequestType.POST)
{
for (RTPostParameter parameter : parameters)
{
if (parameter.getAttachment() != null && parameter.getAttachment().exists() && parameter.getAttachment().length() > 0)
{
hasAttachments = true;
break;
}
}
}
if (debugMode)
{
Log.d(RTApiClient.class.getSimpleName(), "Calling API method via " + rtType.name() + " : " + url);
Log.d(RTApiClient.class.getSimpleName(), "Content-type: " + cmd.getContentType());
if (headers.size() > 0)
{
Log.d(RTApiClient.class.getSimpleName(), "With headers: ");
for (RTPostParameter p : headers)
{
Log.d(RTApiClient.class.getSimpleName(), String.format(" %s = %s", p.getName(), p.getValue()));
}
} else
{
Log.d(RTApiClient.class.getSimpleName(), "Without headers");
}
if (parameters.size() > 0)
{
Log.d(RTApiClient.class.getSimpleName(), "With parameters: ");
for (RTPostParameter p : parameters)
{
if (rtType == RTApiRequestType.POST)
{
Log.d(RTApiClient.class.getSimpleName(), String.format("%s: %s = %s", rtType.name(), p.getName(), p.getAttachment() != null ? p.getAttachment().getAbsolutePath() : p.getValue()));
} else
{
Log.d(RTApiClient.class.getSimpleName(), String.format("%s: %s = %s", rtType.name(), p.getName(), p.getValue()));
}
}
} else
{
Log.d(RTApiClient.class.getSimpleName(), "Without parameters");
}
}
HttpResponse response = null;
switch (rtType)
{
case POST:
if (!hasAttachments)
{
response = processPost(cmd, url, parameters, headers);
} else
{
response = submitForm(url, headers, parameters);
}
break;
case GET:
response = executeGetRequest(url, headers, parameters);
break;
case PUT:
response = processPut(cmd, url, headers, parameters);
break;
case DELETE:
response = processDelete(cmd, url, headers, parameters);
break;
default:
response = submitForm(url, headers, parameters);
break;
}
onCommandHttpRequestDone(cmd, url, parameters, response);
if (debugMode)
{
Log.d(RTApiClient.class.getSimpleName(), "<< Server returned status code: " + response.getStatusLine().getStatusCode());
Log.d(RTApiClient.class.getSimpleName(), "<< " + response.getStatusLine().getReasonPhrase());
}
final String data = loadHttpResponseToString(response, transportEncoding);
onCommandResponseDataLoaded(cmd, url, parameters, response, data);
if (debugMode)
{
Log.d(RTApiClient.class.getSimpleName(), "\n\n<< " + url);
Log.d(RTApiClient.class.getSimpleName(), data);
Log.d(RTApiClient.class.getSimpleName(), "\n\n");
}
RTApiCommandResult result = cmd.parseServerResponseData(data);
onCommandPostExecure(cmd, url, parameters, response, result);
return result;
} catch (RTHTTPError httpError)
{
- onCommandPostExecureWithError(cmd, url, parameters, httpError.getStatusCode(), httpError.getStatusText(), httpError.getResponseBody());
+ onCommandPostExecureWithError(cmd, url, parameters, httpError.getStatusCode(), httpError.getStatusText(),
+ httpError.getResponseBody());
+ if (debugMode)
+ {
+ Log.d(RTApiClient.class.getSimpleName(), "<< " + httpError.getResponseBody());
+ }
RTApiCommandResult result = cmd.parseServerErrorResponseData(httpError);
return result;
} catch (RTApiError baw)
{
throw baw;
} catch (Throwable otherError)
{
throw new RTApiError(otherError);
}
}
private HttpResponse processPost(final RTApiCommand cmd, final String url, final List<RTPostParameter> parameters, final List<RTPostParameter> headers)
{
StringBuffer body = new StringBuffer();
cmd.buildRequestBody(body);
if (debugMode)
{
if (body.length() > 0)
{
Log.d(RTApiClient.class.getSimpleName(), "POST Body:\n" + body.toString());
}
}
if (body.length() > 0)
{
return executePostRequest(url, cmd.getContentType(), "utf-8", body.toString(), headers.toArray(new RTPostParameter[headers.size()]));
} else
{
return submitForm(url, headers, parameters);
}
}
private HttpResponse processPut(final RTApiCommand cmd, final String url, final List<RTPostParameter> headers, final List<RTPostParameter> parameters)
{
StringBuffer body = new StringBuffer();
cmd.buildRequestBody(body);
if (debugMode)
{
if (body.length() > 0)
{
Log.d(RTApiClient.class.getSimpleName(), "PUT Body:\n" + body.toString());
}
}
if (body.length() > 0)
{
return executePutRequest(url, cmd.getContentType(), "utf-8", body.toString(), headers, parameters);
} else
{
return executePutRequest(url, headers, parameters);
}
}
private HttpResponse processDelete(final RTApiCommand cmd, final String url, final List<RTPostParameter> headers, final List<RTPostParameter> parameters)
{
StringBuffer body = new StringBuffer();
cmd.buildRequestBody(body);
if (debugMode)
{
if (body.length() > 0)
{
Log.d(RTApiClient.class.getSimpleName(), "DELETE Body:\n" + body.toString());
}
}
if (body.length() > 0)
{
return executeDeleteRequest(url, cmd.getContentType(), "utf-8", body.toString(), headers, parameters);
} else
{
return executeDeleteRequest(url, headers, parameters);
}
}
protected abstract void onCommandHttpRequestDone(RTApiCommand cmd, String url, List<RTPostParameter> parameters, HttpResponse response);
protected abstract void onCommandResponseDataLoaded(RTApiCommand cmd, String url, List<RTPostParameter> parameters, HttpResponse response, String data);
protected abstract void onCommandPostExecure(RTApiCommand cmd, String url, List<RTPostParameter> parameters, HttpResponse response, RTApiCommandResult result);
protected abstract void onCommandPreExecute(RTApiCommand cmd, String finalUrl, List<RTPostParameter> parameters, List<RTPostParameter> headers);
protected abstract void onCommandPostExecureWithError(final RTApiCommand cmd, final String url, final List<RTPostParameter> parameters, final int statusCode, final String statusText, final String responseBody);
public void resetCookies()
{
getConfiguration().resetCookies();
}
protected String secureSlash(String path)
{
if (path != null && path.length() > 1 && !path.startsWith("/") && !path.toLowerCase().startsWith("http"))
{
return "/" + path;
}
return path;
}
}
| true | true | public RTApiCommandResult execute(final RTApiCommand cmd)
{
final String url = String.format("%s%s", getEndpointUrlFor(cmd), secureSlash(cmd.buildRequestUri()));
final List<RTPostParameter> parameters = new ArrayList<RTPostParameter>();
final List<RTPostParameter> headers = new ArrayList<RTPostParameter>();
try
{
RTApiRequestType rtType = cmd.getRequestType();
cmd.buildRequestParameters(parameters);
onCommandPreExecute(cmd, url, parameters, headers);
boolean hasAttachments = false;
if (rtType == RTApiRequestType.POST)
{
for (RTPostParameter parameter : parameters)
{
if (parameter.getAttachment() != null && parameter.getAttachment().exists() && parameter.getAttachment().length() > 0)
{
hasAttachments = true;
break;
}
}
}
if (debugMode)
{
Log.d(RTApiClient.class.getSimpleName(), "Calling API method via " + rtType.name() + " : " + url);
Log.d(RTApiClient.class.getSimpleName(), "Content-type: " + cmd.getContentType());
if (headers.size() > 0)
{
Log.d(RTApiClient.class.getSimpleName(), "With headers: ");
for (RTPostParameter p : headers)
{
Log.d(RTApiClient.class.getSimpleName(), String.format(" %s = %s", p.getName(), p.getValue()));
}
} else
{
Log.d(RTApiClient.class.getSimpleName(), "Without headers");
}
if (parameters.size() > 0)
{
Log.d(RTApiClient.class.getSimpleName(), "With parameters: ");
for (RTPostParameter p : parameters)
{
if (rtType == RTApiRequestType.POST)
{
Log.d(RTApiClient.class.getSimpleName(), String.format("%s: %s = %s", rtType.name(), p.getName(), p.getAttachment() != null ? p.getAttachment().getAbsolutePath() : p.getValue()));
} else
{
Log.d(RTApiClient.class.getSimpleName(), String.format("%s: %s = %s", rtType.name(), p.getName(), p.getValue()));
}
}
} else
{
Log.d(RTApiClient.class.getSimpleName(), "Without parameters");
}
}
HttpResponse response = null;
switch (rtType)
{
case POST:
if (!hasAttachments)
{
response = processPost(cmd, url, parameters, headers);
} else
{
response = submitForm(url, headers, parameters);
}
break;
case GET:
response = executeGetRequest(url, headers, parameters);
break;
case PUT:
response = processPut(cmd, url, headers, parameters);
break;
case DELETE:
response = processDelete(cmd, url, headers, parameters);
break;
default:
response = submitForm(url, headers, parameters);
break;
}
onCommandHttpRequestDone(cmd, url, parameters, response);
if (debugMode)
{
Log.d(RTApiClient.class.getSimpleName(), "<< Server returned status code: " + response.getStatusLine().getStatusCode());
Log.d(RTApiClient.class.getSimpleName(), "<< " + response.getStatusLine().getReasonPhrase());
}
final String data = loadHttpResponseToString(response, transportEncoding);
onCommandResponseDataLoaded(cmd, url, parameters, response, data);
if (debugMode)
{
Log.d(RTApiClient.class.getSimpleName(), "\n\n<< " + url);
Log.d(RTApiClient.class.getSimpleName(), data);
Log.d(RTApiClient.class.getSimpleName(), "\n\n");
}
RTApiCommandResult result = cmd.parseServerResponseData(data);
onCommandPostExecure(cmd, url, parameters, response, result);
return result;
} catch (RTHTTPError httpError)
{
onCommandPostExecureWithError(cmd, url, parameters, httpError.getStatusCode(), httpError.getStatusText(), httpError.getResponseBody());
RTApiCommandResult result = cmd.parseServerErrorResponseData(httpError);
return result;
} catch (RTApiError baw)
{
throw baw;
} catch (Throwable otherError)
{
throw new RTApiError(otherError);
}
}
| public RTApiCommandResult execute(final RTApiCommand cmd)
{
final String url = String.format("%s%s", getEndpointUrlFor(cmd), secureSlash(cmd.buildRequestUri()));
final List<RTPostParameter> parameters = new ArrayList<RTPostParameter>();
final List<RTPostParameter> headers = new ArrayList<RTPostParameter>();
try
{
RTApiRequestType rtType = cmd.getRequestType();
cmd.buildRequestParameters(parameters);
onCommandPreExecute(cmd, url, parameters, headers);
boolean hasAttachments = false;
if (rtType == RTApiRequestType.POST)
{
for (RTPostParameter parameter : parameters)
{
if (parameter.getAttachment() != null && parameter.getAttachment().exists() && parameter.getAttachment().length() > 0)
{
hasAttachments = true;
break;
}
}
}
if (debugMode)
{
Log.d(RTApiClient.class.getSimpleName(), "Calling API method via " + rtType.name() + " : " + url);
Log.d(RTApiClient.class.getSimpleName(), "Content-type: " + cmd.getContentType());
if (headers.size() > 0)
{
Log.d(RTApiClient.class.getSimpleName(), "With headers: ");
for (RTPostParameter p : headers)
{
Log.d(RTApiClient.class.getSimpleName(), String.format(" %s = %s", p.getName(), p.getValue()));
}
} else
{
Log.d(RTApiClient.class.getSimpleName(), "Without headers");
}
if (parameters.size() > 0)
{
Log.d(RTApiClient.class.getSimpleName(), "With parameters: ");
for (RTPostParameter p : parameters)
{
if (rtType == RTApiRequestType.POST)
{
Log.d(RTApiClient.class.getSimpleName(), String.format("%s: %s = %s", rtType.name(), p.getName(), p.getAttachment() != null ? p.getAttachment().getAbsolutePath() : p.getValue()));
} else
{
Log.d(RTApiClient.class.getSimpleName(), String.format("%s: %s = %s", rtType.name(), p.getName(), p.getValue()));
}
}
} else
{
Log.d(RTApiClient.class.getSimpleName(), "Without parameters");
}
}
HttpResponse response = null;
switch (rtType)
{
case POST:
if (!hasAttachments)
{
response = processPost(cmd, url, parameters, headers);
} else
{
response = submitForm(url, headers, parameters);
}
break;
case GET:
response = executeGetRequest(url, headers, parameters);
break;
case PUT:
response = processPut(cmd, url, headers, parameters);
break;
case DELETE:
response = processDelete(cmd, url, headers, parameters);
break;
default:
response = submitForm(url, headers, parameters);
break;
}
onCommandHttpRequestDone(cmd, url, parameters, response);
if (debugMode)
{
Log.d(RTApiClient.class.getSimpleName(), "<< Server returned status code: " + response.getStatusLine().getStatusCode());
Log.d(RTApiClient.class.getSimpleName(), "<< " + response.getStatusLine().getReasonPhrase());
}
final String data = loadHttpResponseToString(response, transportEncoding);
onCommandResponseDataLoaded(cmd, url, parameters, response, data);
if (debugMode)
{
Log.d(RTApiClient.class.getSimpleName(), "\n\n<< " + url);
Log.d(RTApiClient.class.getSimpleName(), data);
Log.d(RTApiClient.class.getSimpleName(), "\n\n");
}
RTApiCommandResult result = cmd.parseServerResponseData(data);
onCommandPostExecure(cmd, url, parameters, response, result);
return result;
} catch (RTHTTPError httpError)
{
onCommandPostExecureWithError(cmd, url, parameters, httpError.getStatusCode(), httpError.getStatusText(),
httpError.getResponseBody());
if (debugMode)
{
Log.d(RTApiClient.class.getSimpleName(), "<< " + httpError.getResponseBody());
}
RTApiCommandResult result = cmd.parseServerErrorResponseData(httpError);
return result;
} catch (RTApiError baw)
{
throw baw;
} catch (Throwable otherError)
{
throw new RTApiError(otherError);
}
}
|
diff --git a/geoserver/community/geosearch/src/main/java/org/geoserver/geosearch/FeatureRestlet.java b/geoserver/community/geosearch/src/main/java/org/geoserver/geosearch/FeatureRestlet.java
index bbbdfeb8c4..4d851d4d47 100644
--- a/geoserver/community/geosearch/src/main/java/org/geoserver/geosearch/FeatureRestlet.java
+++ b/geoserver/community/geosearch/src/main/java/org/geoserver/geosearch/FeatureRestlet.java
@@ -1,179 +1,182 @@
package org.geoserver.geosearch;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.geoserver.ows.KvpParser;
import org.geoserver.ows.util.CaseInsensitiveMap;
import org.geoserver.platform.GeoServerExtensions;
import org.geoserver.rest.RESTUtils;
import org.geoserver.wms.kvp.GetMapKvpRequestReader;
import org.geotools.util.logging.Logging;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.OutputRepresentation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.vfny.geoserver.config.DataConfig;
import org.vfny.geoserver.global.Data;
import org.vfny.geoserver.global.WMS;
import org.vfny.geoserver.wms.requests.GetMapRequest;
import org.vfny.geoserver.wms.responses.GetMapResponse;
import org.vfny.geoserver.wms.responses.map.kml.GeoSearchMapProducerFactory;
import org.vfny.geoserver.wms.servlets.GetMap;
public class FeatureRestlet extends GeoServerProxyAwareRestlet implements ApplicationContextAware {
private static Logger LOGGER = Logging.getLogger("org.geoserver.geosearch");
private Data myData;
private DataConfig myDataConfig;
private WMS myWMS;
private GetMap myGetMap;
private ApplicationContext myContext;
public void setData(Data d){
myData = d;
}
public void setGetMap(GetMap gm){
myGetMap = gm;
}
public void setWms(WMS wms){
myWMS = wms;
}
public void setDataConfig(DataConfig dc){
myDataConfig = dc;
}
public void setApplicationContext(ApplicationContext context){
myContext = context;
}
public Data getData(){
return myData;
}
public GetMap getGetMap(){
return myGetMap;
}
public WMS getWms(){
return myWMS;
}
public DataConfig getDataConfig(){
return myDataConfig;
}
public ApplicationContext getApplicationContext(){
return myContext;
}
public FeatureRestlet() {
}
public void handle(Request request, Response response){
try{
if (request.getMethod().equals(Method.GET)){
doGet(request, response);
} else {
response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
}
} catch (Exception e){
LOGGER.severe("Badness (" + e + ") while handling layer request!");
e.printStackTrace();
response.setStatus(Status.SERVER_ERROR_INTERNAL);
}
}
public void doGet(Request request, Response response) throws Exception{
String namespace = (String)request.getAttributes().get("namespace");
String layername = (String)request.getAttributes().get("layer");
String featureId = (String)request.getAttributes().get("feature");
String format = (String)request.getAttributes().get("format");
- GeoSearchMapProducerFactory.BASE_URL = getBaseURL(request);
+ String bu = getBaseURL(request);
+ int lastslash = bu.lastIndexOf("/");
+ bu = bu.substring(0, lastslash);
+ GeoSearchMapProducerFactory.BASE_URL = bu;
if (request.getMethod().equals(Method.GET)) {
GetMapKvpRequestReader reader = new GetMapKvpRequestReader(getWms());
reader.setHttpRequest( RESTUtils.getServletRequest( request ) );
Map raw = new HashMap();
raw.put("layers", namespace + ":" + layername);
raw.put("styles", "polygon");
- raw.put("format", "kmlgeosearch");
+ raw.put("format", "geosearch-kml");
raw.put("srs", "epsg:4326");
raw.put("bbox", "-180,-90,180,90");
raw.put("height", "600");
raw.put("width", "800");
raw.put("featureid", layername + "." + featureId);
final GetMapRequest gmreq = (GetMapRequest) reader.read((GetMapRequest) reader.createRequest(), parseKvp(raw), raw);
final GetMapResponse gmresp = new GetMapResponse(getWms(), getApplicationContext());
response.setEntity(new OutputRepresentation(new MediaType("application/xml+kml")){
public void write(OutputStream os){
try{
gmresp.execute(gmreq);
gmresp.writeTo(os);
} catch (IOException ioe){
// blah, this will never happen
}
}
});
} else {
response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
}
}
/**
* Parses a raw set of kvp's into a parsed set of kvps.
*
* @param kvp Map of String,String.
*/
protected Map parseKvp(Map /*<String,String>*/ raw)
throws Exception {
//parse the raw values
List parsers = GeoServerExtensions.extensions(KvpParser.class, getApplicationContext());
Map kvp = new CaseInsensitiveMap(new HashMap());
for (Iterator e = raw.entrySet().iterator(); e.hasNext();) {
Map.Entry entry = (Map.Entry) e.next();
String key = (String) entry.getKey();
String val = (String) entry.getValue();
Object parsed = null;
for (Iterator p = parsers.iterator(); p.hasNext();) {
KvpParser parser = (KvpParser) p.next();
if (key.equalsIgnoreCase(parser.getKey())) {
parsed = parser.parse(val);
if (parsed != null) {
break;
}
}
}
if (parsed == null) {
parsed = val;
}
kvp.put(key, parsed);
}
return kvp;
}
}
| false | true | public void doGet(Request request, Response response) throws Exception{
String namespace = (String)request.getAttributes().get("namespace");
String layername = (String)request.getAttributes().get("layer");
String featureId = (String)request.getAttributes().get("feature");
String format = (String)request.getAttributes().get("format");
GeoSearchMapProducerFactory.BASE_URL = getBaseURL(request);
if (request.getMethod().equals(Method.GET)) {
GetMapKvpRequestReader reader = new GetMapKvpRequestReader(getWms());
reader.setHttpRequest( RESTUtils.getServletRequest( request ) );
Map raw = new HashMap();
raw.put("layers", namespace + ":" + layername);
raw.put("styles", "polygon");
raw.put("format", "kmlgeosearch");
raw.put("srs", "epsg:4326");
raw.put("bbox", "-180,-90,180,90");
raw.put("height", "600");
raw.put("width", "800");
raw.put("featureid", layername + "." + featureId);
final GetMapRequest gmreq = (GetMapRequest) reader.read((GetMapRequest) reader.createRequest(), parseKvp(raw), raw);
final GetMapResponse gmresp = new GetMapResponse(getWms(), getApplicationContext());
response.setEntity(new OutputRepresentation(new MediaType("application/xml+kml")){
public void write(OutputStream os){
try{
gmresp.execute(gmreq);
gmresp.writeTo(os);
} catch (IOException ioe){
// blah, this will never happen
}
}
});
} else {
response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
}
}
| public void doGet(Request request, Response response) throws Exception{
String namespace = (String)request.getAttributes().get("namespace");
String layername = (String)request.getAttributes().get("layer");
String featureId = (String)request.getAttributes().get("feature");
String format = (String)request.getAttributes().get("format");
String bu = getBaseURL(request);
int lastslash = bu.lastIndexOf("/");
bu = bu.substring(0, lastslash);
GeoSearchMapProducerFactory.BASE_URL = bu;
if (request.getMethod().equals(Method.GET)) {
GetMapKvpRequestReader reader = new GetMapKvpRequestReader(getWms());
reader.setHttpRequest( RESTUtils.getServletRequest( request ) );
Map raw = new HashMap();
raw.put("layers", namespace + ":" + layername);
raw.put("styles", "polygon");
raw.put("format", "geosearch-kml");
raw.put("srs", "epsg:4326");
raw.put("bbox", "-180,-90,180,90");
raw.put("height", "600");
raw.put("width", "800");
raw.put("featureid", layername + "." + featureId);
final GetMapRequest gmreq = (GetMapRequest) reader.read((GetMapRequest) reader.createRequest(), parseKvp(raw), raw);
final GetMapResponse gmresp = new GetMapResponse(getWms(), getApplicationContext());
response.setEntity(new OutputRepresentation(new MediaType("application/xml+kml")){
public void write(OutputStream os){
try{
gmresp.execute(gmreq);
gmresp.writeTo(os);
} catch (IOException ioe){
// blah, this will never happen
}
}
});
} else {
response.setStatus(Status.CLIENT_ERROR_NOT_FOUND);
}
}
|
diff --git a/src/com/esotericsoftware/kryo/serializers/FieldSerializer.java b/src/com/esotericsoftware/kryo/serializers/FieldSerializer.java
index e27b997..2515891 100644
--- a/src/com/esotericsoftware/kryo/serializers/FieldSerializer.java
+++ b/src/com/esotericsoftware/kryo/serializers/FieldSerializer.java
@@ -1,1072 +1,1072 @@
package com.esotericsoftware.kryo.serializers;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sun.misc.Unsafe;
import com.esotericsoftware.kryo.Generics;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.NotNull;
import com.esotericsoftware.kryo.Registration;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.util.IntArray;
import com.esotericsoftware.kryo.util.ObjectMap;
import static com.esotericsoftware.kryo.util.UnsafeUtil.unsafe;
import com.esotericsoftware.kryo.util.Util;
import com.esotericsoftware.reflectasm.FieldAccess;
import com.esotericsoftware.kryo.serializers.AsmCacheFields.*;
import com.esotericsoftware.kryo.serializers.UnsafeCacheFields.*;
import static com.esotericsoftware.minlog.Log.*;
// BOZO - Make primitive serialization with ReflectASM configurable?
/** Serializes objects using direct field assignment. No header or schema data is stored, only the data for each field. This
* reduces output size but means if any field is added or removed, previously serialized bytes are invalidated. If fields are
* public, bytecode generation will be used instead of reflection.
* @see Serializer
* @see Kryo#register(Class, Serializer)
* @author Nathan Sweet <[email protected]>
* @author Roman Levenstein <[email protected]> */
public class FieldSerializer<T> extends Serializer<T> implements Comparator<FieldSerializer.CachedField> {
final private Kryo kryo;
final private Class type;
// type variables declared for this type
final private TypeVariable[] typeParameters;
private CachedField[] fields = new CachedField[0];
private CachedField[] transientFields = new CachedField[0];
Object access;
private boolean fieldsCanBeNull = true, setFieldsAsAccessible = true;
private boolean ignoreSyntheticFields = true;
private boolean fixedFieldTypes;
// If set, ASM-backend is used. Otherwise Unsafe-based backend or reflection is used
private boolean useAsmBackend;
// Concrete classes passed as values for type variables
private Class[] generics;
private Generics genericsScope;
// If set, this serializer tries to use a variable length encoding
// for int and long fields
private boolean optimizeInts;
// If set, adjacent primitive fields are written in bulk
// This flag may only work with Oracle JVMs, because they
// layout primitive fields in memory in such a way that
// primitive fields are grouped together.
// This option has effect only when used with Unsafe-based FieldSerializer.
// FIXME: Not all versions of Sun/Oracle JDK properly work with this option. Disable it for now. Later add dynamic checks
// to see if this feature is supported by a current JDK version.
private boolean useMemRegions = false;
// If set, transient fields will be copied
private final boolean copyTransient = true;
// If set, transient fields will be serialized
private final boolean serializeTransient = false;
{
useAsmBackend = unsafe() != null;
optimizeInts = true;
if(TRACE) trace("kryo", "optimize ints is " + optimizeInts);
}
// BOZO - Get rid of kryo here?
public FieldSerializer (Kryo kryo, Class type) {
this.kryo = kryo;
this.type = type;
this.typeParameters = type.getTypeParameters();
this.useAsmBackend = kryo.useAsmBackend();
if(TRACE) trace("kryo", "FieldSerializer(Kryo, Class)");
rebuildCachedFields();
}
public FieldSerializer (Kryo kryo, Class type, Class[] generics) {
this.kryo = kryo;
this.type = type;
this.generics = generics;
this.typeParameters = type.getTypeParameters();
this.useAsmBackend = kryo.useAsmBackend();
if(TRACE) trace("kryo", "FieldSerializer(Kryo, Class, Generics)");
rebuildCachedFields();
}
/***
* Create a mapping from type variable names (which are declared as type parameters of a generic class) to the
* concrete classes used for type instantiation.
*
* @param clazz class with generic type arguments
* @param generics concrete types used to instantiate the class
* @return new scope for type parameters
*/
private Generics buildGenericsScope(Class clazz, Class[] generics) {
Class typ = clazz;
TypeVariable[] typeParams = null;
while (typ != null) {
typeParams = typ.getTypeParameters();
if (typeParams == null || typeParams.length == 0) {
typ = typ.getComponentType();
} else
break;
}
if(typeParams != null && typeParams.length > 0) {
Generics genScope;
trace("kryo", "Class " + clazz.getName() + " has generic type parameters");
int typeVarNum = 0;
Map<String, Class> typeVar2concreteClass;
typeVar2concreteClass = new HashMap<String, Class>();
for(TypeVariable typeVar: typeParams) {
String typeVarName = typeVar.getName();
if(TRACE) trace("kryo", "Type parameter variable: name=" + typeVarName + " type bounds=" + Arrays.toString(typeVar.getBounds()));
if(generics != null && generics.length>typeVarNum) {
// If passed concrete classes are known explicitly, use this information
typeVar2concreteClass.put(typeVarName, generics[typeVarNum]);
if(TRACE) trace("kryo", "Concrete type used for " +typeVarName + " is: " + generics[typeVarNum].getName());
} else {
// Otherwise try to derive the information from the current GenericScope
if(TRACE) trace("kryo", "Trying to use kryo.getGenericScope");
Generics scope = kryo.getGenericsScope();
if(scope != null) {
Class concreteClass = scope.getConcreteClass(typeVarName);
if(concreteClass != null) {
typeVar2concreteClass.put(typeVarName, concreteClass);
if(TRACE) trace("kryo", "Concrete type used for " +typeVarName + " is: " + concreteClass.getName());
}
}
}
typeVarNum++;
}
genScope = new Generics(typeVar2concreteClass);
return genScope;
} else
return null;
}
/** Called when the list of cached fields must be rebuilt. This is done any time settings are changed that affect which fields
* will be used. It is called from the constructor for FieldSerializer, but not for subclasses. Subclasses must call this from
* their constructor. */
private void rebuildCachedFields () {
if(TRACE) {
// new RuntimeException("Call stack for rebuildCachedFields").printStackTrace(System.out);
trace("kryo", "rebuilding cache fields for " + type.getName());
}
if(TRACE && generics != null) trace("kryo", "generic type parameters are" + Arrays.toString(generics));
if (type.isInterface()) {
fields = new CachedField[0]; // No fields to serialize.
return;
}
// For generic classes, generate a mapping from type variable names to the concrete types
// This mapping is the same for the whole class.
Generics genScope = buildGenericsScope(type, generics);
genericsScope = genScope;
// Push proper scopes at serializer construction time
if(genericsScope!=null)
kryo.pushGenericsScope(type, genericsScope);
// Collect all fields.
List<Field> allFields = new ArrayList();
Class nextClass = type;
while (nextClass != Object.class) {
Field[] declaredFields = nextClass.getDeclaredFields();
if(declaredFields != null)
for(Field f: declaredFields) {
if(Modifier.isStatic(f.getModifiers()))
continue;
allFields.add(f);
}
nextClass = nextClass.getSuperclass();
}
ObjectMap context = kryo.getContext();
IntArray useAsm = new IntArray();
// Sort fields by their offsets
if (useMemRegions && !useAsmBackend && unsafe() != null) {
Field[] allFieldsArray = allFields.toArray(new Field[] {});
Comparator<Field> fieldOffsetComparator = new Comparator<Field>() {
@Override
public int compare(Field f1, Field f2) {
long offset1 = unsafe().objectFieldOffset(f1);
long offset2 = unsafe().objectFieldOffset(f2);
if (offset1 < offset2)
return -1;
if (offset1 == offset2)
return 0;
return 1;
}
};
Arrays.sort(allFieldsArray, fieldOffsetComparator);
allFields = Arrays.asList(allFieldsArray);
for(Field f: allFields) {
if(TRACE) trace("kryo", "Field " + f.getName()+ " at offset " + unsafe().objectFieldOffset(f));
}
}
ArrayList<Field> validFields = new ArrayList(allFields.size());
for (int i = 0, n = allFields.size(); i < n; i++) {
Field field = allFields.get(i);
int modifiers = field.getModifiers();
if (Modifier.isTransient(modifiers)) continue;
if (Modifier.isStatic(modifiers)) continue;
if (field.isSynthetic() && ignoreSyntheticFields) continue;
if (!field.isAccessible()) {
if (!setFieldsAsAccessible) continue;
try {
field.setAccessible(true);
} catch (AccessControlException ex) {
continue;
}
}
Optional optional = field.getAnnotation(Optional.class);
if (optional != null && !context.containsKey(optional.value())) continue;
validFields.add(field);
// BOZO - Must be public?
useAsm.add(!Modifier.isFinal(modifiers) && Modifier.isPublic(modifiers)
&& Modifier.isPublic(field.getType().getModifiers()) ? 1 : 0);
}
ArrayList<Field> validTransientFields = new ArrayList(allFields.size());
// Process transient fields
for (int i = 0, n = allFields.size(); i < n; i++) {
Field field = allFields.get(i);
int modifiers = field.getModifiers();
if (!Modifier.isTransient(modifiers)) continue;
if (Modifier.isStatic(modifiers)) continue;
if (field.isSynthetic() && ignoreSyntheticFields) continue;
if (!field.isAccessible()) {
if (!setFieldsAsAccessible) continue;
try {
field.setAccessible(true);
} catch (AccessControlException ex) {
continue;
}
}
Optional optional = field.getAnnotation(Optional.class);
if (optional != null && !context.containsKey(optional.value())) continue;
validTransientFields.add(field);
// BOZO - Must be public?
useAsm.add(!Modifier.isFinal(modifiers) && Modifier.isPublic(modifiers)
&& Modifier.isPublic(field.getType().getModifiers()) ? 1 : 0);
}
// Use ReflectASM for any public fields.
if (useAsmBackend && !Util.isAndroid && Modifier.isPublic(type.getModifiers()) && useAsm.indexOf(1) != -1) {
try {
access = FieldAccess.get(type);
} catch (RuntimeException ignored) {
}
}
ArrayList<CachedField> cachedFields = new ArrayList(validFields.size());
ArrayList<CachedField> cachedTransientFields = new ArrayList(validTransientFields.size());
createCachedFields(useAsm, validFields, cachedFields, 0);
createCachedFields(useAsm, validTransientFields, cachedTransientFields, validFields.size());
Collections.sort(cachedFields, this);
fields = cachedFields.toArray(new CachedField[cachedFields.size()]);
Collections.sort(cachedTransientFields, this);
transientFields = cachedTransientFields.toArray(new CachedField[cachedTransientFields.size()]);
initializeCachedFields();
if(genericsScope!=null)
kryo.popGenericsScope();
}
private void createCachedFields(IntArray useAsm,
ArrayList<Field> validFields, ArrayList<CachedField> cachedFields, int baseIndex) {
// Find adjacent fields of primitive types
long startPrimitives = 0;
long endPrimitives = 0;
boolean lastWasPrimitive = false;
int primitiveLength = 0;
int lastAccessIndex = -1;
Field lastField = null;
long fieldOffset = -1;
long fieldEndOffset = -1;
long lastFieldEndOffset = -1;
for (int i = 0, n = validFields.size(); i < n; i++) {
Field field = validFields.get(i);
int accessIndex = -1;
if (access != null && useAsm.get(baseIndex + i) == 1) accessIndex = ((FieldAccess)access).getIndex(field.getName());
if(useAsmBackend || !useMemRegions)
cachedFields.add(newCachedField(field, cachedFields.size(), accessIndex));
else {
fieldOffset = unsafe().objectFieldOffset(field);
fieldEndOffset = fieldOffset + fieldSizeOf(field.getType());
if (!field.getType().isPrimitive() && lastWasPrimitive) {
// This is not a primitive field. Therefore, it marks
// the end of a region of primitive fields
endPrimitives = lastFieldEndOffset;
lastWasPrimitive = false;
if (primitiveLength > 1) {
if(TRACE)
trace("kryo", "Class "
+ type.getName()
+ ". Found a set of consecutive primitive fields. Number of fields = "
+ primitiveLength
+ ". Byte length = "
+ (endPrimitives - startPrimitives)
+ " Start offset = "
+ startPrimitives + " endOffset="
+ endPrimitives);
// TODO: register a region instead of a field
CachedField cf = new UnsafeRegionField(startPrimitives, (endPrimitives - startPrimitives));
cf.field = lastField;
cachedFields.add(cf);
} else {
if(lastField != null)
cachedFields.add(newCachedField(lastField, cachedFields.size(), lastAccessIndex));
}
cachedFields.add(newCachedField(field, cachedFields.size(), accessIndex));
} else if(!field.getType().isPrimitive() ) {
cachedFields.add(newCachedField(field, cachedFields.size(), accessIndex));
} else if (!lastWasPrimitive) {
// If previous field was non primitive, it marks a start
// of a region of primitive fields
startPrimitives = fieldOffset;
lastWasPrimitive = true;
primitiveLength = 1;
} else {
primitiveLength++;
}
}
lastAccessIndex = accessIndex;
lastField = field;
lastFieldEndOffset = fieldEndOffset;
}
if(!useAsmBackend && useMemRegions && lastWasPrimitive) {
endPrimitives = lastFieldEndOffset;
if (primitiveLength > 1) {
if(TRACE)
trace("kryo", "Class "
+ type.getName()
+ ". Found a set of consecutive primitive fields. Number of fields = "
+ primitiveLength
+ ". Byte length = "
+ (endPrimitives - startPrimitives)
+ " Start offset = "
+ startPrimitives + " endOffset="
+ endPrimitives);
// register a region instead of a field
CachedField cf = new UnsafeRegionField(startPrimitives, (endPrimitives - startPrimitives));
cf.field = lastField;
cachedFields.add(cf);
} else {
if(lastField != null)
cachedFields.add(newCachedField(lastField, cachedFields.size(), lastAccessIndex));
}
}
}
private int fieldSizeOf(Class<?> clazz) {
if(clazz == int.class || clazz == float.class)
return 4;
if(clazz == long.class || clazz == double.class)
return 8;
if(clazz == byte.class || clazz == boolean.class)
return 1;
if(clazz == short.class || clazz == char.class)
return 2;
// Everything else is a reference to an object, i.e. an address
return unsafe().addressSize();
}
/***
* {@inheritDoc}
*/
public void setGenerics (Kryo kryo, Class[] generics) {
this.generics = generics;
if(TRACE) trace("kryo", "setGenerics");
if(typeParameters != null && typeParameters.length > 0)
rebuildCachedFields();
}
protected void initializeCachedFields () {
}
private Class[] computeFieldGenerics(Type fieldGenericType, Field field) {
Class[] fieldGenerics = null;
if(fieldGenericType != null) {
if (fieldGenericType instanceof TypeVariable) {
TypeVariable typeVar = (TypeVariable) fieldGenericType;
// Obtain information about a concrete type of a given variable from the environment
Class concreteClass = genericsScope.getConcreteClass(typeVar.getName());
if(concreteClass != null) {
Class fieldClass = concreteClass;
fieldGenerics = new Class[] {fieldClass};
if(TRACE) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldClass.getName());
}
} else if(fieldGenericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)fieldGenericType;
// Get actual type arguments of the current field's type
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
// if(actualTypeArguments != null && generics != null) {
if(actualTypeArguments != null) {
fieldGenerics = new Class[actualTypeArguments.length];
for(int i=0; i < actualTypeArguments.length; ++i) {
Type t = actualTypeArguments[i];
if (t instanceof Class)
fieldGenerics[i] = (Class)t;
else if (t instanceof ParameterizedType)
fieldGenerics[i] = (Class)((ParameterizedType)t).getRawType();
else if (t instanceof TypeVariable)
fieldGenerics[i] = genericsScope.getConcreteClass(((TypeVariable) t).getName());
else if (t instanceof WildcardType)
fieldGenerics[i] = Object.class;
else
fieldGenerics[i] = null;
}
if(TRACE && fieldGenerics != null) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType + " where type parameters are " + Arrays.toString(fieldGenerics));
}
} else if(fieldGenericType instanceof GenericArrayType) {
// TODO: store generics for arrays as well?
GenericArrayType arrayType = (GenericArrayType)fieldGenericType;
Type genericComponentType = arrayType.getGenericComponentType();
fieldGenerics = computeFieldGenerics(genericComponentType, field);
// Kryo.getGenerics(fieldGenericType);
if(TRACE && fieldGenerics != null) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType + " where type parameters are " + Arrays.toString(fieldGenerics));
if(TRACE) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType);
}
}
return fieldGenerics;
}
private CachedField newCachedField (Field field, int fieldIndex, int accessIndex) {
Class fieldClass = field.getType();
Type fieldGenericType = field.getGenericType();
Class[] fieldGenerics = null;
if(TRACE) {
if(fieldGenericType != fieldClass)
trace("kryo", "Field " + field.getName() + " of type " + fieldClass + " of generic type " + fieldGenericType);
else
trace("kryo", "Field " + field.getName() + " of type " + fieldClass);
}
if(TRACE && fieldGenericType != null) trace("kryo", "Field generic type is of class " + fieldGenericType.getClass().getName());
if(fieldClass != fieldGenericType) {
// Get set of provided type parameters
// Get list of field specific concrete classes passed as generic parameters
Class[] cachedFieldGenerics = kryo.getGenerics(fieldGenericType);
// Build a generics scope for this field
Generics scope = buildGenericsScope(fieldClass, cachedFieldGenerics);
// Is it a field of a generic parameter type, i.e. "T field"?
- if (fieldClass == Object.class && fieldGenericType instanceof TypeVariable) {
+ if (fieldClass == Object.class && fieldGenericType instanceof TypeVariable && genericsScope != null) {
TypeVariable typeVar = (TypeVariable) fieldGenericType;
// Obtain information about a concrete type of a given variable from the environment
Class concreteClass = genericsScope.getConcreteClass(typeVar.getName());
if (concreteClass != null) {
scope = new Generics();
scope.add(typeVar.getName(), concreteClass);
}
}
if(TRACE) trace("kryo", "Generics scope of field " + field.getName() + " of class " + fieldGenericType + " is " + scope);
}
if(fieldGenericType != null) {
- if (fieldGenericType instanceof TypeVariable) {
+ if (fieldGenericType instanceof TypeVariable && genericsScope != null) {
TypeVariable typeVar = (TypeVariable) fieldGenericType;
// Obtain information about a concrete type of a given variable from the environment
Class concreteClass = genericsScope.getConcreteClass(typeVar.getName());
if(concreteClass != null) {
fieldClass = concreteClass;
fieldGenerics = new Class[] {fieldClass};
if(TRACE) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldClass.getName());
}
} else if(fieldGenericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)fieldGenericType;
// Get actual type arguments of the current field's type
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
// if(actualTypeArguments != null && generics != null) {
if(actualTypeArguments != null) {
fieldGenerics = new Class[actualTypeArguments.length];
for(int i=0; i < actualTypeArguments.length; ++i) {
Type t = actualTypeArguments[i];
if (t instanceof Class)
fieldGenerics[i] = (Class)t;
else if (t instanceof ParameterizedType)
fieldGenerics[i] = (Class)((ParameterizedType)t).getRawType();
- else if (t instanceof TypeVariable)
+ else if (t instanceof TypeVariable && genericsScope != null)
fieldGenerics[i] = genericsScope.getConcreteClass(((TypeVariable) t).getName());
else if (t instanceof WildcardType)
fieldGenerics[i] = Object.class;
else
fieldGenerics[i] = null;
}
if(TRACE && fieldGenerics != null) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType + " where type parameters are " + Arrays.toString(fieldGenerics));
}
} else if(fieldGenericType instanceof GenericArrayType) {
// TODO: store generics for arrays as well?
GenericArrayType arrayType = (GenericArrayType)fieldGenericType;
Type genericComponentType = arrayType.getGenericComponentType();
fieldGenerics = computeFieldGenerics(genericComponentType, field);
// Type componentType = arrayType.getGenericComponentType();
// Kryo.getGenerics(fieldGenericType);
if(TRACE && fieldGenerics != null) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType + " where type parameters are " + Arrays.toString(fieldGenerics));
if(TRACE) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType);
}
}
CachedField cachedField;
if (accessIndex != -1) {
if (fieldClass.isPrimitive()) {
if (fieldClass == boolean.class)
cachedField = new BooleanField();
else if (fieldClass == byte.class)
cachedField = new ByteField();
else if (fieldClass == char.class)
cachedField = new CharField();
else if (fieldClass == short.class)
cachedField = new ShortField();
else if (fieldClass == int.class)
cachedField = new IntField();
else if (fieldClass == long.class)
cachedField = new LongField();
else if (fieldClass == float.class)
cachedField = new FloatField();
else if (fieldClass == double.class)
cachedField = new DoubleField();
else {
if (TRACE)
trace("kryo", "ObjectField1");
cachedField = new AsmObjectField(this);
}
} else if (fieldClass == String.class
&& (!kryo.getReferences() || !kryo.getReferenceResolver().useReferences(String.class))) {
cachedField = new StringField();
} else {
if(TRACE) trace("kryo", "ObjectField2");
cachedField = new AsmObjectField(this);
}
} else if(!useAsmBackend) {
if (fieldClass.isPrimitive()) {
if (fieldClass == boolean.class)
cachedField = new UnsafeBooleanField(field);
else if (fieldClass == byte.class)
cachedField = new UnsafeByteField(field);
else if (fieldClass == char.class)
cachedField = new UnsafeCharField(field);
else if (fieldClass == short.class)
cachedField = new UnsafeShortField(field);
else if (fieldClass == int.class)
cachedField = new UnsafeIntField(field);
else if (fieldClass == long.class)
cachedField = new UnsafeLongField(field);
else if (fieldClass == float.class)
cachedField = new UnsafeFloatField(field);
else if (fieldClass == double.class)
cachedField = new UnsafeDoubleField(field);
else {
if (TRACE)
trace("kryo", "ObjectField1");
cachedField = new UnsafeObjectField(this);
}
} else if (fieldClass == String.class
&& (!kryo.getReferences() || !kryo.getReferenceResolver().useReferences(String.class))) {
cachedField = new UnsafeStringField(field);
} else {
if(TRACE) trace("kryo", "ObjectField2");
cachedField = new UnsafeObjectField(this);
}
} else {
if(TRACE) trace("kryo", "ObjectField3");
cachedField = new ObjectField(this);
if(fieldGenerics != null)
((ObjectField)cachedField).generics = fieldGenerics;
else {
Class[] cachedFieldGenerics = kryo.getGenerics(fieldGenericType);
((ObjectField) cachedField).generics = cachedFieldGenerics;
if(TRACE) trace("kryo", "Field generics: " + Arrays.toString(cachedFieldGenerics));
}
}
if(fieldGenerics != null && cachedField instanceof FieldSerializer.ObjectField) {
if (fieldGenerics[0] != null) {
// If any information about concrete types for generic arguments of current field's type
// was deriver, remember it.
((ObjectField) cachedField).generics = fieldGenerics;
if (TRACE)
trace("kryo",
"Field generics: " + Arrays.toString(fieldGenerics));
}
}
cachedField.field = field;
cachedField.optimizeInts = optimizeInts;
if(!useAsmBackend) {
cachedField.offset = unsafe().objectFieldOffset(field);
}
cachedField.access = (FieldAccess) access;
cachedField.accessIndex = accessIndex;
cachedField.canBeNull = fieldsCanBeNull && !fieldClass.isPrimitive() && !field.isAnnotationPresent(NotNull.class);
// Always use the same serializer for this field if the field's class is final.
if (kryo.isFinal(fieldClass) || fixedFieldTypes) cachedField.valueClass = fieldClass;
return cachedField;
}
public int compare (CachedField o1, CachedField o2) {
// Fields are sorted by alpha so the order of the data is known.
return o1.field.getName().compareTo(o2.field.getName());
}
/** Sets the default value for {@link CachedField#setCanBeNull(boolean)}. Calling this method resets the {@link #getFields()
* cached fields}.
* @param fieldsCanBeNull False if none of the fields are null. Saves 0-1 byte per field. True if it is not known (default). */
public void setFieldsCanBeNull (boolean fieldsCanBeNull) {
this.fieldsCanBeNull = fieldsCanBeNull;
if(TRACE) trace("kryo", "setFieldsCanBeNull");
rebuildCachedFields();
}
/** Controls which fields are serialized. Calling this method resets the {@link #getFields() cached fields}.
* @param setFieldsAsAccessible If true, all non-transient fields (inlcuding private fields) will be serialized and
* {@link Field#setAccessible(boolean) set as accessible} if necessary (default). If false, only fields in the public
* API will be serialized. */
public void setFieldsAsAccessible (boolean setFieldsAsAccessible) {
this.setFieldsAsAccessible = setFieldsAsAccessible;
if(TRACE) trace("kryo", "setFieldsAsAccessible");
rebuildCachedFields();
}
/** Controls if synthetic fields are serialized. Default is true. Calling this method resets the {@link #getFields() cached
* fields}.
* @param ignoreSyntheticFields If true, only non-synthetic fields will be serialized. */
public void setIgnoreSyntheticFields (boolean ignoreSyntheticFields) {
this.ignoreSyntheticFields = ignoreSyntheticFields;
if(TRACE) trace("kryo", "setIgnoreSyntheticFields");
rebuildCachedFields();
}
/** Sets the default value for {@link CachedField#setClass(Class)} to the field's declared type. This allows FieldSerializer to
* be more efficient, since it knows field values will not be a subclass of their declared type. Default is false. Calling this
* method resets the {@link #getFields() cached fields}. */
public void setFixedFieldTypes (boolean fixedFieldTypes) {
this.fixedFieldTypes = fixedFieldTypes;
if(TRACE) trace("kryo", "setFixedFieldTypes");
rebuildCachedFields();
}
/** Controls whether ASM should be used. Calling this method resets the {@link #getFields() cached fields}.
* @param setUseAsm If true, ASM will be used for fast serialization. If false, Unsafe will be used (default)
*/
public void setUseAsm (boolean setUseAsm) {
useAsmBackend = setUseAsm;
// optimizeInts = useAsmBackend;
if(TRACE) trace("kryo", "setUseAsm");
rebuildCachedFields();
}
// Uncomment this method, if we want to allow explicit control over copying of transient fields
// public void setCopyTransient (boolean setCopyTransient) {
// copyTransient = setCopyTransient;
// if(TRACE) trace("kryo", "setCopyTransient");
// }
/**
* This method can be called for different fields having the same type.
* Even though the raw type is the same, if the type is generic, it could
* happen that different concrete classes are used to instantiate it.
* Therefore, in case of different instantiation parameters, the
* fields analysis should be repeated.
*
* TODO: Cache serializer instances generated for a given set of generic parameters.
* Reuse it later instead of recomputing every time.
*
*/
public void write (Kryo kryo, Output output, T object) {
if(TRACE) trace("kryo", "FieldSerializer.write fields of class " + object.getClass().getName());
if(typeParameters != null && generics != null) {
// Rebuild fields info. It may result in rebuilding the genericScope
rebuildCachedFields();
}
if(genericsScope != null) {
// Push proper scopes at serializer usage time
kryo.pushGenericsScope(type, genericsScope);
}
CachedField[] fields = this.fields;
for (int i = 0, n = fields.length; i < n; i++)
fields[i].write(output, object);
// Serialize transient fields
if (serializeTransient) {
for (int i = 0, n = transientFields.length; i < n; i++)
transientFields[i].write(output, object);
}
if(genericsScope != null) {
// Pop the scope for generics
kryo.popGenericsScope();
}
}
public T read (Kryo kryo, Input input, Class<T> type) {
try {
if (typeParameters != null && generics != null) {
// Rebuild fields info. It may result in rebuilding the
// genericScope
rebuildCachedFields();
}
if(genericsScope != null) {
// Push a new scope for generics
kryo.pushGenericsScope(type, genericsScope);
}
T object = create(kryo, input, type);
kryo.reference(object);
CachedField[] fields = this.fields;
for (int i = 0, n = fields.length; i < n; i++)
fields[i].read(input, object);
// De-serialize transient fields
if (serializeTransient) {
for (int i = 0, n = transientFields.length; i < n; i++)
transientFields[i].read(input, object);
}
return object;
} finally {
if(genericsScope != null && kryo.getGenericsScope() != null) {
// Pop the scope for generics
kryo.popGenericsScope();
}
}
}
/** Used by {@link #read(Kryo, Input, Class)} to create the new object. This can be overridden to customize object creation, eg
* to call a constructor with arguments. The default implementation uses {@link Kryo#newInstance(Class)}. */
protected T create (Kryo kryo, Input input, Class<T> type) {
return kryo.newInstance(type);
}
/** Allows specific fields to be optimized. */
public CachedField getField (String fieldName) {
for (CachedField cachedField : fields)
if (cachedField.field.getName().equals(fieldName)) return cachedField;
throw new IllegalArgumentException("Field \"" + fieldName + "\" not found on class: " + type.getName());
}
/** Removes a field so that it won't be serialized. */
public void removeField (String fieldName) {
for (int i = 0; i < fields.length; i++) {
CachedField cachedField = fields[i];
if (cachedField.field.getName().equals(fieldName)) {
CachedField[] newFields = new CachedField[fields.length - 1];
System.arraycopy(fields, 0, newFields, 0, i);
System.arraycopy(fields, i + 1, newFields, i, newFields.length - i);
fields = newFields;
return;
}
}
throw new IllegalArgumentException("Field \"" + fieldName + "\" not found on class: " + type.getName());
}
public CachedField[] getFields () {
return fields;
}
public Class getType () {
return type;
}
/** Used by {@link #copy(Kryo, Object)} to create the new object. This can be overridden to customize object creation, eg to
* call a constructor with arguments. The default implementation uses {@link Kryo#newInstance(Class)}. */
protected T createCopy (Kryo kryo, T original) {
return (T)kryo.newInstance(original.getClass());
}
public T copy(Kryo kryo, T original) {
T copy = createCopy(kryo, original);
kryo.reference(copy);
// Copy transient fields
if (copyTransient) {
for (int i = 0, n = transientFields.length; i < n; i++)
transientFields[i].copy(original, copy);
}
for (int i = 0, n = fields.length; i < n; i++)
fields[i].copy(original, copy);
return copy;
}
/** Controls how a field will be serialized. */
public static abstract class CachedField<X> {
Field field;
FieldAccess access;
Class valueClass;
Serializer serializer;
boolean canBeNull;
int accessIndex = -1;
long offset = -1;
boolean optimizeInts = true;
/** @param valueClass The concrete class of the values for this field. This saves 1-2 bytes. The serializer registered for the
* specified class will be used. Only set to a non-null value if the field type in the class definition is final
* or the values for this field will not vary. */
public void setClass (Class valueClass) {
this.valueClass = valueClass;
this.serializer = null;
}
/** @param valueClass The concrete class of the values for this field. This saves 1-2 bytes. Only set to a non-null value if
* the field type in the class definition is final or the values for this field will not vary. */
public void setClass (Class valueClass, Serializer serializer) {
this.valueClass = valueClass;
this.serializer = serializer;
}
public void setSerializer (Serializer serializer) {
this.serializer = serializer;
}
public void setCanBeNull (boolean canBeNull) {
this.canBeNull = canBeNull;
}
public Field getField () {
return field;
}
public String toString () {
return field.getName();
}
abstract public void write (Output output, Object object);
abstract public void read (Input input, Object object);
abstract public void copy (Object original, Object copy);
}
/***
* Defer generation of serializers until it is really required at run-time.
* By default, use reflection-based approach.
*
*/
public static class ObjectField extends CachedField {
Class[] generics;
final FieldSerializer fieldSerializer;
final Class type;
final Kryo kryo;
ObjectField(FieldSerializer fieldSerializer){
this.fieldSerializer = fieldSerializer;
this.kryo = fieldSerializer.kryo;
this.type = fieldSerializer.type;
}
public Object getField(Object object) throws IllegalArgumentException, IllegalAccessException {
return field.get(object);
}
public void setField(Object object, Object value) throws IllegalArgumentException, IllegalAccessException {
field.set(object, value);
}
final public void write (Output output, Object object) {
try {
// if(typeVar2concreteClass != null) {
// // Push a new scope for generics
// kryo.pushGenericsScope(type, new Generics(typeVar2concreteClass));
// }
if (TRACE) trace("kryo", "Write field: " + this + " (" + object.getClass().getName() + ")" + " pos=" + output.position());
Object value = getField(object);
Serializer serializer = this.serializer;
if (valueClass == null) {
// The concrete type of the field is unknown, write the class first.
if (value == null) {
kryo.writeClass(output, null);
return;
}
Registration registration = kryo.writeClass(output, value.getClass());
if (serializer == null) serializer = registration.getSerializer();
// if (generics != null)
serializer.setGenerics(kryo, generics);
kryo.writeObject(output, value, serializer);
} else {
// The concrete type of the field is known, always use the same serializer.
if (serializer == null) this.serializer = serializer = kryo.getSerializer(valueClass);
// if (generics != null)
serializer.setGenerics(kryo, generics);
if (canBeNull) {
kryo.writeObjectOrNull(output, value, serializer);
} else {
if (value == null) {
throw new KryoException("Field value is null but canBeNull is false: " + this + " ("
+ object.getClass().getName() + ")");
}
kryo.writeObject(output, value, serializer);
}
}
} catch (IllegalAccessException ex) {
throw new KryoException("Error accessing field: " + this + " (" + object.getClass().getName() + ")", ex);
} catch (KryoException ex) {
ex.addTrace(this + " (" + object.getClass().getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
KryoException ex = new KryoException(runtimeEx);
ex.addTrace(this + " (" + object.getClass().getName() + ")");
throw ex;
} finally {
// if(typeVar2concreteClass != null)
// kryo.popGenericsScope();
}
}
final public void read (Input input, Object object) {
try {
if (TRACE) trace("kryo", "Read field: " + this + " (" + type.getName() + ")" + " pos=" + input.position());
Object value;
Class concreteType = valueClass;
Serializer serializer = this.serializer;
if (concreteType == null) {
Registration registration = kryo.readClass(input);
if (registration == null)
value = null;
else {
if (serializer == null) serializer = registration.getSerializer();
// if (generics != null)
serializer.setGenerics(kryo, generics);
value = kryo.readObject(input, registration.getType(), serializer);
}
} else {
if (serializer == null) this.serializer = serializer = kryo.getSerializer(valueClass);
// if (generics != null)
serializer.setGenerics(kryo, generics);
if (canBeNull)
value = kryo.readObjectOrNull(input, concreteType, serializer);
else
value = kryo.readObject(input, concreteType, serializer);
}
setField(object, value);
} catch (IllegalAccessException ex) {
throw new KryoException("Error accessing field: " + this + " (" + type.getName() + ")", ex);
} catch (KryoException ex) {
ex.addTrace(this + " (" + type.getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
KryoException ex = new KryoException(runtimeEx);
ex.addTrace(this + " (" + type.getName() + ")");
throw ex;
} finally {
// if(typeVar2concreteClass != null)
// kryo.popGenericsScope();
}
}
public void copy (Object original, Object copy) {
try {
if (accessIndex != -1) {
FieldAccess access = (FieldAccess)fieldSerializer.access;
access.set(copy, accessIndex, kryo.copy(access.get(original, accessIndex)));
} else
field.set(copy, kryo.copy(field.get(original)));
} catch (IllegalAccessException ex) {
throw new KryoException("Error accessing field: " + this + " (" + type.getName() + ")", ex);
} catch (KryoException ex) {
ex.addTrace(this + " (" + type.getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
KryoException ex = new KryoException(runtimeEx);
ex.addTrace(this + " (" + type.getName() + ")");
throw ex;
}
}
}
/** Indicates a field should be ignored when its declaring class is registered unless the {@link Kryo#getContext() context} has
* a value set for the specified key. This can be useful when a field must be serialized for one purpose, but not for another.
* Eg, a class for a networked application could have a field that should not be serialized and sent to clients, but should be
* serialized when stored on the server.
* @author Nathan Sweet <[email protected]> */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
static public @interface Optional {
public String value();
}
}
| false | true | private CachedField newCachedField (Field field, int fieldIndex, int accessIndex) {
Class fieldClass = field.getType();
Type fieldGenericType = field.getGenericType();
Class[] fieldGenerics = null;
if(TRACE) {
if(fieldGenericType != fieldClass)
trace("kryo", "Field " + field.getName() + " of type " + fieldClass + " of generic type " + fieldGenericType);
else
trace("kryo", "Field " + field.getName() + " of type " + fieldClass);
}
if(TRACE && fieldGenericType != null) trace("kryo", "Field generic type is of class " + fieldGenericType.getClass().getName());
if(fieldClass != fieldGenericType) {
// Get set of provided type parameters
// Get list of field specific concrete classes passed as generic parameters
Class[] cachedFieldGenerics = kryo.getGenerics(fieldGenericType);
// Build a generics scope for this field
Generics scope = buildGenericsScope(fieldClass, cachedFieldGenerics);
// Is it a field of a generic parameter type, i.e. "T field"?
if (fieldClass == Object.class && fieldGenericType instanceof TypeVariable) {
TypeVariable typeVar = (TypeVariable) fieldGenericType;
// Obtain information about a concrete type of a given variable from the environment
Class concreteClass = genericsScope.getConcreteClass(typeVar.getName());
if (concreteClass != null) {
scope = new Generics();
scope.add(typeVar.getName(), concreteClass);
}
}
if(TRACE) trace("kryo", "Generics scope of field " + field.getName() + " of class " + fieldGenericType + " is " + scope);
}
if(fieldGenericType != null) {
if (fieldGenericType instanceof TypeVariable) {
TypeVariable typeVar = (TypeVariable) fieldGenericType;
// Obtain information about a concrete type of a given variable from the environment
Class concreteClass = genericsScope.getConcreteClass(typeVar.getName());
if(concreteClass != null) {
fieldClass = concreteClass;
fieldGenerics = new Class[] {fieldClass};
if(TRACE) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldClass.getName());
}
} else if(fieldGenericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)fieldGenericType;
// Get actual type arguments of the current field's type
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
// if(actualTypeArguments != null && generics != null) {
if(actualTypeArguments != null) {
fieldGenerics = new Class[actualTypeArguments.length];
for(int i=0; i < actualTypeArguments.length; ++i) {
Type t = actualTypeArguments[i];
if (t instanceof Class)
fieldGenerics[i] = (Class)t;
else if (t instanceof ParameterizedType)
fieldGenerics[i] = (Class)((ParameterizedType)t).getRawType();
else if (t instanceof TypeVariable)
fieldGenerics[i] = genericsScope.getConcreteClass(((TypeVariable) t).getName());
else if (t instanceof WildcardType)
fieldGenerics[i] = Object.class;
else
fieldGenerics[i] = null;
}
if(TRACE && fieldGenerics != null) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType + " where type parameters are " + Arrays.toString(fieldGenerics));
}
} else if(fieldGenericType instanceof GenericArrayType) {
// TODO: store generics for arrays as well?
GenericArrayType arrayType = (GenericArrayType)fieldGenericType;
Type genericComponentType = arrayType.getGenericComponentType();
fieldGenerics = computeFieldGenerics(genericComponentType, field);
// Type componentType = arrayType.getGenericComponentType();
// Kryo.getGenerics(fieldGenericType);
if(TRACE && fieldGenerics != null) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType + " where type parameters are " + Arrays.toString(fieldGenerics));
if(TRACE) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType);
}
}
CachedField cachedField;
if (accessIndex != -1) {
if (fieldClass.isPrimitive()) {
if (fieldClass == boolean.class)
cachedField = new BooleanField();
else if (fieldClass == byte.class)
cachedField = new ByteField();
else if (fieldClass == char.class)
cachedField = new CharField();
else if (fieldClass == short.class)
cachedField = new ShortField();
else if (fieldClass == int.class)
cachedField = new IntField();
else if (fieldClass == long.class)
cachedField = new LongField();
else if (fieldClass == float.class)
cachedField = new FloatField();
else if (fieldClass == double.class)
cachedField = new DoubleField();
else {
if (TRACE)
trace("kryo", "ObjectField1");
cachedField = new AsmObjectField(this);
}
} else if (fieldClass == String.class
&& (!kryo.getReferences() || !kryo.getReferenceResolver().useReferences(String.class))) {
cachedField = new StringField();
} else {
if(TRACE) trace("kryo", "ObjectField2");
cachedField = new AsmObjectField(this);
}
} else if(!useAsmBackend) {
if (fieldClass.isPrimitive()) {
if (fieldClass == boolean.class)
cachedField = new UnsafeBooleanField(field);
else if (fieldClass == byte.class)
cachedField = new UnsafeByteField(field);
else if (fieldClass == char.class)
cachedField = new UnsafeCharField(field);
else if (fieldClass == short.class)
cachedField = new UnsafeShortField(field);
else if (fieldClass == int.class)
cachedField = new UnsafeIntField(field);
else if (fieldClass == long.class)
cachedField = new UnsafeLongField(field);
else if (fieldClass == float.class)
cachedField = new UnsafeFloatField(field);
else if (fieldClass == double.class)
cachedField = new UnsafeDoubleField(field);
else {
if (TRACE)
trace("kryo", "ObjectField1");
cachedField = new UnsafeObjectField(this);
}
} else if (fieldClass == String.class
&& (!kryo.getReferences() || !kryo.getReferenceResolver().useReferences(String.class))) {
cachedField = new UnsafeStringField(field);
} else {
if(TRACE) trace("kryo", "ObjectField2");
cachedField = new UnsafeObjectField(this);
}
} else {
if(TRACE) trace("kryo", "ObjectField3");
cachedField = new ObjectField(this);
if(fieldGenerics != null)
((ObjectField)cachedField).generics = fieldGenerics;
else {
Class[] cachedFieldGenerics = kryo.getGenerics(fieldGenericType);
((ObjectField) cachedField).generics = cachedFieldGenerics;
if(TRACE) trace("kryo", "Field generics: " + Arrays.toString(cachedFieldGenerics));
}
}
if(fieldGenerics != null && cachedField instanceof FieldSerializer.ObjectField) {
if (fieldGenerics[0] != null) {
// If any information about concrete types for generic arguments of current field's type
// was deriver, remember it.
((ObjectField) cachedField).generics = fieldGenerics;
if (TRACE)
trace("kryo",
"Field generics: " + Arrays.toString(fieldGenerics));
}
}
cachedField.field = field;
cachedField.optimizeInts = optimizeInts;
if(!useAsmBackend) {
cachedField.offset = unsafe().objectFieldOffset(field);
}
cachedField.access = (FieldAccess) access;
cachedField.accessIndex = accessIndex;
cachedField.canBeNull = fieldsCanBeNull && !fieldClass.isPrimitive() && !field.isAnnotationPresent(NotNull.class);
// Always use the same serializer for this field if the field's class is final.
if (kryo.isFinal(fieldClass) || fixedFieldTypes) cachedField.valueClass = fieldClass;
return cachedField;
}
| private CachedField newCachedField (Field field, int fieldIndex, int accessIndex) {
Class fieldClass = field.getType();
Type fieldGenericType = field.getGenericType();
Class[] fieldGenerics = null;
if(TRACE) {
if(fieldGenericType != fieldClass)
trace("kryo", "Field " + field.getName() + " of type " + fieldClass + " of generic type " + fieldGenericType);
else
trace("kryo", "Field " + field.getName() + " of type " + fieldClass);
}
if(TRACE && fieldGenericType != null) trace("kryo", "Field generic type is of class " + fieldGenericType.getClass().getName());
if(fieldClass != fieldGenericType) {
// Get set of provided type parameters
// Get list of field specific concrete classes passed as generic parameters
Class[] cachedFieldGenerics = kryo.getGenerics(fieldGenericType);
// Build a generics scope for this field
Generics scope = buildGenericsScope(fieldClass, cachedFieldGenerics);
// Is it a field of a generic parameter type, i.e. "T field"?
if (fieldClass == Object.class && fieldGenericType instanceof TypeVariable && genericsScope != null) {
TypeVariable typeVar = (TypeVariable) fieldGenericType;
// Obtain information about a concrete type of a given variable from the environment
Class concreteClass = genericsScope.getConcreteClass(typeVar.getName());
if (concreteClass != null) {
scope = new Generics();
scope.add(typeVar.getName(), concreteClass);
}
}
if(TRACE) trace("kryo", "Generics scope of field " + field.getName() + " of class " + fieldGenericType + " is " + scope);
}
if(fieldGenericType != null) {
if (fieldGenericType instanceof TypeVariable && genericsScope != null) {
TypeVariable typeVar = (TypeVariable) fieldGenericType;
// Obtain information about a concrete type of a given variable from the environment
Class concreteClass = genericsScope.getConcreteClass(typeVar.getName());
if(concreteClass != null) {
fieldClass = concreteClass;
fieldGenerics = new Class[] {fieldClass};
if(TRACE) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldClass.getName());
}
} else if(fieldGenericType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType)fieldGenericType;
// Get actual type arguments of the current field's type
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
// if(actualTypeArguments != null && generics != null) {
if(actualTypeArguments != null) {
fieldGenerics = new Class[actualTypeArguments.length];
for(int i=0; i < actualTypeArguments.length; ++i) {
Type t = actualTypeArguments[i];
if (t instanceof Class)
fieldGenerics[i] = (Class)t;
else if (t instanceof ParameterizedType)
fieldGenerics[i] = (Class)((ParameterizedType)t).getRawType();
else if (t instanceof TypeVariable && genericsScope != null)
fieldGenerics[i] = genericsScope.getConcreteClass(((TypeVariable) t).getName());
else if (t instanceof WildcardType)
fieldGenerics[i] = Object.class;
else
fieldGenerics[i] = null;
}
if(TRACE && fieldGenerics != null) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType + " where type parameters are " + Arrays.toString(fieldGenerics));
}
} else if(fieldGenericType instanceof GenericArrayType) {
// TODO: store generics for arrays as well?
GenericArrayType arrayType = (GenericArrayType)fieldGenericType;
Type genericComponentType = arrayType.getGenericComponentType();
fieldGenerics = computeFieldGenerics(genericComponentType, field);
// Type componentType = arrayType.getGenericComponentType();
// Kryo.getGenerics(fieldGenericType);
if(TRACE && fieldGenerics != null) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType + " where type parameters are " + Arrays.toString(fieldGenerics));
if(TRACE) trace("kryo", "Determined concrete class of " + field.getName() + " to be " + fieldGenericType);
}
}
CachedField cachedField;
if (accessIndex != -1) {
if (fieldClass.isPrimitive()) {
if (fieldClass == boolean.class)
cachedField = new BooleanField();
else if (fieldClass == byte.class)
cachedField = new ByteField();
else if (fieldClass == char.class)
cachedField = new CharField();
else if (fieldClass == short.class)
cachedField = new ShortField();
else if (fieldClass == int.class)
cachedField = new IntField();
else if (fieldClass == long.class)
cachedField = new LongField();
else if (fieldClass == float.class)
cachedField = new FloatField();
else if (fieldClass == double.class)
cachedField = new DoubleField();
else {
if (TRACE)
trace("kryo", "ObjectField1");
cachedField = new AsmObjectField(this);
}
} else if (fieldClass == String.class
&& (!kryo.getReferences() || !kryo.getReferenceResolver().useReferences(String.class))) {
cachedField = new StringField();
} else {
if(TRACE) trace("kryo", "ObjectField2");
cachedField = new AsmObjectField(this);
}
} else if(!useAsmBackend) {
if (fieldClass.isPrimitive()) {
if (fieldClass == boolean.class)
cachedField = new UnsafeBooleanField(field);
else if (fieldClass == byte.class)
cachedField = new UnsafeByteField(field);
else if (fieldClass == char.class)
cachedField = new UnsafeCharField(field);
else if (fieldClass == short.class)
cachedField = new UnsafeShortField(field);
else if (fieldClass == int.class)
cachedField = new UnsafeIntField(field);
else if (fieldClass == long.class)
cachedField = new UnsafeLongField(field);
else if (fieldClass == float.class)
cachedField = new UnsafeFloatField(field);
else if (fieldClass == double.class)
cachedField = new UnsafeDoubleField(field);
else {
if (TRACE)
trace("kryo", "ObjectField1");
cachedField = new UnsafeObjectField(this);
}
} else if (fieldClass == String.class
&& (!kryo.getReferences() || !kryo.getReferenceResolver().useReferences(String.class))) {
cachedField = new UnsafeStringField(field);
} else {
if(TRACE) trace("kryo", "ObjectField2");
cachedField = new UnsafeObjectField(this);
}
} else {
if(TRACE) trace("kryo", "ObjectField3");
cachedField = new ObjectField(this);
if(fieldGenerics != null)
((ObjectField)cachedField).generics = fieldGenerics;
else {
Class[] cachedFieldGenerics = kryo.getGenerics(fieldGenericType);
((ObjectField) cachedField).generics = cachedFieldGenerics;
if(TRACE) trace("kryo", "Field generics: " + Arrays.toString(cachedFieldGenerics));
}
}
if(fieldGenerics != null && cachedField instanceof FieldSerializer.ObjectField) {
if (fieldGenerics[0] != null) {
// If any information about concrete types for generic arguments of current field's type
// was deriver, remember it.
((ObjectField) cachedField).generics = fieldGenerics;
if (TRACE)
trace("kryo",
"Field generics: " + Arrays.toString(fieldGenerics));
}
}
cachedField.field = field;
cachedField.optimizeInts = optimizeInts;
if(!useAsmBackend) {
cachedField.offset = unsafe().objectFieldOffset(field);
}
cachedField.access = (FieldAccess) access;
cachedField.accessIndex = accessIndex;
cachedField.canBeNull = fieldsCanBeNull && !fieldClass.isPrimitive() && !field.isAnnotationPresent(NotNull.class);
// Always use the same serializer for this field if the field's class is final.
if (kryo.isFinal(fieldClass) || fixedFieldTypes) cachedField.valueClass = fieldClass;
return cachedField;
}
|
diff --git a/src/org/zaproxy/zap/extension/ascanrulesBeta/SQLInjection.java b/src/org/zaproxy/zap/extension/ascanrulesBeta/SQLInjection.java
index d0ce0be..a76ef01 100644
--- a/src/org/zaproxy/zap/extension/ascanrulesBeta/SQLInjection.java
+++ b/src/org/zaproxy/zap/extension/ascanrulesBeta/SQLInjection.java
@@ -1,597 +1,597 @@
/**
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* 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.zaproxy.zap.extension.ascanrulesBeta;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.core.scanner.AbstractAppParamPlugin;
import org.parosproxy.paros.core.scanner.Alert;
import org.parosproxy.paros.core.scanner.Category;
import org.parosproxy.paros.network.HttpMessage;
/**
* TODO: implement stacked query check, since it is actually supported on more RDBMS drivers / frameworks than not (MySQL on PHP/ASP does not by default, but can).
* PostgreSQL and MSSQL on ASP, ASP.NET, and PHP *do* support it, for instance. It's better to put the code here and try it for all RDBMSs as a result.
* Use the following variables: doStackedBased, doStackedMaxRequests, countStackedBasedRequests
* TODO: implement checks in Header fields (currently does Cookie values, form fields, and url parameters)
* TODO: change the Alert Titles.
* TODO: if the argument is reflected back in the HTML output, the boolean based logic will not detect an alert
* (because the HTML results of argument values "id=1" will not be the same as for "id=1 and 1=1")
* TODO: add "<param>*2/2" check to the Logic based ones (for integer parameter values).. if the result is the same, it might be a SQL Injection
* TODO: implement mode checks (Mode.standard, Mode.safe, Mode.protected) for 2.* using "implements SessionChangedListener"
*
* The SQLInjection plugin identifies SQL Injection vulnerabilities
* note the ordering of checks, for efficiency is :
* 1) Error based
* 2) Boolean Based
* 3) UNION based
* 4) Stacked (TODO: implement stacked based)
* 5) Blind/Time Based (RDBMS specific, so not done here right now)
*
* @author Colm O'Flaherty, Encription Ireland Ltd
*/
public class SQLInjection extends AbstractAppParamPlugin {
//what do we do at each attack strength?
//(some SQL Injection vulns would be picked up by multiple types of checks, and we skip out after the first alert for a URL)
private boolean doErrorBased = true;
private boolean doBooleanBased=true;
private boolean doUnionBased = true;
private boolean doStackedBased = true; //TODO: use in the stacked based implementation
//how many requests can we fire for each method? will be set depending on the attack strength
private int doErrorMaxRequests = 0;
private int doBooleanMaxRequests = 0;
private int doUnionMaxRequests = 0;
private int doStackedMaxRequests = 0; //TODO: use in the stacked based implementation
/**
* generic one-line comment. Various RDBMS Documentation suggests that this syntax works with almost every single RDBMS considered here
*/
public static final String SQL_ONE_LINE_COMMENT = " -- ";
/**
* used to inject to check for SQL errors: some basic SQL metacharacters ordered so as to maximise SQL errors
* Note that we do separate runs for each family of characters, in case one family are filtered out, the others might still
* get past
*/
private static final String [] SQL_CHECK_ERR = {"'", "\"", ")", "(", "NULL", "'\""};
/**
* create a map of SQL related error message fragments, and map them back to the RDBMS that they are associated with
* keep the ordering the same as the order in which the values are inserted, to allow the more (subjectively judged) common cases to be tested first
* Note: these should represent actual (driver level) error messages for things like syntax error,
* otherwise we are simply guessing that the string should/might occur.
*/
private static final Map<String, String> SQL_ERROR_TO_DBMS = new LinkedHashMap<>();
static {
//DONE: we have implemented a MySQL specific scanner. See SQLInjectionMySQL
SQL_ERROR_TO_DBMS.put("com.mysql.jdbc.exceptions", "MySQL");
SQL_ERROR_TO_DBMS.put("org.gjt.mm.mysql", "MySQL");
//TODO: implement a plugin that uses Microsoft SQL specific functionality to detect SQL Injection vulnerabilities
SQL_ERROR_TO_DBMS.put("com.microsoft.sqlserver.jdbc", "Microsoft SQL Server");
SQL_ERROR_TO_DBMS.put("com.microsoft.jdbc", "Microsoft SQL Server");
SQL_ERROR_TO_DBMS.put("com.inet.tds", "Microsoft SQL Server");
SQL_ERROR_TO_DBMS.put("com.microsoft.sqlserver.jdbc", "Microsoft SQL Server");
SQL_ERROR_TO_DBMS.put("com.ashna.jturbo", "Microsoft SQL Server");
SQL_ERROR_TO_DBMS.put("weblogic.jdbc.mssqlserver", "Microsoft SQL Server");
SQL_ERROR_TO_DBMS.put("[Microsoft]", "Microsoft SQL Server");
SQL_ERROR_TO_DBMS.put("[SQLServer]", "Microsoft SQL Server");
SQL_ERROR_TO_DBMS.put("[SQLServer 2000 Driver for JDBC]", "Microsoft SQL Server");
SQL_ERROR_TO_DBMS.put("net.sourceforge.jtds.jdbc", "Microsoft SQL Server"); //see also Sybase. could be either!
//DONE: we have implemented an Oracle specific scanner. See SQLInjectionOracle
SQL_ERROR_TO_DBMS.put("oracle.jdbc", "Oracle");
SQL_ERROR_TO_DBMS.put("SQLSTATE[HY", "Oracle");
SQL_ERROR_TO_DBMS.put("ORA-00933", "Oracle");
SQL_ERROR_TO_DBMS.put("ORA-06512", "Oracle"); //indicates the line number of an error
SQL_ERROR_TO_DBMS.put("SQL command not properly ended", "Oracle");
SQL_ERROR_TO_DBMS.put("ORA-00942", "Oracle"); //table or view does not exist
SQL_ERROR_TO_DBMS.put("ORA-29257", "Oracle"); //host unknown
SQL_ERROR_TO_DBMS.put("ORA-00932", "Oracle"); //inconsistent datatypes
//TODO: implement a plugin that uses DB2 specific functionality to detect SQL Injection vulnerabilities
SQL_ERROR_TO_DBMS.put("com.ibm.db2.jcc", "IBM DB2");
SQL_ERROR_TO_DBMS.put("COM.ibm.db2.jdbc", "IBM DB2");
//DONE: we have implemented a PostgreSQL specific scanner. See SQLInjectionPostgresql
SQL_ERROR_TO_DBMS.put("org.postgresql.util.PSQLException", "PostgreSQL");
SQL_ERROR_TO_DBMS.put("org.postgresql", "PostgreSQL");
//TODO: implement a plugin that uses Sybase specific functionality to detect SQL Injection vulnerabilities
//Note: this plugin would also detect Microsoft SQL Server vulnerabilities, due to common syntax.
SQL_ERROR_TO_DBMS.put("com.sybase.jdbc", "Sybase");
SQL_ERROR_TO_DBMS.put("com.sybase.jdbc2.jdbc", "Sybase");
SQL_ERROR_TO_DBMS.put("com.sybase.jdbc3.jdbc", "Sybase");
SQL_ERROR_TO_DBMS.put("net.sourceforge.jtds.jdbc", "Sybase"); //see also Microsoft SQL Server. could be either!
//TODO: implement a plugin that uses Informix specific functionality to detect SQL Injection vulnerabilities
SQL_ERROR_TO_DBMS.put("com.informix.jdbc", "Informix");
//TODO: implement a plugin that uses Firebird specific functionality to detect SQL Injection vulnerabilities
SQL_ERROR_TO_DBMS.put("org.firebirdsql.jdbc", "Firebird");
//TODO: implement a plugin that uses IDS Server specific functionality to detect SQL Injection vulnerabilities
SQL_ERROR_TO_DBMS.put("ids.sql", "IDS Server");
//TODO: implement a plugin that uses InstantDB specific functionality to detect SQL Injection vulnerabilities
SQL_ERROR_TO_DBMS.put("org.enhydra.instantdb.jdbc", "InstantDB");
SQL_ERROR_TO_DBMS.put("jdbc.idb", "InstantDB");
//TODO: implement a plugin that uses Interbase specific functionality to detect SQL Injection vulnerabilities
SQL_ERROR_TO_DBMS.put("interbase.interclient", "Interbase");
//DONE: we have implemented a Hypersonic specific scanner. See SQLInjectionHypersonic
SQL_ERROR_TO_DBMS.put("org.hsql", "Hypersonic SQL");
SQL_ERROR_TO_DBMS.put("hSql.", "Hypersonic SQL");
SQL_ERROR_TO_DBMS.put("Unexpected token , requires FROM in statement", "Hypersonic SQL");
SQL_ERROR_TO_DBMS.put("Unexpected end of command in statement", "Hypersonic SQL");
SQL_ERROR_TO_DBMS.put("Column count does not match in statement", "Hypersonic SQL"); //TODO: too generic to leave in???
SQL_ERROR_TO_DBMS.put("Table not found in statement", "Hypersonic SQL"); //TODO: too generic to leave in???
SQL_ERROR_TO_DBMS.put("Unexpected token:", "Hypersonic SQL"); //TODO: too generic to leave in???
//TODO: implement a plugin that uses Sybase SQL Anywhere specific functionality to detect SQL Injection vulnerabilities
SQL_ERROR_TO_DBMS.put("sybase.jdbc.sqlanywhere", "Sybase SQL Anywhere");
//TODO: implement a plugin that uses PointBase specific functionality to detect SQL Injection vulnerabilities
SQL_ERROR_TO_DBMS.put("com.pointbase.jdbc", "Pointbase");
//TODO: implement a plugin that uses Cloudbase specific functionality to detect SQL Injection vulnerabilities
SQL_ERROR_TO_DBMS.put("db2j.","Cloudscape");
SQL_ERROR_TO_DBMS.put("COM.cloudscape","Cloudscape");
SQL_ERROR_TO_DBMS.put("RmiJdbc.RJDriver","Cloudscape");
//TODO: implement a plugin that uses Ingres specific functionality to detect SQL Injection vulnerabilities
SQL_ERROR_TO_DBMS.put("com.ingres.jdbc", "Ingres");
SQL_ERROR_TO_DBMS.put("com.ibatis.common.jdbc", "Generic SQL RDBMS");
SQL_ERROR_TO_DBMS.put("org.hibernate", "Generic SQL RDBMS");
SQL_ERROR_TO_DBMS.put("sun.jdbc.odbc", "Generic SQL RDBMS");
SQL_ERROR_TO_DBMS.put("[ODBC Driver Manager]", "Generic SQL RDBMS");
}
/**
* always true statement for comparison in boolean based SQL injection check
*/
private static final String[] SQL_LOGIC_AND = {
" AND 1=1",
"' AND '1'='1",
"\" AND \"1\"=\"1",
};
/**
* always false statement for comparison in boolean based SQL injection check
*/
private static final String[] SQL_LOGIC_AND_FALSE = {
" AND 1=2",
"' AND '1'='2",
"\" AND \"1\"=\"2",
};
/**
* always true statement for comparison if no output is returned from AND in boolean based SQL injection check
* Note that, if necessary, the code also tries a variant with the one-line comment " -- " appended to the end.
*/
private static final String[] SQL_LOGIC_OR_TRUE = {
" OR 1=1",
"' OR '1'='1",
"\" OR \"1\"=\"1",
};
/**
* generic UNION statements. Hoping these will cause a specific error message that we will recognise
*/
private static String [] SQL_UNION_APPENDAGES = {
" UNION ALL select NULL" + SQL_ONE_LINE_COMMENT,
"' UNION ALL select NULL" + SQL_ONE_LINE_COMMENT,
"\" UNION ALL select NULL" + SQL_ONE_LINE_COMMENT,
") UNION ALL select NULL" + SQL_ONE_LINE_COMMENT,
"') UNION ALL select NULL" + SQL_ONE_LINE_COMMENT,
"\") UNION ALL select NULL" + SQL_ONE_LINE_COMMENT,
};
/*
SQL UNION error messages for various RDBMSs. The more, the merrier.
*/
private static final Map<String, String> SQL_UNION_ERROR_TO_DBMS = new LinkedHashMap<>();
static {
SQL_UNION_ERROR_TO_DBMS.put("The used SELECT statements have a different number of columns", "MySQL");
SQL_UNION_ERROR_TO_DBMS.put("each UNION query must have the same number of columns", "PostgreSQL");
SQL_UNION_ERROR_TO_DBMS.put("All queries in an SQL statement containing a UNION operator must have an equal number of expressions in their target lists", "Microsoft SQL Server");
SQL_UNION_ERROR_TO_DBMS.put("query block has incorrect number of result columns", "Oracle");
SQL_UNION_ERROR_TO_DBMS.put("ORA-01789", "Oracle");
SQL_UNION_ERROR_TO_DBMS.put("Unexpected end of command in statement", "Hypersonic SQL"); //needs a table name in a UNION query. Like Oracle?
SQL_UNION_ERROR_TO_DBMS.put("Column count does not match in statement", "Hypersonic SQL");
//TODO: add other specific UNION based error messages for Union here: PostgreSQL, Sybase, DB2, Informix, etc
}
/**
* plugin dependencies
*/
private static final String[] dependency = {};
/**
* for logging.
*/
private static Logger log = Logger.getLogger(SQLInjection.class);
/**
* determines if we should output Debug level logging
*/
private boolean debugEnabled = log.isDebugEnabled();
@Override
public int getId() {
return 40018;
}
@Override
public String getName() {
return Constant.messages.getString("ascanbeta.sqlinjection.name");
}
@Override
public String[] getDependency() {
return dependency;
}
@Override
public String getDescription() {
return Constant.messages.getString("ascanbeta.sqlinjection.desc");
}
@Override
public int getCategory() {
return Category.INJECTION;
}
@Override
public String getSolution() {
return Constant.messages.getString("ascanbeta.sqlinjection.soln");
}
@Override
public String getReference() {
return Constant.messages.getString("ascanbeta.sqlinjection.refs");
}
/* initialise
* Note that this method gets called each time the scanner is called.
*/
@Override
public void init() {
if ( this.debugEnabled ) log.debug("Initialising");
//DEBUG only
//this.setAttackStrength(AttackStrength.LOW);
//set up what we are allowed to do, depending on the attack strength that was set.
if ( this.getAttackStrength() == AttackStrength.LOW ) {
doErrorBased=true; doErrorMaxRequests=2;
doUnionBased=false; doUnionMaxRequests=0;
doStackedBased=false; doStackedMaxRequests=0;
doBooleanBased=false; doBooleanMaxRequests=0;
} else if ( this.getAttackStrength() == AttackStrength.MEDIUM) {
doErrorBased=true; doErrorMaxRequests=5;
doUnionBased=true; doUnionMaxRequests=5;
doStackedBased=true; doStackedMaxRequests=5;
doBooleanBased=false; doBooleanMaxRequests=0;
} else if ( this.getAttackStrength() == AttackStrength.HIGH) {
doErrorBased=true; doErrorMaxRequests=10;
doUnionBased=true; doUnionMaxRequests=10;
doStackedBased=true; doStackedMaxRequests=10;
doBooleanBased=true; doBooleanMaxRequests=10;
} else if ( this.getAttackStrength() == AttackStrength.INSANE) {
doErrorBased=true; doErrorMaxRequests=100;
doUnionBased=true; doUnionMaxRequests=100;
doStackedBased=true; doStackedMaxRequests=100;
doBooleanBased=true; doBooleanMaxRequests=100;
}
}
/**
* scans for SQL Injection vulnerabilities
*/
@Override
public void scan(HttpMessage msg, String param, String value) {
//as soon as we find a single SQL injection on the url, skip out. Do not look for SQL injection on a subsequent parameter on the same URL
//for performance reasons.
boolean sqlInjectionFoundForUrl = false;
try {
//reinitialise the count for each type of request, for each parameter. We will be sticking to limits defined in the attach strength logic
int countErrorBasedRequests = 0;
int countBooleanBasedRequests = 0;
int countUnionBasedRequests = 0;
int countStackedBasedRequests = 0; //TODO: use in the stacked based queries implementation
//Check 1: Check for Error Based SQL Injection (actual error messages).
//for each SQL metacharacter combination to try
for (int sqlErrorStringIndex = 0;
sqlErrorStringIndex < SQL_CHECK_ERR.length && !sqlInjectionFoundForUrl && doErrorBased && countErrorBasedRequests < doErrorMaxRequests ;
sqlErrorStringIndex++) {
//new message for each value we attack with
HttpMessage msg1 = getNewMsg();
String sqlErrValue = SQL_CHECK_ERR[sqlErrorStringIndex];
setParameter(msg1, param, sqlErrValue);
//send the message with the modified parameters
sendAndReceive(msg1);
countErrorBasedRequests++;
//now check the results against each pattern in turn, to try to identify a database, or even better: a specific database.
//Note: do NOT check the HTTP error code just yet, as the result could come back with one of various codes.
Iterator<String> errorPatternIterator = SQL_ERROR_TO_DBMS.keySet().iterator();
while (errorPatternIterator.hasNext() && ! sqlInjectionFoundForUrl) {
String errorPatternKey = errorPatternIterator.next();
String errorPatternRDBMS = SQL_ERROR_TO_DBMS.get(errorPatternKey);
//Note: must escape the strings, in case they contain strings like "[Microsoft], which would be interpreted as regular character class regexps"
Pattern errorPattern = Pattern.compile("\\Q"+errorPatternKey+"\\E", PATTERN_PARAM);
//if the "error message" occurs in the result of sending the modified query, but did NOT occur in the original result of the original query
//then we may may have a SQL Injection vulnerability
StringBuilder sb = new StringBuilder();
if (! matchBodyPattern(getBaseMsg(), errorPattern, null) && matchBodyPattern(msg1, errorPattern, sb)) {
//Likely a SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.errorbased.extrainfo", errorPatternRDBMS, errorPatternKey);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - Error Based - " + errorPatternRDBMS, getDescription(),
null,
param, sb.toString(),
extraInfo, getSolution(), msg1);
//log it, as the RDBMS may be useful to know later (in subsequent checks, when we need to determine RDBMS specific behaviour, for instance)
getKb().add(getBaseMsg().getRequestHeader().getURI(), "sql/"+errorPatternRDBMS, Boolean.TRUE);
sqlInjectionFoundForUrl = true;
continue;
}
} //end of the loop to check for RDBMS specific error messages
} //for each of the SQL_CHECK_ERR values (SQL metacharacters)
//Check 2: boolean based checks.
//the check goes like so:
// append " and 1 = 1" to the param. Send the query. Check the results. Hopefully they match the original results from the unmodified query,
// *suggesting* (but not yet definitely) that we have successfully modified the query, (hopefully not gotten an error message),
// and have gotten the same results back, which is what you would expect if you added the constraint " and 1 = 1" to most (but not every) SQL query.
// So was it a fluke that we got the same results back from the modified query? Perhaps the original query returned 0 rows, so adding any number of
// constraints would change nothing? It is still a possibility!
// check to see if we can change the original parameter again to *restrict* the scope of the query using an AND with an always false condition (AND_ERR)
// (decreasing the results back to nothing), or to *broaden* the scope of the query using an OR with an always true condition (AND_OR)
// (increasing the results).
// If we can successfully alter the results to our requirements, by one means or another, we have found a SQL Injection vulnerability.
//Some additional complications: assume there are 2 HTML parameters: username and password, and the SQL constructed is like so:
// select * from username where user = "$user" and password = "$password"
// and lets assume we successfully know the type of the user field, via SQL_OR_TRUE value '" OR "1"="1' (single quotes not part of the value)
// we still have the problem that the actual SQL executed would look like so:
// select * from username where user = "" OR "1"="1" and password = "whateveritis"
// Since the password field is still taken into account (by virtue of the AND condition on the password column), and we only inject one parameter at a time,
// we are still not in control.
// the solution is simple: add an end-of-line comment to the field added in (in this example: the user field), so that the SQL becomes:
// select * from username where user = "" OR "1"="1" -- and password = "whateveritis"
// the result is that any additional constraints are commented out, and the last condition to have any effect is the one whose
// HTTP param we are manipulating.
// Note also that because this comment only needs to be added to the "SQL_OR_TRUE" and not to the equivalent SQL_AND_FALSE, because of the nature of the OR
// and AND conditions in SQL.
// Corollary: If a particular RDBMS does not offer the ability to comment out the remainder of a line, we will not attempt to comment out anything in the query
// and we will simply hope that the *last* constraint in the SQL query is constructed from a HTTP parameter under our control.
if (this.debugEnabled) log.debug("Doing Check 2, since check 1 did not match for "+ getBaseMsg().getRequestHeader().getURI());
String mResBodyNormal = getBaseMsg().getResponseBody().toString();
//boolean booleanBasedSqlInjectionFoundForParam = false;
//try each of the AND syntax values in turn.
//Which one is successful will depend on the column type of the table/view column into which we are injecting the SQL.
for (int i=0;
i<SQL_LOGIC_AND.length && ! sqlInjectionFoundForUrl && doBooleanBased &&
countBooleanBasedRequests < doBooleanMaxRequests;
i++) {
//needs a new message for each type of AND to be issued
HttpMessage msg2 = getNewMsg();
String sqlBooleanAndValue = value + SQL_LOGIC_AND[i];
String sqlBooleanAndFalseValue = value + SQL_LOGIC_AND_FALSE[i];
setParameter(msg2, param, sqlBooleanAndValue);
//send the AND with an additional TRUE statement tacked onto the end. Hopefully it will return the same results as the original (to find a vulnerability)
sendAndReceive(msg2);
countBooleanBasedRequests++;
//String resBodyAND = stripOff(msg2.getResponseBody().toString(), SQL_LOGIC_AND[i]);
String resBodyAND = msg2.getResponseBody().toString();
//if the results of the "AND 1=1" match the original query, we may be onto something.
if (resBodyAND.compareTo(mResBodyNormal) == 0) {
if (this.debugEnabled) log.debug("Check 2, AND condition ["+sqlBooleanAndValue+"] matched original results for "+ getBaseMsg().getRequestHeader().getURI());
//so they match. Was it a fluke? See if we get the same result by tacking on "AND 1 = 2" to the original
HttpMessage msg2_and_false = getNewMsg();
- setParameter(msg2, param, sqlBooleanAndFalseValue);
+ setParameter(msg2_and_false, param, sqlBooleanAndFalseValue);
sendAndReceive(msg2_and_false);
countBooleanBasedRequests++;
//String resBodyANDFalse = stripOff(msg2_and_false.getResponseBody().toString(), SQL_LOGIC_AND_FALSE[i]);
String resBodyANDFalse = msg2_and_false.getResponseBody().toString();
// build an always false AND query. Result should be different to prove the SQL works.
if (resBodyANDFalse.compareTo(mResBodyNormal) != 0) {
if (this.debugEnabled) log.debug("Check 2, AND FALSE condition ["+sqlBooleanAndFalseValue+"] differed from original for "+ getBaseMsg().getRequestHeader().getURI());
//it's different (suggesting that the "AND 1 = 2" appended on gave different results because it restricted the data set to nothing
//Likely a SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.booleanbased.extrainfo", sqlBooleanAndValue, sqlBooleanAndFalseValue);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - Boolean Based", getDescription(),
null, //url
param, sqlBooleanAndValue,
extraInfo, getSolution(), msg2);
//TODO: do we need this?
//getKb().add(getBaseMsg().getRequestHeader().getURI(), "sql/and", Boolean.TRUE);
sqlInjectionFoundForUrl= true;
//booleanBasedSqlInjectionFoundForParam = true; //causes us to skip past the other entries in SQL_AND. Only one will expose a vuln for a given param, since the database column is of only 1 type
continue; //to the next entry in SQL_AND
} else {
//the first value to try..
String orValue = value + SQL_LOGIC_OR_TRUE[i];
//this is where that comment comes in handy: if the RDBMS supports one-line comments, add one in to attempt to ensure that the
//condition becomes one that is effectively always true, returning ALL data (or as much as possible), allowing us to pinpoint the SQL Injection
if (this.debugEnabled) log.debug("Check 2, AND FALSE condition ["+sqlBooleanAndFalseValue+"] SAME as original (requiring OR TRUE check) for "+ getBaseMsg().getRequestHeader().getURI());
HttpMessage msg2_or_true = getNewMsg();
- setParameter(msg2_or_true, param, sqlBooleanAndFalseValue);
+ setParameter(msg2_or_true, param, orValue);
sendAndReceive(msg2_or_true);
countBooleanBasedRequests++;
//String resBodyORTrue = stripOff(msg2_or_true.getResponseBody().toString(), orValue);
String resBodyORTrue = msg2_or_true.getResponseBody().toString();
int compareOrToOriginal = resBodyORTrue.compareTo(mResBodyNormal);
//if the results for the OR are the same as the original, try again with the OR statement, but this time, include a one-line comment at the end
//to nullify the effect of everything that follows. This is an often necessary (depending on the nature of the original SQL statement) attempt
//to see if we have the results of the page under our control by manipulating this parameter
if (compareOrToOriginal == 0) {
//need to append in the first character of the SQL_OR_TRUE to close off any open quotes before commenting out the remainder
orValue = value + SQL_LOGIC_OR_TRUE[i] + SQL_LOGIC_OR_TRUE[i].substring(0, 1) + SQL_ONE_LINE_COMMENT;
HttpMessage msg2_or_true_comment = getNewMsg();
setParameter(msg2_or_true_comment, param, orValue);
sendAndReceive(msg2_or_true_comment);
countBooleanBasedRequests++;
//and re-set the variable with the results of trying the commented OR
compareOrToOriginal = resBodyORTrue.compareTo(mResBodyNormal);
}
//Note: do NOT put an else condition before this. This logic *always* needs to happen after the previous check.
if (compareOrToOriginal != 0) {
if (this.debugEnabled) log.debug("Check 2, OR TRUE condition ["+orValue+"] different to original for "+ getBaseMsg().getRequestHeader().getURI());
//it's different (suggesting that the "OR 1 = 1" appended on gave different results because it broadened the data set from nothing to something
//Likely a SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.booleanbased.extrainfo", sqlBooleanAndValue, orValue);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - Boolean Based", getDescription(),
null, //url
param, orValue,
extraInfo, getSolution(), msg2);
sqlInjectionFoundForUrl = true;
//booleanBasedSqlInjectionFoundForParam = true; //causes us to skip past the other entries in SQL_AND. Only one will expose a vuln for a given param, since the database column is of only 1 type
continue;
}
}
} //if the results of the "AND 1=1" match the original query, we may be onto something.
}
//end of check 2
//TODO: fix the numbering of the checks..
//Check 4: UNION based
//for each SQL UNION combination to try
for (int sqlUnionStringIndex = 0;
sqlUnionStringIndex < SQL_UNION_APPENDAGES.length && !sqlInjectionFoundForUrl && doUnionBased && countUnionBasedRequests < doUnionMaxRequests;
sqlUnionStringIndex++) {
//new message for each value we attack with
HttpMessage msg3 = getNewMsg();
String sqlUnionValue = value+ SQL_UNION_APPENDAGES[sqlUnionStringIndex];
setParameter(msg3, param, sqlUnionValue);
//send the message with the modified parameters
sendAndReceive(msg3);
countUnionBasedRequests++;
//now check the results.. look first for UNION specific error messages in the output that were not there in the original output
//and failing that, look for generic RDBMS specific error messages
//TODO: maybe also try looking at a differentiation based approach?? Prone to false positives though.
Iterator<String> errorPatternUnionIterator = SQL_UNION_ERROR_TO_DBMS.keySet().iterator();
while (errorPatternUnionIterator.hasNext() && ! sqlInjectionFoundForUrl) {
String errorPatternKey = errorPatternUnionIterator.next();
String errorPatternRDBMS = SQL_UNION_ERROR_TO_DBMS.get(errorPatternKey);
//Note: must escape the strings, in case they contain strings like "[Microsoft], which would be interpreted as regular character class regexps"
Pattern errorPattern = Pattern.compile("\\Q"+errorPatternKey+"\\E", PATTERN_PARAM);
//if the "error message" occurs in the result of sending the modified query, but did NOT occur in the original result of the original query
//then we may may have a SQL Injection vulnerability
StringBuilder sb = new StringBuilder();
if (! matchBodyPattern(getBaseMsg(), errorPattern, null) && matchBodyPattern(msg3, errorPattern, sb)) {
//Likely a UNION Based SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.unionbased.extrainfo", errorPatternRDBMS, errorPatternKey);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - UNION Based - " + errorPatternRDBMS, getDescription(),
getBaseMsg().getRequestHeader().getURI().getURI(), //url
param, sb.toString(),
extraInfo, getSolution(), msg3);
//log it, as the RDBMS may be useful to know later (in subsequent checks, when we need to determine RDBMS specific behaviour, for instance)
getKb().add(getBaseMsg().getRequestHeader().getURI(), "sql/"+errorPatternRDBMS, Boolean.TRUE);
sqlInjectionFoundForUrl = true;
continue;
}
} //end of the loop to check for RDBMS specific UNION error messages
} ////for each SQL UNION combination to try
//end of check 4
} catch (Exception e) {
//Do not try to internationalise this.. we need an error message in any event..
//if it's in English, it's still better than not having it at all.
log.error("An error occurred checking a url for SQL Injection vulnerabilities", e);
}
}
@Override
public int getRisk() {
return Alert.RISK_HIGH;
}
}
| false | true | public void scan(HttpMessage msg, String param, String value) {
//as soon as we find a single SQL injection on the url, skip out. Do not look for SQL injection on a subsequent parameter on the same URL
//for performance reasons.
boolean sqlInjectionFoundForUrl = false;
try {
//reinitialise the count for each type of request, for each parameter. We will be sticking to limits defined in the attach strength logic
int countErrorBasedRequests = 0;
int countBooleanBasedRequests = 0;
int countUnionBasedRequests = 0;
int countStackedBasedRequests = 0; //TODO: use in the stacked based queries implementation
//Check 1: Check for Error Based SQL Injection (actual error messages).
//for each SQL metacharacter combination to try
for (int sqlErrorStringIndex = 0;
sqlErrorStringIndex < SQL_CHECK_ERR.length && !sqlInjectionFoundForUrl && doErrorBased && countErrorBasedRequests < doErrorMaxRequests ;
sqlErrorStringIndex++) {
//new message for each value we attack with
HttpMessage msg1 = getNewMsg();
String sqlErrValue = SQL_CHECK_ERR[sqlErrorStringIndex];
setParameter(msg1, param, sqlErrValue);
//send the message with the modified parameters
sendAndReceive(msg1);
countErrorBasedRequests++;
//now check the results against each pattern in turn, to try to identify a database, or even better: a specific database.
//Note: do NOT check the HTTP error code just yet, as the result could come back with one of various codes.
Iterator<String> errorPatternIterator = SQL_ERROR_TO_DBMS.keySet().iterator();
while (errorPatternIterator.hasNext() && ! sqlInjectionFoundForUrl) {
String errorPatternKey = errorPatternIterator.next();
String errorPatternRDBMS = SQL_ERROR_TO_DBMS.get(errorPatternKey);
//Note: must escape the strings, in case they contain strings like "[Microsoft], which would be interpreted as regular character class regexps"
Pattern errorPattern = Pattern.compile("\\Q"+errorPatternKey+"\\E", PATTERN_PARAM);
//if the "error message" occurs in the result of sending the modified query, but did NOT occur in the original result of the original query
//then we may may have a SQL Injection vulnerability
StringBuilder sb = new StringBuilder();
if (! matchBodyPattern(getBaseMsg(), errorPattern, null) && matchBodyPattern(msg1, errorPattern, sb)) {
//Likely a SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.errorbased.extrainfo", errorPatternRDBMS, errorPatternKey);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - Error Based - " + errorPatternRDBMS, getDescription(),
null,
param, sb.toString(),
extraInfo, getSolution(), msg1);
//log it, as the RDBMS may be useful to know later (in subsequent checks, when we need to determine RDBMS specific behaviour, for instance)
getKb().add(getBaseMsg().getRequestHeader().getURI(), "sql/"+errorPatternRDBMS, Boolean.TRUE);
sqlInjectionFoundForUrl = true;
continue;
}
} //end of the loop to check for RDBMS specific error messages
} //for each of the SQL_CHECK_ERR values (SQL metacharacters)
//Check 2: boolean based checks.
//the check goes like so:
// append " and 1 = 1" to the param. Send the query. Check the results. Hopefully they match the original results from the unmodified query,
// *suggesting* (but not yet definitely) that we have successfully modified the query, (hopefully not gotten an error message),
// and have gotten the same results back, which is what you would expect if you added the constraint " and 1 = 1" to most (but not every) SQL query.
// So was it a fluke that we got the same results back from the modified query? Perhaps the original query returned 0 rows, so adding any number of
// constraints would change nothing? It is still a possibility!
// check to see if we can change the original parameter again to *restrict* the scope of the query using an AND with an always false condition (AND_ERR)
// (decreasing the results back to nothing), or to *broaden* the scope of the query using an OR with an always true condition (AND_OR)
// (increasing the results).
// If we can successfully alter the results to our requirements, by one means or another, we have found a SQL Injection vulnerability.
//Some additional complications: assume there are 2 HTML parameters: username and password, and the SQL constructed is like so:
// select * from username where user = "$user" and password = "$password"
// and lets assume we successfully know the type of the user field, via SQL_OR_TRUE value '" OR "1"="1' (single quotes not part of the value)
// we still have the problem that the actual SQL executed would look like so:
// select * from username where user = "" OR "1"="1" and password = "whateveritis"
// Since the password field is still taken into account (by virtue of the AND condition on the password column), and we only inject one parameter at a time,
// we are still not in control.
// the solution is simple: add an end-of-line comment to the field added in (in this example: the user field), so that the SQL becomes:
// select * from username where user = "" OR "1"="1" -- and password = "whateveritis"
// the result is that any additional constraints are commented out, and the last condition to have any effect is the one whose
// HTTP param we are manipulating.
// Note also that because this comment only needs to be added to the "SQL_OR_TRUE" and not to the equivalent SQL_AND_FALSE, because of the nature of the OR
// and AND conditions in SQL.
// Corollary: If a particular RDBMS does not offer the ability to comment out the remainder of a line, we will not attempt to comment out anything in the query
// and we will simply hope that the *last* constraint in the SQL query is constructed from a HTTP parameter under our control.
if (this.debugEnabled) log.debug("Doing Check 2, since check 1 did not match for "+ getBaseMsg().getRequestHeader().getURI());
String mResBodyNormal = getBaseMsg().getResponseBody().toString();
//boolean booleanBasedSqlInjectionFoundForParam = false;
//try each of the AND syntax values in turn.
//Which one is successful will depend on the column type of the table/view column into which we are injecting the SQL.
for (int i=0;
i<SQL_LOGIC_AND.length && ! sqlInjectionFoundForUrl && doBooleanBased &&
countBooleanBasedRequests < doBooleanMaxRequests;
i++) {
//needs a new message for each type of AND to be issued
HttpMessage msg2 = getNewMsg();
String sqlBooleanAndValue = value + SQL_LOGIC_AND[i];
String sqlBooleanAndFalseValue = value + SQL_LOGIC_AND_FALSE[i];
setParameter(msg2, param, sqlBooleanAndValue);
//send the AND with an additional TRUE statement tacked onto the end. Hopefully it will return the same results as the original (to find a vulnerability)
sendAndReceive(msg2);
countBooleanBasedRequests++;
//String resBodyAND = stripOff(msg2.getResponseBody().toString(), SQL_LOGIC_AND[i]);
String resBodyAND = msg2.getResponseBody().toString();
//if the results of the "AND 1=1" match the original query, we may be onto something.
if (resBodyAND.compareTo(mResBodyNormal) == 0) {
if (this.debugEnabled) log.debug("Check 2, AND condition ["+sqlBooleanAndValue+"] matched original results for "+ getBaseMsg().getRequestHeader().getURI());
//so they match. Was it a fluke? See if we get the same result by tacking on "AND 1 = 2" to the original
HttpMessage msg2_and_false = getNewMsg();
setParameter(msg2, param, sqlBooleanAndFalseValue);
sendAndReceive(msg2_and_false);
countBooleanBasedRequests++;
//String resBodyANDFalse = stripOff(msg2_and_false.getResponseBody().toString(), SQL_LOGIC_AND_FALSE[i]);
String resBodyANDFalse = msg2_and_false.getResponseBody().toString();
// build an always false AND query. Result should be different to prove the SQL works.
if (resBodyANDFalse.compareTo(mResBodyNormal) != 0) {
if (this.debugEnabled) log.debug("Check 2, AND FALSE condition ["+sqlBooleanAndFalseValue+"] differed from original for "+ getBaseMsg().getRequestHeader().getURI());
//it's different (suggesting that the "AND 1 = 2" appended on gave different results because it restricted the data set to nothing
//Likely a SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.booleanbased.extrainfo", sqlBooleanAndValue, sqlBooleanAndFalseValue);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - Boolean Based", getDescription(),
null, //url
param, sqlBooleanAndValue,
extraInfo, getSolution(), msg2);
//TODO: do we need this?
//getKb().add(getBaseMsg().getRequestHeader().getURI(), "sql/and", Boolean.TRUE);
sqlInjectionFoundForUrl= true;
//booleanBasedSqlInjectionFoundForParam = true; //causes us to skip past the other entries in SQL_AND. Only one will expose a vuln for a given param, since the database column is of only 1 type
continue; //to the next entry in SQL_AND
} else {
//the first value to try..
String orValue = value + SQL_LOGIC_OR_TRUE[i];
//this is where that comment comes in handy: if the RDBMS supports one-line comments, add one in to attempt to ensure that the
//condition becomes one that is effectively always true, returning ALL data (or as much as possible), allowing us to pinpoint the SQL Injection
if (this.debugEnabled) log.debug("Check 2, AND FALSE condition ["+sqlBooleanAndFalseValue+"] SAME as original (requiring OR TRUE check) for "+ getBaseMsg().getRequestHeader().getURI());
HttpMessage msg2_or_true = getNewMsg();
setParameter(msg2_or_true, param, sqlBooleanAndFalseValue);
sendAndReceive(msg2_or_true);
countBooleanBasedRequests++;
//String resBodyORTrue = stripOff(msg2_or_true.getResponseBody().toString(), orValue);
String resBodyORTrue = msg2_or_true.getResponseBody().toString();
int compareOrToOriginal = resBodyORTrue.compareTo(mResBodyNormal);
//if the results for the OR are the same as the original, try again with the OR statement, but this time, include a one-line comment at the end
//to nullify the effect of everything that follows. This is an often necessary (depending on the nature of the original SQL statement) attempt
//to see if we have the results of the page under our control by manipulating this parameter
if (compareOrToOriginal == 0) {
//need to append in the first character of the SQL_OR_TRUE to close off any open quotes before commenting out the remainder
orValue = value + SQL_LOGIC_OR_TRUE[i] + SQL_LOGIC_OR_TRUE[i].substring(0, 1) + SQL_ONE_LINE_COMMENT;
HttpMessage msg2_or_true_comment = getNewMsg();
setParameter(msg2_or_true_comment, param, orValue);
sendAndReceive(msg2_or_true_comment);
countBooleanBasedRequests++;
//and re-set the variable with the results of trying the commented OR
compareOrToOriginal = resBodyORTrue.compareTo(mResBodyNormal);
}
//Note: do NOT put an else condition before this. This logic *always* needs to happen after the previous check.
if (compareOrToOriginal != 0) {
if (this.debugEnabled) log.debug("Check 2, OR TRUE condition ["+orValue+"] different to original for "+ getBaseMsg().getRequestHeader().getURI());
//it's different (suggesting that the "OR 1 = 1" appended on gave different results because it broadened the data set from nothing to something
//Likely a SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.booleanbased.extrainfo", sqlBooleanAndValue, orValue);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - Boolean Based", getDescription(),
null, //url
param, orValue,
extraInfo, getSolution(), msg2);
sqlInjectionFoundForUrl = true;
//booleanBasedSqlInjectionFoundForParam = true; //causes us to skip past the other entries in SQL_AND. Only one will expose a vuln for a given param, since the database column is of only 1 type
continue;
}
}
} //if the results of the "AND 1=1" match the original query, we may be onto something.
}
//end of check 2
//TODO: fix the numbering of the checks..
//Check 4: UNION based
//for each SQL UNION combination to try
for (int sqlUnionStringIndex = 0;
sqlUnionStringIndex < SQL_UNION_APPENDAGES.length && !sqlInjectionFoundForUrl && doUnionBased && countUnionBasedRequests < doUnionMaxRequests;
sqlUnionStringIndex++) {
//new message for each value we attack with
HttpMessage msg3 = getNewMsg();
String sqlUnionValue = value+ SQL_UNION_APPENDAGES[sqlUnionStringIndex];
setParameter(msg3, param, sqlUnionValue);
//send the message with the modified parameters
sendAndReceive(msg3);
countUnionBasedRequests++;
//now check the results.. look first for UNION specific error messages in the output that were not there in the original output
//and failing that, look for generic RDBMS specific error messages
//TODO: maybe also try looking at a differentiation based approach?? Prone to false positives though.
Iterator<String> errorPatternUnionIterator = SQL_UNION_ERROR_TO_DBMS.keySet().iterator();
while (errorPatternUnionIterator.hasNext() && ! sqlInjectionFoundForUrl) {
String errorPatternKey = errorPatternUnionIterator.next();
String errorPatternRDBMS = SQL_UNION_ERROR_TO_DBMS.get(errorPatternKey);
//Note: must escape the strings, in case they contain strings like "[Microsoft], which would be interpreted as regular character class regexps"
Pattern errorPattern = Pattern.compile("\\Q"+errorPatternKey+"\\E", PATTERN_PARAM);
//if the "error message" occurs in the result of sending the modified query, but did NOT occur in the original result of the original query
//then we may may have a SQL Injection vulnerability
StringBuilder sb = new StringBuilder();
if (! matchBodyPattern(getBaseMsg(), errorPattern, null) && matchBodyPattern(msg3, errorPattern, sb)) {
//Likely a UNION Based SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.unionbased.extrainfo", errorPatternRDBMS, errorPatternKey);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - UNION Based - " + errorPatternRDBMS, getDescription(),
getBaseMsg().getRequestHeader().getURI().getURI(), //url
param, sb.toString(),
extraInfo, getSolution(), msg3);
//log it, as the RDBMS may be useful to know later (in subsequent checks, when we need to determine RDBMS specific behaviour, for instance)
getKb().add(getBaseMsg().getRequestHeader().getURI(), "sql/"+errorPatternRDBMS, Boolean.TRUE);
sqlInjectionFoundForUrl = true;
continue;
}
} //end of the loop to check for RDBMS specific UNION error messages
} ////for each SQL UNION combination to try
//end of check 4
} catch (Exception e) {
//Do not try to internationalise this.. we need an error message in any event..
//if it's in English, it's still better than not having it at all.
log.error("An error occurred checking a url for SQL Injection vulnerabilities", e);
}
}
| public void scan(HttpMessage msg, String param, String value) {
//as soon as we find a single SQL injection on the url, skip out. Do not look for SQL injection on a subsequent parameter on the same URL
//for performance reasons.
boolean sqlInjectionFoundForUrl = false;
try {
//reinitialise the count for each type of request, for each parameter. We will be sticking to limits defined in the attach strength logic
int countErrorBasedRequests = 0;
int countBooleanBasedRequests = 0;
int countUnionBasedRequests = 0;
int countStackedBasedRequests = 0; //TODO: use in the stacked based queries implementation
//Check 1: Check for Error Based SQL Injection (actual error messages).
//for each SQL metacharacter combination to try
for (int sqlErrorStringIndex = 0;
sqlErrorStringIndex < SQL_CHECK_ERR.length && !sqlInjectionFoundForUrl && doErrorBased && countErrorBasedRequests < doErrorMaxRequests ;
sqlErrorStringIndex++) {
//new message for each value we attack with
HttpMessage msg1 = getNewMsg();
String sqlErrValue = SQL_CHECK_ERR[sqlErrorStringIndex];
setParameter(msg1, param, sqlErrValue);
//send the message with the modified parameters
sendAndReceive(msg1);
countErrorBasedRequests++;
//now check the results against each pattern in turn, to try to identify a database, or even better: a specific database.
//Note: do NOT check the HTTP error code just yet, as the result could come back with one of various codes.
Iterator<String> errorPatternIterator = SQL_ERROR_TO_DBMS.keySet().iterator();
while (errorPatternIterator.hasNext() && ! sqlInjectionFoundForUrl) {
String errorPatternKey = errorPatternIterator.next();
String errorPatternRDBMS = SQL_ERROR_TO_DBMS.get(errorPatternKey);
//Note: must escape the strings, in case they contain strings like "[Microsoft], which would be interpreted as regular character class regexps"
Pattern errorPattern = Pattern.compile("\\Q"+errorPatternKey+"\\E", PATTERN_PARAM);
//if the "error message" occurs in the result of sending the modified query, but did NOT occur in the original result of the original query
//then we may may have a SQL Injection vulnerability
StringBuilder sb = new StringBuilder();
if (! matchBodyPattern(getBaseMsg(), errorPattern, null) && matchBodyPattern(msg1, errorPattern, sb)) {
//Likely a SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.errorbased.extrainfo", errorPatternRDBMS, errorPatternKey);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - Error Based - " + errorPatternRDBMS, getDescription(),
null,
param, sb.toString(),
extraInfo, getSolution(), msg1);
//log it, as the RDBMS may be useful to know later (in subsequent checks, when we need to determine RDBMS specific behaviour, for instance)
getKb().add(getBaseMsg().getRequestHeader().getURI(), "sql/"+errorPatternRDBMS, Boolean.TRUE);
sqlInjectionFoundForUrl = true;
continue;
}
} //end of the loop to check for RDBMS specific error messages
} //for each of the SQL_CHECK_ERR values (SQL metacharacters)
//Check 2: boolean based checks.
//the check goes like so:
// append " and 1 = 1" to the param. Send the query. Check the results. Hopefully they match the original results from the unmodified query,
// *suggesting* (but not yet definitely) that we have successfully modified the query, (hopefully not gotten an error message),
// and have gotten the same results back, which is what you would expect if you added the constraint " and 1 = 1" to most (but not every) SQL query.
// So was it a fluke that we got the same results back from the modified query? Perhaps the original query returned 0 rows, so adding any number of
// constraints would change nothing? It is still a possibility!
// check to see if we can change the original parameter again to *restrict* the scope of the query using an AND with an always false condition (AND_ERR)
// (decreasing the results back to nothing), or to *broaden* the scope of the query using an OR with an always true condition (AND_OR)
// (increasing the results).
// If we can successfully alter the results to our requirements, by one means or another, we have found a SQL Injection vulnerability.
//Some additional complications: assume there are 2 HTML parameters: username and password, and the SQL constructed is like so:
// select * from username where user = "$user" and password = "$password"
// and lets assume we successfully know the type of the user field, via SQL_OR_TRUE value '" OR "1"="1' (single quotes not part of the value)
// we still have the problem that the actual SQL executed would look like so:
// select * from username where user = "" OR "1"="1" and password = "whateveritis"
// Since the password field is still taken into account (by virtue of the AND condition on the password column), and we only inject one parameter at a time,
// we are still not in control.
// the solution is simple: add an end-of-line comment to the field added in (in this example: the user field), so that the SQL becomes:
// select * from username where user = "" OR "1"="1" -- and password = "whateveritis"
// the result is that any additional constraints are commented out, and the last condition to have any effect is the one whose
// HTTP param we are manipulating.
// Note also that because this comment only needs to be added to the "SQL_OR_TRUE" and not to the equivalent SQL_AND_FALSE, because of the nature of the OR
// and AND conditions in SQL.
// Corollary: If a particular RDBMS does not offer the ability to comment out the remainder of a line, we will not attempt to comment out anything in the query
// and we will simply hope that the *last* constraint in the SQL query is constructed from a HTTP parameter under our control.
if (this.debugEnabled) log.debug("Doing Check 2, since check 1 did not match for "+ getBaseMsg().getRequestHeader().getURI());
String mResBodyNormal = getBaseMsg().getResponseBody().toString();
//boolean booleanBasedSqlInjectionFoundForParam = false;
//try each of the AND syntax values in turn.
//Which one is successful will depend on the column type of the table/view column into which we are injecting the SQL.
for (int i=0;
i<SQL_LOGIC_AND.length && ! sqlInjectionFoundForUrl && doBooleanBased &&
countBooleanBasedRequests < doBooleanMaxRequests;
i++) {
//needs a new message for each type of AND to be issued
HttpMessage msg2 = getNewMsg();
String sqlBooleanAndValue = value + SQL_LOGIC_AND[i];
String sqlBooleanAndFalseValue = value + SQL_LOGIC_AND_FALSE[i];
setParameter(msg2, param, sqlBooleanAndValue);
//send the AND with an additional TRUE statement tacked onto the end. Hopefully it will return the same results as the original (to find a vulnerability)
sendAndReceive(msg2);
countBooleanBasedRequests++;
//String resBodyAND = stripOff(msg2.getResponseBody().toString(), SQL_LOGIC_AND[i]);
String resBodyAND = msg2.getResponseBody().toString();
//if the results of the "AND 1=1" match the original query, we may be onto something.
if (resBodyAND.compareTo(mResBodyNormal) == 0) {
if (this.debugEnabled) log.debug("Check 2, AND condition ["+sqlBooleanAndValue+"] matched original results for "+ getBaseMsg().getRequestHeader().getURI());
//so they match. Was it a fluke? See if we get the same result by tacking on "AND 1 = 2" to the original
HttpMessage msg2_and_false = getNewMsg();
setParameter(msg2_and_false, param, sqlBooleanAndFalseValue);
sendAndReceive(msg2_and_false);
countBooleanBasedRequests++;
//String resBodyANDFalse = stripOff(msg2_and_false.getResponseBody().toString(), SQL_LOGIC_AND_FALSE[i]);
String resBodyANDFalse = msg2_and_false.getResponseBody().toString();
// build an always false AND query. Result should be different to prove the SQL works.
if (resBodyANDFalse.compareTo(mResBodyNormal) != 0) {
if (this.debugEnabled) log.debug("Check 2, AND FALSE condition ["+sqlBooleanAndFalseValue+"] differed from original for "+ getBaseMsg().getRequestHeader().getURI());
//it's different (suggesting that the "AND 1 = 2" appended on gave different results because it restricted the data set to nothing
//Likely a SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.booleanbased.extrainfo", sqlBooleanAndValue, sqlBooleanAndFalseValue);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - Boolean Based", getDescription(),
null, //url
param, sqlBooleanAndValue,
extraInfo, getSolution(), msg2);
//TODO: do we need this?
//getKb().add(getBaseMsg().getRequestHeader().getURI(), "sql/and", Boolean.TRUE);
sqlInjectionFoundForUrl= true;
//booleanBasedSqlInjectionFoundForParam = true; //causes us to skip past the other entries in SQL_AND. Only one will expose a vuln for a given param, since the database column is of only 1 type
continue; //to the next entry in SQL_AND
} else {
//the first value to try..
String orValue = value + SQL_LOGIC_OR_TRUE[i];
//this is where that comment comes in handy: if the RDBMS supports one-line comments, add one in to attempt to ensure that the
//condition becomes one that is effectively always true, returning ALL data (or as much as possible), allowing us to pinpoint the SQL Injection
if (this.debugEnabled) log.debug("Check 2, AND FALSE condition ["+sqlBooleanAndFalseValue+"] SAME as original (requiring OR TRUE check) for "+ getBaseMsg().getRequestHeader().getURI());
HttpMessage msg2_or_true = getNewMsg();
setParameter(msg2_or_true, param, orValue);
sendAndReceive(msg2_or_true);
countBooleanBasedRequests++;
//String resBodyORTrue = stripOff(msg2_or_true.getResponseBody().toString(), orValue);
String resBodyORTrue = msg2_or_true.getResponseBody().toString();
int compareOrToOriginal = resBodyORTrue.compareTo(mResBodyNormal);
//if the results for the OR are the same as the original, try again with the OR statement, but this time, include a one-line comment at the end
//to nullify the effect of everything that follows. This is an often necessary (depending on the nature of the original SQL statement) attempt
//to see if we have the results of the page under our control by manipulating this parameter
if (compareOrToOriginal == 0) {
//need to append in the first character of the SQL_OR_TRUE to close off any open quotes before commenting out the remainder
orValue = value + SQL_LOGIC_OR_TRUE[i] + SQL_LOGIC_OR_TRUE[i].substring(0, 1) + SQL_ONE_LINE_COMMENT;
HttpMessage msg2_or_true_comment = getNewMsg();
setParameter(msg2_or_true_comment, param, orValue);
sendAndReceive(msg2_or_true_comment);
countBooleanBasedRequests++;
//and re-set the variable with the results of trying the commented OR
compareOrToOriginal = resBodyORTrue.compareTo(mResBodyNormal);
}
//Note: do NOT put an else condition before this. This logic *always* needs to happen after the previous check.
if (compareOrToOriginal != 0) {
if (this.debugEnabled) log.debug("Check 2, OR TRUE condition ["+orValue+"] different to original for "+ getBaseMsg().getRequestHeader().getURI());
//it's different (suggesting that the "OR 1 = 1" appended on gave different results because it broadened the data set from nothing to something
//Likely a SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.booleanbased.extrainfo", sqlBooleanAndValue, orValue);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - Boolean Based", getDescription(),
null, //url
param, orValue,
extraInfo, getSolution(), msg2);
sqlInjectionFoundForUrl = true;
//booleanBasedSqlInjectionFoundForParam = true; //causes us to skip past the other entries in SQL_AND. Only one will expose a vuln for a given param, since the database column is of only 1 type
continue;
}
}
} //if the results of the "AND 1=1" match the original query, we may be onto something.
}
//end of check 2
//TODO: fix the numbering of the checks..
//Check 4: UNION based
//for each SQL UNION combination to try
for (int sqlUnionStringIndex = 0;
sqlUnionStringIndex < SQL_UNION_APPENDAGES.length && !sqlInjectionFoundForUrl && doUnionBased && countUnionBasedRequests < doUnionMaxRequests;
sqlUnionStringIndex++) {
//new message for each value we attack with
HttpMessage msg3 = getNewMsg();
String sqlUnionValue = value+ SQL_UNION_APPENDAGES[sqlUnionStringIndex];
setParameter(msg3, param, sqlUnionValue);
//send the message with the modified parameters
sendAndReceive(msg3);
countUnionBasedRequests++;
//now check the results.. look first for UNION specific error messages in the output that were not there in the original output
//and failing that, look for generic RDBMS specific error messages
//TODO: maybe also try looking at a differentiation based approach?? Prone to false positives though.
Iterator<String> errorPatternUnionIterator = SQL_UNION_ERROR_TO_DBMS.keySet().iterator();
while (errorPatternUnionIterator.hasNext() && ! sqlInjectionFoundForUrl) {
String errorPatternKey = errorPatternUnionIterator.next();
String errorPatternRDBMS = SQL_UNION_ERROR_TO_DBMS.get(errorPatternKey);
//Note: must escape the strings, in case they contain strings like "[Microsoft], which would be interpreted as regular character class regexps"
Pattern errorPattern = Pattern.compile("\\Q"+errorPatternKey+"\\E", PATTERN_PARAM);
//if the "error message" occurs in the result of sending the modified query, but did NOT occur in the original result of the original query
//then we may may have a SQL Injection vulnerability
StringBuilder sb = new StringBuilder();
if (! matchBodyPattern(getBaseMsg(), errorPattern, null) && matchBodyPattern(msg3, errorPattern, sb)) {
//Likely a UNION Based SQL Injection. Raise it
String extraInfo = Constant.messages.getString("ascanbeta.sqlinjection.alert.unionbased.extrainfo", errorPatternRDBMS, errorPatternKey);
//raise the alert
bingo(Alert.RISK_HIGH, Alert.WARNING, getName() + " - UNION Based - " + errorPatternRDBMS, getDescription(),
getBaseMsg().getRequestHeader().getURI().getURI(), //url
param, sb.toString(),
extraInfo, getSolution(), msg3);
//log it, as the RDBMS may be useful to know later (in subsequent checks, when we need to determine RDBMS specific behaviour, for instance)
getKb().add(getBaseMsg().getRequestHeader().getURI(), "sql/"+errorPatternRDBMS, Boolean.TRUE);
sqlInjectionFoundForUrl = true;
continue;
}
} //end of the loop to check for RDBMS specific UNION error messages
} ////for each SQL UNION combination to try
//end of check 4
} catch (Exception e) {
//Do not try to internationalise this.. we need an error message in any event..
//if it's in English, it's still better than not having it at all.
log.error("An error occurred checking a url for SQL Injection vulnerabilities", e);
}
}
|
diff --git a/jetty/src/main/java/org/mortbay/jetty/servlet/ServletHandler.java b/jetty/src/main/java/org/mortbay/jetty/servlet/ServletHandler.java
index 270477827..c874df1b6 100644
--- a/jetty/src/main/java/org/mortbay/jetty/servlet/ServletHandler.java
+++ b/jetty/src/main/java/org/mortbay/jetty/servlet/ServletHandler.java
@@ -1,892 +1,894 @@
// ========================================================================
// Copyright 199-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
package org.mortbay.jetty.servlet;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.component.Container;
import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.RetryRequest;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.jetty.handler.WrappedHandler;
import org.mortbay.log.Log;
import org.mortbay.util.LazyList;
import org.mortbay.util.MultiException;
import org.mortbay.util.MultiMap;
import org.mortbay.util.URIUtil;
/* --------------------------------------------------------------------- */
/** Servlet HttpHandler.
* This handler maps requests to servlets that implement the
* javax.servlet.http.HttpServlet API.
* <P>
* This handler does not implement the full J2EE features and is intended to
* be used when a full web application is not required. Specifically filters
* and request wrapping are not supported.
* <P>
* If a SessionManager is not added to the handler before it is
* initialized, then a HashSessionManager with a standard
* java.util.Random generator is created.
* <P>
* @see org.mortbay.jetty.servlet.WebAppContext
* @author Greg Wilkins
*/
public class ServletHandler extends AbstractHandler
{
private static String __AllowString="GET, HEAD, POST, OPTIONS, TRACE";
/* ------------------------------------------------------------ */
public static final String __DEFAULT_SERVLET="default";
public static final String __J_S_CONTEXT_TEMPDIR="javax.servlet.context.tempdir";
public static final String __J_S_ERROR_EXCEPTION="javax.servlet.error.exception";
public static final String __J_S_ERROR_EXCEPTION_TYPE="javax.servlet.error.exception_type";
public static final String __J_S_ERROR_MESSAGE="javax.servlet.error.message";
public static final String __J_S_ERROR_REQUEST_URI="javax.servlet.error.request_uri";
public static final String __J_S_ERROR_SERVLET_NAME="javax.servlet.error.servlet_name";
public static final String __J_S_ERROR_STATUS_CODE="javax.servlet.error.status_code";
/* ------------------------------------------------------------ */
private ContextHandler _contextHandler;
private ContextHandler.Context _servletContext;
private FilterHolder[] _filters;
private FilterMapping[] _filterMappings;
private boolean _filterChainsCached=true;
private ServletHolder[] _servlets;
private ServletMapping[] _servletMappings;
private boolean _initializeAtStart=true;
private transient Map _filterNameMap;
private transient List _filterPathMappings;
private transient MultiMap _filterNameMappings;
private transient Map _servletNameMap;
private transient PathMap _servletPathMap;
protected transient HashMap _chainCache[];
protected transient HashMap _namedChainCache[];
/* ------------------------------------------------------------ */
/** Constructor.
*/
public ServletHandler()
{
}
/* ------------------------------------------------------------ */
/*
* @see org.mortbay.jetty.handler.AbstractHandler#setServer(org.mortbay.jetty.Server)
*/
public void setServer(Server server)
{
if (getServer()!=null && getServer()!=server)
{
getServer().getContainer().update(this, _filters, null, "filter");
getServer().getContainer().update(this, _filterMappings, null, "filterMapping");
getServer().getContainer().update(this, _servlets, null, "servlet");
getServer().getContainer().update(this, _servletMappings, null, "servletMapping");
}
if (server!=null && getServer()!=server)
{
server.getContainer().update(this, null, _filters, "filter");
server.getContainer().update(this, null, _filterMappings, "filterMapping");
server.getContainer().update(this, null, _servlets, "servlet");
server.getContainer().update(this, null, _servletMappings, "servletMapping");
}
super.setServer(server);
}
/* ----------------------------------------------------------------- */
protected synchronized void doStart()
throws Exception
{
_servletContext=ContextHandler.getCurrentContext();
_contextHandler=_servletContext.getContextHandler();
updateMappings();
if (isInitializeAtStart())
initialize();
if(_filterChainsCached && _filters!=null && _filters.length>0)
{
_chainCache= new HashMap[]{null,new HashMap(),new HashMap(),null,new HashMap(),null,null,null,new HashMap()};
_namedChainCache=new HashMap[]{null,null,new HashMap(),null,new HashMap(),null,null,null,new HashMap()};
}
super.doStart();
}
/* ----------------------------------------------------------------- */
protected synchronized void doStop()
throws Exception
{
super.doStop();
// Stop filters
if (_filters!=null)
{
for (int i=_filters.length; i-->0;)
{
try { _filters[i].stop(); }catch(Exception e){Log.warn(Log.EXCEPTION,e);}
}
}
// Stop servlets
if (_servlets!=null)
{
for (int i=_servlets.length; i-->0;)
{
try { _servlets[i].stop(); }catch(Exception e){Log.warn(Log.EXCEPTION,e);}
}
}
_filterNameMap=null;
_filterPathMappings=null;
_filterNameMappings=null;
_servletNameMap=null;
_servletPathMap=null;
_chainCache=null;
_namedChainCache=null;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the contextLog.
*/
public Object getContextLog()
{
return null;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the filterMappings.
*/
public FilterMapping[] getFilterMappings()
{
return _filterMappings;
}
/* ------------------------------------------------------------ */
/** Get Filters.
* @return Array of defined servlets
*/
public FilterHolder[] getFilters()
{
return _filters;
}
/* ------------------------------------------------------------ */
/** ServletHolder matching path.
* @param pathInContext Path within _context.
* @return PathMap Entries pathspec to ServletHolder
*/
private PathMap.Entry getHolderEntry(String pathInContext)
{
return _servletPathMap.getMatch(pathInContext);
}
/* ------------------------------------------------------------ */
/**
* @param ipath
* @return
*/
public RequestDispatcher getRequestDispatcher(String uriInContext)
{
if (uriInContext == null)
return null;
if (!uriInContext.startsWith("/"))
return null;
try
{
String query=null;
int q=0;
if ((q=uriInContext.indexOf('?'))>0)
{
query=uriInContext.substring(q+1);
uriInContext=uriInContext.substring(0,q);
}
if ((q=uriInContext.indexOf(';'))>0)
uriInContext=uriInContext.substring(0,q);
String pathInContext=URIUtil.canonicalPath(URIUtil.decodePath(uriInContext));
String uri=URIUtil.addPaths(_contextHandler.getContextPath(), uriInContext);
return new Dispatcher(_contextHandler, uri, pathInContext, query);
}
catch(Exception e)
{
Log.ignore(e);
}
return null;
}
/* ------------------------------------------------------------ */
public ServletContext getServletContext()
{
return _servletContext;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the servletMappings.
*/
public ServletMapping[] getServletMappings()
{
return _servletMappings;
}
/* ------------------------------------------------------------ */
/** Get Servlets.
* @return Array of defined servlets
*/
public ServletHolder[] getServlets()
{
return _servlets;
}
/* ------------------------------------------------------------ */
/*
* @see org.mortbay.jetty.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
*/
public boolean handle(String target, HttpServletRequest request,HttpServletResponse response, int type)
throws IOException
{
if (!isStarted())
return false;
// Get the base requests
Request base_request=(request instanceof Request)?((Request)request):HttpConnection.getCurrentConnection().getRequest();
String old_servlet_path=null;
String old_path_info=null;
try
{
old_servlet_path=base_request.getServletPath();
old_path_info=base_request.getPathInfo();
ServletHolder servlet_holder=null;
FilterChain chain=null;
// find the servlet
if (target.startsWith("/"))
{
// Look for the servlet by path
PathMap.Entry entry=getHolderEntry(target);
if (entry!=null)
{
servlet_holder=(ServletHolder)entry.getValue();
if(Log.isDebugEnabled())Log.debug("servlet="+servlet_holder);
String servlet_path_spec=(String)entry.getKey();
String servlet_path=entry.getMapped()!=null?entry.getMapped():PathMap.pathMatch(servlet_path_spec,target);
String path_info=PathMap.pathInfo(servlet_path_spec,target);
if (type==INCLUDE)
{
base_request.setAttribute(Dispatcher.__INCLUDE_SERVLET_PATH,servlet_path);
base_request.setAttribute(Dispatcher.__INCLUDE_PATH_INFO, path_info);
}
else
{
base_request.setServletPath(servlet_path);
base_request.setPathInfo(path_info);
}
if (servlet_holder!=null && _filterMappings!=null && _filterMappings.length>0)
chain=getFilterChain(type, target, servlet_holder);
}
}
else
{
// look for a servlet by name!
servlet_holder=(ServletHolder)_servletNameMap.get(target);
if (servlet_holder!=null && _filterMappings!=null && _filterMappings.length>0)
chain=getFilterChain(type, null,servlet_holder);
}
if (Log.isDebugEnabled())
{
Log.debug("chain="+chain);
Log.debug("servelet holder="+servlet_holder);
}
// Do the filter/handling thang
if (chain!=null)
chain.doFilter(request, response);
else if (servlet_holder != null)
servlet_holder.handle(request,response);
else
notFound(request, response);
}
catch(RetryRequest e)
{
throw e;
}
catch(Exception e)
{
Throwable th=e;
while (th instanceof ServletException)
{
Throwable cause=((ServletException)th).getRootCause();
if (cause==th || cause==null)
break;
th=cause;
}
/* TODO
if (th instanceof HttpException)
throw (HttpException)th;
if (th instanceof EOFException)
throw (IOException)th;
else */
if (Log.isDebugEnabled() || !( th instanceof java.io.IOException))
{
Log.warn(request.getRequestURI()+": ",th);
if(Log.isDebugEnabled())
{
Log.warn(request.getRequestURI()+": ",th);
Log.debug(request.toString());
}
}
// TODO clean up
Log.warn(request.getRequestURI(), th);
// TODO httpResponse.getHttpConnection().forceClose();
if (!response.isCommitted())
{
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,th.getClass());
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,th);
if (th instanceof UnavailableException)
{
UnavailableException ue = (UnavailableException)th;
if (ue.isPermanent())
response.sendError(HttpServletResponse.SC_NOT_FOUND,th.getMessage());
else
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,th.getMessage());
}
else
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,th.getMessage());
}
else
if(Log.isDebugEnabled())Log.debug("Response already committed for handling "+th);
}
catch(Error e)
{
Log.warn("Error for "+request.getRequestURI(),e);
if(Log.isDebugEnabled())Log.debug(request.toString());
// TODO httpResponse.getHttpConnection().forceClose();
if (!response.isCommitted())
{
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,e.getClass());
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage());
}
else
if(Log.isDebugEnabled())Log.debug("Response already committed for handling ",e);
}
finally
{
if (type!=INCLUDE)
- base_request.setServletPath(old_servlet_path);
- base_request.setPathInfo(old_path_info);
+ {
+ base_request.setServletPath(old_servlet_path);
+ base_request.setPathInfo(old_path_info);
+ }
}
return true;
}
/* ------------------------------------------------------------ */
private FilterChain getFilterChain(int requestType, String pathInContext, ServletHolder servletHolder)
{
String key=pathInContext==null?servletHolder.getName():pathInContext;
if (_filterChainsCached && _chainCache!=null)
{
synchronized(this)
{
if(_chainCache[requestType].containsKey(key))
return (FilterChain)_chainCache[requestType].get(key);
}
}
// Build list of filters
Object filters= null;
// Path filters
if (pathInContext!=null && _filterPathMappings!=null)
{
for (int i= 0; i < _filterPathMappings.size(); i++)
{
FilterMapping mapping = (FilterMapping)_filterPathMappings.get(i);
if (mapping.appliesTo(pathInContext, requestType))
filters= LazyList.add(filters, mapping.getFilterHolder());
}
}
// Servlet name filters
if (servletHolder != null && _filterNameMappings!=null && _filterNameMappings.size() > 0)
{
// Servlet name filters
if (_filterNameMappings.size() > 0)
{
Object o= _filterNameMappings.get(servletHolder.getName());
for (int i=0; i<LazyList.size(o);i++)
{
FilterMapping mapping = (FilterMapping)LazyList.get(o,i);
if (mapping.appliesTo(requestType))
filters=LazyList.add(filters,mapping.getFilterHolder());
}
o= _filterNameMappings.get("*");
for (int i=0; i<LazyList.size(o);i++)
{
FilterMapping mapping = (FilterMapping)LazyList.get(o,i);
if (mapping.appliesTo(requestType))
filters=LazyList.add(filters,mapping.getFilterHolder());
}
}
}
if (filters==null)
return null;
FilterChain chain = null;
if (_filterChainsCached)
{
synchronized(this)
{
if (LazyList.size(filters) > 0)
chain= new CachedChain(filters, servletHolder);
_chainCache[requestType].put(key,chain);
}
}
else if (LazyList.size(filters) > 0)
chain = new Chain(filters, servletHolder);
return chain;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the initializeAtStart.
*/
public boolean isInitializeAtStart()
{
return _initializeAtStart;
}
/* ------------------------------------------------------------ */
/**
* @param initializeAtStart The initializeAtStart to set.
*/
public void setInitializeAtStart(boolean initializeAtStart)
{
_initializeAtStart = initializeAtStart;
}
/* ------------------------------------------------------------ */
/** Initialize filters and load-on-startup servlets.
* Called automatically from start if autoInitializeServlet is true.
*/
public void initialize()
throws Exception
{
MultiException mx = new MultiException();
// Start filters
if (_filters!=null)
{
for (int i=_filters.length; i-->0;)
_filters[i].start();
}
if (_servlets!=null)
{
// Sort and Initialize servlets
ServletHolder[] servlets = (ServletHolder[])_servlets.clone();
Arrays.sort(servlets);
for (int i=0; i<servlets.length; i++)
{
try
{
if (servlets[i].getClassName()==null && servlets[i].getForcedPath()!=null)
{
ServletHolder forced_holder = (ServletHolder)_servletPathMap.match(servlets[i].getForcedPath());
if (forced_holder==null)
{
mx.add(new IllegalStateException("No servlet for "+servlets[i].getForcedPath()));
continue;
}
servlets[i].setClassName(forced_holder.getClassName());
}
servlets[i].start();
}
catch(Exception e)
{
Log.debug(Log.EXCEPTION,e);
mx.add(e);
}
}
mx.ifExceptionThrow();
}
}
/* ------------------------------------------------------------ */
/**
* @return Returns the filterChainsCached.
*/
public boolean isFilterChainsCached()
{
return _filterChainsCached;
}
/* ------------------------------------------------------------ */
protected synchronized void updateMappings()
{
// Map servlet names to holders
if (_servlets==null)
{
_servletNameMap=null;
}
else
{
HashMap nm = new HashMap();
// update the maps
for (int i=0;i<_servlets.length;i++)
{
nm.put(_servlets[i].getName(),_servlets[i]);
_servlets[i].setServletHandler(this);
}
_servletNameMap=nm;
}
// Map servlet paths to holders
if (_servletMappings==null || _servletNameMap==null)
{
_servletPathMap=null;
}
else
{
PathMap pm = new PathMap();
// update the maps
for (int i=0;i<_servletMappings.length;i++)
{
ServletHolder servlet_holder = (ServletHolder)_servletNameMap.get(_servletMappings[i].getServletName());
if (servlet_holder==null)
throw new IllegalStateException("No such servlet: "+_servletMappings[i].getServletName());
else if (_servletMappings[i].getPathSpecs()!=null)
{
String[] pathSpecs = _servletMappings[i].getPathSpecs();
for (int j=0;j<pathSpecs.length;j++)
if (pathSpecs[j]!=null)
pm.put(pathSpecs[j],servlet_holder);
}
}
_servletPathMap=pm;
}
// update filter name map
if (_filters==null)
{
_filterNameMap=null;
}
else
{
HashMap nm = new HashMap();
for (int i=0;i<_filters.length;i++)
{
nm.put(_filters[i].getName(),_filters[i]);
_filters[i].setServletHandler(this);
}
_filterNameMap=nm;
}
// update filter mappings
if (_filterMappings==null)
{
_filterPathMappings=null;
_filterNameMappings=null;
}
else
{
_filterPathMappings=new ArrayList();
_filterNameMappings=new MultiMap();
for (int i=0;i<_filterMappings.length;i++)
{
FilterHolder filter_holder = (FilterHolder)_filterNameMap.get(_filterMappings[i].getFilterName());
if (filter_holder==null)
throw new IllegalStateException("No filter named "+_filterMappings[i].getFilterName());
_filterMappings[i].setFilterHolder(filter_holder);
if (_filterMappings[i].getPathSpecs()!=null)
_filterPathMappings.add(_filterMappings[i]);
if (_filterMappings[i].getServletNames()!=null)
{
String[] names=_filterMappings[i].getServletNames();
for (int j=0;j<names.length;j++)
{
if (names[j]!=null)
_filterNameMappings.add(names[j], _filterMappings[i]);
}
}
}
}
if (Log.isDebugEnabled())
{
Log.debug("filterNameMap="+_filterNameMap);
Log.debug("pathFilters="+_filterPathMappings);
Log.debug("servletFilterMap="+_filterNameMappings);
Log.debug("servletPathMap="+_servletPathMap);
Log.debug("servletNameMap="+_servletNameMap);
}
try
{
if (isStarted())
initialize();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
/* ------------------------------------------------------------ */
protected void notFound(HttpServletRequest request,
HttpServletResponse response)
throws IOException
{
if(Log.isDebugEnabled())Log.debug("Not Found "+request.getRequestURI());
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
/* ------------------------------------------------------------ */
/**
* @param contextLog The contextLog to set.
*/
public void setContextLog(Object contextLog)
{
// TODO
}
/* ------------------------------------------------------------ */
/**
* @param filterChainsCached The filterChainsCached to set.
*/
public void setFilterChainsCached(boolean filterChainsCached)
{
_filterChainsCached = filterChainsCached;
}
/* ------------------------------------------------------------ */
/**
* @param filterMappings The filterMappings to set.
*/
public void setFilterMappings(FilterMapping[] filterMappings)
{
if (getServer()!=null)
getServer().getContainer().update(this,_filterMappings,filterMappings,"filterMapping");
_filterMappings = filterMappings;
if (isStarted())
updateMappings();
}
/* ------------------------------------------------------------ */
/** Get Filters.
* @return Array of defined servlets
*/
public synchronized void setFilters(FilterHolder[] holders)
{
if (getServer()!=null)
getServer().getContainer().update(this,_filters,holders,"filter");
_filters=holders;
}
/* ------------------------------------------------------------ */
/**
* @param servletMappings The servletMappings to set.
*/
public void setServletMappings(ServletMapping[] servletMappings)
{
if (getServer()!=null)
getServer().getContainer().update(this,_servletMappings,servletMappings,"servletMapping");
_servletMappings = servletMappings;
if (isStarted())
updateMappings();
}
/* ------------------------------------------------------------ */
/** Get Servlets.
* @return Array of defined servlets
*/
public synchronized void setServlets(ServletHolder[] holders)
{
if (getServer()!=null)
getServer().getContainer().update(this,_servlets,holders,"servlet");
_servlets=holders;
updateMappings();
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private class CachedChain implements FilterChain
{
FilterHolder _filterHolder;
CachedChain _next;
ServletHolder _servletHolder;
/* ------------------------------------------------------------ */
CachedChain(Object filters, ServletHolder servletHolder)
{
if (LazyList.size(filters)>0)
{
_filterHolder=(FilterHolder)LazyList.get(filters, 0);
filters=LazyList.remove(filters,0);
_next=new CachedChain(filters,servletHolder);
}
else
_servletHolder=servletHolder;
}
/* ------------------------------------------------------------ */
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
// pass to next filter
if (_filterHolder!=null)
{
if (Log.isDebugEnabled())
Log.debug("call filter " + _filterHolder);
Filter filter= _filterHolder.getFilter();
filter.doFilter(request, response, _next);
return;
}
// Call servlet
if (_servletHolder != null)
{
if (Log.isDebugEnabled())
Log.debug("call servlet " + _servletHolder);
_servletHolder.handle(request, response);
}
else // Not found
notFound((HttpServletRequest)request, (HttpServletResponse)response);
}
public String toString()
{
if (_filterHolder!=null)
return _filterHolder+"->"+_next.toString();
if (_servletHolder!=null)
return _servletHolder.toString();
return "null";
}
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private class Chain implements FilterChain
{
int _filter= 0;
Object _filters;
ServletHolder _servletHolder;
/* ------------------------------------------------------------ */
Chain(Object filters, ServletHolder servletHolder)
{
_filters= filters;
_servletHolder= servletHolder;
}
/* ------------------------------------------------------------ */
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
if (Log.isDebugEnabled()) Log.debug("doFilter " + _filter);
// pass to next filter
if (_filter < LazyList.size(_filters))
{
FilterHolder holder= (FilterHolder)LazyList.get(_filters, _filter++);
if (Log.isDebugEnabled()) Log.debug("call filter " + holder);
Filter filter= holder.getFilter();
filter.doFilter(request, response, this);
return;
}
// Call servlet
if (_servletHolder != null)
{
if (Log.isDebugEnabled()) Log.debug("call servlet " + _servletHolder);
_servletHolder.handle(request, response);
}
else // Not found
notFound((HttpServletRequest)request, (HttpServletResponse)response);
}
public String toString()
{
StringBuffer b = new StringBuffer();
for (int i=0; i<LazyList.size(_filters);i++)
{
b.append(LazyList.get(_filters, i).toString());
b.append("->");
}
b.append(_servletHolder);
return b.toString();
}
}
}
| true | true | public boolean handle(String target, HttpServletRequest request,HttpServletResponse response, int type)
throws IOException
{
if (!isStarted())
return false;
// Get the base requests
Request base_request=(request instanceof Request)?((Request)request):HttpConnection.getCurrentConnection().getRequest();
String old_servlet_path=null;
String old_path_info=null;
try
{
old_servlet_path=base_request.getServletPath();
old_path_info=base_request.getPathInfo();
ServletHolder servlet_holder=null;
FilterChain chain=null;
// find the servlet
if (target.startsWith("/"))
{
// Look for the servlet by path
PathMap.Entry entry=getHolderEntry(target);
if (entry!=null)
{
servlet_holder=(ServletHolder)entry.getValue();
if(Log.isDebugEnabled())Log.debug("servlet="+servlet_holder);
String servlet_path_spec=(String)entry.getKey();
String servlet_path=entry.getMapped()!=null?entry.getMapped():PathMap.pathMatch(servlet_path_spec,target);
String path_info=PathMap.pathInfo(servlet_path_spec,target);
if (type==INCLUDE)
{
base_request.setAttribute(Dispatcher.__INCLUDE_SERVLET_PATH,servlet_path);
base_request.setAttribute(Dispatcher.__INCLUDE_PATH_INFO, path_info);
}
else
{
base_request.setServletPath(servlet_path);
base_request.setPathInfo(path_info);
}
if (servlet_holder!=null && _filterMappings!=null && _filterMappings.length>0)
chain=getFilterChain(type, target, servlet_holder);
}
}
else
{
// look for a servlet by name!
servlet_holder=(ServletHolder)_servletNameMap.get(target);
if (servlet_holder!=null && _filterMappings!=null && _filterMappings.length>0)
chain=getFilterChain(type, null,servlet_holder);
}
if (Log.isDebugEnabled())
{
Log.debug("chain="+chain);
Log.debug("servelet holder="+servlet_holder);
}
// Do the filter/handling thang
if (chain!=null)
chain.doFilter(request, response);
else if (servlet_holder != null)
servlet_holder.handle(request,response);
else
notFound(request, response);
}
catch(RetryRequest e)
{
throw e;
}
catch(Exception e)
{
Throwable th=e;
while (th instanceof ServletException)
{
Throwable cause=((ServletException)th).getRootCause();
if (cause==th || cause==null)
break;
th=cause;
}
/* TODO
if (th instanceof HttpException)
throw (HttpException)th;
if (th instanceof EOFException)
throw (IOException)th;
else */
if (Log.isDebugEnabled() || !( th instanceof java.io.IOException))
{
Log.warn(request.getRequestURI()+": ",th);
if(Log.isDebugEnabled())
{
Log.warn(request.getRequestURI()+": ",th);
Log.debug(request.toString());
}
}
// TODO clean up
Log.warn(request.getRequestURI(), th);
// TODO httpResponse.getHttpConnection().forceClose();
if (!response.isCommitted())
{
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,th.getClass());
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,th);
if (th instanceof UnavailableException)
{
UnavailableException ue = (UnavailableException)th;
if (ue.isPermanent())
response.sendError(HttpServletResponse.SC_NOT_FOUND,th.getMessage());
else
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,th.getMessage());
}
else
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,th.getMessage());
}
else
if(Log.isDebugEnabled())Log.debug("Response already committed for handling "+th);
}
catch(Error e)
{
Log.warn("Error for "+request.getRequestURI(),e);
if(Log.isDebugEnabled())Log.debug(request.toString());
// TODO httpResponse.getHttpConnection().forceClose();
if (!response.isCommitted())
{
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,e.getClass());
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage());
}
else
if(Log.isDebugEnabled())Log.debug("Response already committed for handling ",e);
}
finally
{
if (type!=INCLUDE)
base_request.setServletPath(old_servlet_path);
base_request.setPathInfo(old_path_info);
}
return true;
}
| public boolean handle(String target, HttpServletRequest request,HttpServletResponse response, int type)
throws IOException
{
if (!isStarted())
return false;
// Get the base requests
Request base_request=(request instanceof Request)?((Request)request):HttpConnection.getCurrentConnection().getRequest();
String old_servlet_path=null;
String old_path_info=null;
try
{
old_servlet_path=base_request.getServletPath();
old_path_info=base_request.getPathInfo();
ServletHolder servlet_holder=null;
FilterChain chain=null;
// find the servlet
if (target.startsWith("/"))
{
// Look for the servlet by path
PathMap.Entry entry=getHolderEntry(target);
if (entry!=null)
{
servlet_holder=(ServletHolder)entry.getValue();
if(Log.isDebugEnabled())Log.debug("servlet="+servlet_holder);
String servlet_path_spec=(String)entry.getKey();
String servlet_path=entry.getMapped()!=null?entry.getMapped():PathMap.pathMatch(servlet_path_spec,target);
String path_info=PathMap.pathInfo(servlet_path_spec,target);
if (type==INCLUDE)
{
base_request.setAttribute(Dispatcher.__INCLUDE_SERVLET_PATH,servlet_path);
base_request.setAttribute(Dispatcher.__INCLUDE_PATH_INFO, path_info);
}
else
{
base_request.setServletPath(servlet_path);
base_request.setPathInfo(path_info);
}
if (servlet_holder!=null && _filterMappings!=null && _filterMappings.length>0)
chain=getFilterChain(type, target, servlet_holder);
}
}
else
{
// look for a servlet by name!
servlet_holder=(ServletHolder)_servletNameMap.get(target);
if (servlet_holder!=null && _filterMappings!=null && _filterMappings.length>0)
chain=getFilterChain(type, null,servlet_holder);
}
if (Log.isDebugEnabled())
{
Log.debug("chain="+chain);
Log.debug("servelet holder="+servlet_holder);
}
// Do the filter/handling thang
if (chain!=null)
chain.doFilter(request, response);
else if (servlet_holder != null)
servlet_holder.handle(request,response);
else
notFound(request, response);
}
catch(RetryRequest e)
{
throw e;
}
catch(Exception e)
{
Throwable th=e;
while (th instanceof ServletException)
{
Throwable cause=((ServletException)th).getRootCause();
if (cause==th || cause==null)
break;
th=cause;
}
/* TODO
if (th instanceof HttpException)
throw (HttpException)th;
if (th instanceof EOFException)
throw (IOException)th;
else */
if (Log.isDebugEnabled() || !( th instanceof java.io.IOException))
{
Log.warn(request.getRequestURI()+": ",th);
if(Log.isDebugEnabled())
{
Log.warn(request.getRequestURI()+": ",th);
Log.debug(request.toString());
}
}
// TODO clean up
Log.warn(request.getRequestURI(), th);
// TODO httpResponse.getHttpConnection().forceClose();
if (!response.isCommitted())
{
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,th.getClass());
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,th);
if (th instanceof UnavailableException)
{
UnavailableException ue = (UnavailableException)th;
if (ue.isPermanent())
response.sendError(HttpServletResponse.SC_NOT_FOUND,th.getMessage());
else
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,th.getMessage());
}
else
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,th.getMessage());
}
else
if(Log.isDebugEnabled())Log.debug("Response already committed for handling "+th);
}
catch(Error e)
{
Log.warn("Error for "+request.getRequestURI(),e);
if(Log.isDebugEnabled())Log.debug(request.toString());
// TODO httpResponse.getHttpConnection().forceClose();
if (!response.isCommitted())
{
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,e.getClass());
request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage());
}
else
if(Log.isDebugEnabled())Log.debug("Response already committed for handling ",e);
}
finally
{
if (type!=INCLUDE)
{
base_request.setServletPath(old_servlet_path);
base_request.setPathInfo(old_path_info);
}
}
return true;
}
|
diff --git a/lbImpl/src/org/LexGrid/LexBIG/Impl/pagedgraph/PagingCodedNodeGraphImpl.java b/lbImpl/src/org/LexGrid/LexBIG/Impl/pagedgraph/PagingCodedNodeGraphImpl.java
index 0dcbeb349..d9f0125f5 100644
--- a/lbImpl/src/org/LexGrid/LexBIG/Impl/pagedgraph/PagingCodedNodeGraphImpl.java
+++ b/lbImpl/src/org/LexGrid/LexBIG/Impl/pagedgraph/PagingCodedNodeGraphImpl.java
@@ -1,415 +1,415 @@
/*
* Copyright: (c) 2004-2010 Mayo Foundation for Medical Education and
* Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
* triple-shield Mayo logo are trademarks and service marks of MFMER.
*
* Except as contained in the copyright notice above, or as used to identify
* MFMER as the author of this software, the trade names, trademarks, service
* marks, or product names of the copyright holder shall not be used in
* advertising, promotion or otherwise in connection with this software without
* prior written authorization of the copyright holder.
*
* Licensed under the Eclipse Public 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.eclipse.org/legal/epl-v10.html
*
*/
package org.LexGrid.LexBIG.Impl.pagedgraph;
import java.util.List;
import org.LexGrid.LexBIG.DataModel.Collections.LocalNameList;
import org.LexGrid.LexBIG.DataModel.Collections.ResolvedConceptReferenceList;
import org.LexGrid.LexBIG.DataModel.Collections.SortOptionList;
import org.LexGrid.LexBIG.DataModel.Core.AbsoluteCodingSchemeVersionReference;
import org.LexGrid.LexBIG.DataModel.Core.AssociatedConcept;
import org.LexGrid.LexBIG.DataModel.Core.Association;
import org.LexGrid.LexBIG.DataModel.Core.ConceptReference;
import org.LexGrid.LexBIG.DataModel.Core.ResolvedConceptReference;
import org.LexGrid.LexBIG.Exceptions.LBInvocationException;
import org.LexGrid.LexBIG.Exceptions.LBParameterException;
import org.LexGrid.LexBIG.Extensions.Query.Filter;
import org.LexGrid.LexBIG.Impl.namespace.NamespaceHandler;
import org.LexGrid.LexBIG.Impl.namespace.NamespaceHandlerFactory;
import org.LexGrid.LexBIG.Impl.pagedgraph.builder.AssociationListBuilder;
import org.LexGrid.LexBIG.Impl.pagedgraph.model.LazyLoadableResolvedConceptReferenceList;
import org.LexGrid.LexBIG.Impl.pagedgraph.paging.callback.CycleDetectingCallback;
import org.LexGrid.LexBIG.Impl.pagedgraph.query.GraphQueryBuilder;
import org.LexGrid.LexBIG.Impl.pagedgraph.root.NullFocusRootsResolver;
import org.LexGrid.LexBIG.Impl.pagedgraph.root.RootsResolver;
import org.LexGrid.LexBIG.Impl.pagedgraph.utility.PagedGraphUtils;
import org.LexGrid.LexBIG.Impl.pagedgraph.utility.ValidatedParameterResolvingCallback;
import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType;
import org.LexGrid.LexBIG.Utility.ServiceUtility;
import org.apache.commons.lang.StringUtils;
import org.lexevs.dao.database.utility.DaoUtility;
import org.lexevs.locator.LexEvsServiceLocator;
import org.lexevs.logging.LoggerFactory;
import org.springframework.util.CollectionUtils;
/**
* The Class PagingCodedNodeGraphImpl.
*
* @author <a href="mailto:[email protected]">Kevin Peterson</a>
*/
public class PagingCodedNodeGraphImpl extends AbstractQueryBuildingCodedNodeGraph {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -1153282485482789848L;
private RootsResolver rootsResolver = new NullFocusRootsResolver();
private AssociationListBuilder associationListBuilder = new AssociationListBuilder();
public PagingCodedNodeGraphImpl() {
super();
}
/**
* Instantiates a new paging coded node graph impl.
*
* @param codingSchemeUri the coding scheme uri
* @param version the version
* @param relationsContainerName the relations container name
* @throws LBParameterException
*/
public PagingCodedNodeGraphImpl(
String codingSchemeUri,
String version,
String relationsContainerName) throws LBParameterException{
super(codingSchemeUri, version, StringUtils.isBlank(relationsContainerName) ? null : relationsContainerName);
}
/* (non-Javadoc)
* @see org.LexGrid.LexBIG.LexBIGService.CodedNodeGraph#resolveAsList(org.LexGrid.LexBIG.DataModel.Core.ConceptReference, boolean, boolean, int, int, org.LexGrid.LexBIG.DataModel.Collections.LocalNameList, org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.PropertyType[], org.LexGrid.LexBIG.DataModel.Collections.SortOptionList, org.LexGrid.LexBIG.DataModel.Collections.LocalNameList, int)
*/
@Override
public ResolvedConceptReferenceList doResolveAsValidatedParameterList(
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveCodedEntryDepth,
int resolveAssociationDepth,
LocalNameList propertyNames,
PropertyType[] propertyTypes,
SortOptionList sortOptions,
LocalNameList filterOptions,
int maxToReturn,
boolean keepLastAssociationLevelUnresolved,
CycleDetectingCallback cycleDetectingCallback) throws LBInvocationException, LBParameterException {
String codingSchemeUri = this.getCodingSchemeUri();
String version = this.getVersion();
String relationsContainerName = this.getRelationsContainerName();
GraphQueryBuilder graphQueryBuilder = this.getGraphQueryBuilder();
Filter[] filters = ServiceUtility.validateFilters(filterOptions);
if (graphFocus == null && resolveForward && resolveBackward) {
throw new LBParameterException(
"If you do not provide a focus node, you must choose resolve forward or resolve reverse, not both."
+ " Choose resolve forward to start at root nodes. Choose resolve reverse to start at tail nodes.");
}
ResolvedConceptReference focus = null;
boolean needToValidateFocusExistsInGraph = true;
if(graphFocus != null) {
if(StringUtils.isNotBlank(graphFocus.getCodeNamespace())
&&
StringUtils.isNotBlank(graphFocus.getCodingSchemeName())){
String codingSchemeName =
this.getNamespaceHandler().getCodingSchemeNameForNamespace(codingSchemeUri, version, graphFocus.getCodeNamespace());
if(! StringUtils.equals(graphFocus.getCodingSchemeName(), codingSchemeName)){
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("Based on the namespace provided as a focus (" + graphFocus.getCodeNamespace() + ")" +
" there is no match to the provided Coding Scheme Name (" + graphFocus.getCodingSchemeName() + ")." +
" If " + graphFocus.getCodeNamespace() + " is meant to be equivalent to the CodingScheme " + graphFocus.getCodingSchemeName() + ", " +
" this must be declared in the SupportedNamespaces."),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation());
}
}
focus =
LexEvsServiceLocator.getInstance().getDatabaseServiceManager().
getEntityService().
getResolvedCodedNodeReference(
codingSchemeUri,
version,
graphFocus.getCode(),
graphFocus.getCodeNamespace(),
this.shouldResolveNextLevel(resolveCodedEntryDepth),
DaoUtility.localNameListToString(propertyNames),
DaoUtility.propertyTypeArrayToString(propertyTypes));
if(focus == null) {
if(graphFocus.getCodeNamespace() != null) {
AbsoluteCodingSchemeVersionReference ref = null;
try {
ref = this.getNamespaceHandler().getCodingSchemeForNamespace(codingSchemeUri, version, graphFocus.getCodeNamespace());
} catch (LBParameterException e) {
LoggerFactory.getLogger().warn(e.getMessage());
}
if(ref != null) {
focus =
LexEvsServiceLocator.getInstance().getDatabaseServiceManager().
getEntityService().
getResolvedCodedNodeReference(
ref.getCodingSchemeURN(),
ref.getCodingSchemeVersion(),
graphFocus.getCode(),
graphFocus.getCodeNamespace(),
this.shouldResolveNextLevel(resolveCodedEntryDepth),
DaoUtility.localNameListToString(propertyNames),
DaoUtility.propertyTypeArrayToString(propertyTypes));
}
}
} else {
needToValidateFocusExistsInGraph = false;
}
if(focus == null) {
focus = new ResolvedConceptReference();
focus.setCode(graphFocus.getCode());
String namespace = graphFocus.getCodeNamespace();
String codingSchemeName = graphFocus.getCodingSchemeName();
if(StringUtils.isBlank(namespace)){
if(StringUtils.isBlank(codingSchemeName)) {
namespace = LexEvsServiceLocator.getInstance().getSystemResourceService().getInternalCodingSchemeNameForUserCodingSchemeName(codingSchemeUri, version);
} else {
List<String> namespaces = this.getNamespaceHandler().getNamespacesForCodingScheme(codingSchemeUri, version, codingSchemeName);
if(CollectionUtils.isEmpty(namespaces)) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("The provided focus did not contain a namespace, and information in the " +
"SupportedNamespaces was unable to generate the correct one."),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation());
}
if(namespaces.size() > 1) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("The provided focus did not contain a namespace, and information in the " +
"SupportedNamespaces did not provide a unique namespace. Please provide a namespace with the focus"),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation());
}
namespace = namespaces.get(0);
}
}
String expectedCodingSchemeName = this.getNamespaceHandler().getCodingSchemeNameForNamespace(codingSchemeUri, version, namespace);
if(StringUtils.isBlank(codingSchemeName)){
codingSchemeName = expectedCodingSchemeName;
} else {
if(!codingSchemeName.equals(expectedCodingSchemeName)) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("Based on the namespace provided as a focus (" + namespace + ")" +
" there is no match to the provided Coding Scheme Name (" + codingSchemeName + ")." +
" If " + namespace + " is meant to be equivalent to the CodingScheme " + codingSchemeName + ", " +
" this must be declared in the SupportedNamespaces."
),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation()
);
}
}
if(StringUtils.isBlank(codingSchemeName)) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("Could not determine a Coding Scheme for the requested Focus Code."),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation()
);
}
focus.setCodeNamespace(namespace);
focus.setCodingSchemeName(codingSchemeName);
}
boolean isValidFocus = PagedGraphUtils.checkFocus(
this.getCodingSchemeUri(),
this.getVersion(),
this.getRelationsContainerName(),
focus,
resolveForward,
resolveBackward,
filters,
this.getGraphQueryBuilder().getQuery(),
needToValidateFocusExistsInGraph);
if(! isValidFocus) {
return new ResolvedConceptReferenceList();
}
} else {
return new LazyLoadableResolvedConceptReferenceList(
new ValidatedParameterResolvingCallback() {
private static final long serialVersionUID = 1401783416514871042L;
@Override
public ResolvedConceptReferenceList doResolveAsValidatedParameterList(
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveCodedEntryDepth,
int resolveAssociationDepth,
LocalNameList propertyNames,
PropertyType[] propertyTypes,
SortOptionList sortOptions,
LocalNameList filterOptions,
int maxToReturn,
boolean keepLastAssociationLevelUnresolved,
CycleDetectingCallback cycleDetectingCallback) throws LBInvocationException, LBParameterException {
- return this.doResolveAsValidatedParameterList(
+ return PagingCodedNodeGraphImpl.this.doResolveAsValidatedParameterList(
graphFocus,
resolveForward,
resolveBackward,
resolveCodedEntryDepth,
resolveAssociationDepth,
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
maxToReturn,
keepLastAssociationLevelUnresolved,
cycleDetectingCallback);
}
},
this.getCodingSchemeUri(),
this.getVersion(),
this.getRelationsContainerName(),
resolveForward,
resolveBackward,
resolveAssociationDepth,
resolveCodedEntryDepth,
keepLastAssociationLevelUnresolved,
this.getGraphQueryBuilder().getQuery(),
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
cycleDetectingCallback,
maxToReturn);
}
int resolveForwardAssociationDepth = resolveAssociationDepth;
int resolveBackwardAssociationDepth = resolveAssociationDepth;
if(this.rootsResolver.isRootOrTail(focus) && resolveAssociationDepth >= 0) {
if(resolveForward) {
resolveForwardAssociationDepth++;
}
if(resolveBackward) {
resolveBackwardAssociationDepth++;
}
}
if(resolveForward && shouldResolveNextLevel(resolveForwardAssociationDepth)) {
focus.setSourceOf(
associationListBuilder.buildSourceOfAssociationList(
this.getCodingSchemeUri(),
this.getVersion(),
focus.getCode(),
focus.getCodeNamespace(),
relationsContainerName,
resolveForward,
resolveBackward,
resolveForwardAssociationDepth - 1,
resolveBackwardAssociationDepth,
resolveCodedEntryDepth,
graphQueryBuilder.getQuery(),
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
cycleDetectingCallback));
}
if(resolveBackward && shouldResolveNextLevel(resolveBackwardAssociationDepth)) {
focus.setTargetOf(
associationListBuilder.buildTargetOfAssociationList(
this.getCodingSchemeUri(),
this.getVersion(),
focus.getCode(),
focus.getCodeNamespace(),
relationsContainerName,
resolveForward,
resolveBackward,
resolveForwardAssociationDepth,
resolveBackwardAssociationDepth - 1,
resolveCodedEntryDepth,
graphQueryBuilder.getQuery(),
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
cycleDetectingCallback));
}
ResolvedConceptReferenceList returnList = new ResolvedConceptReferenceList();
if(! this.rootsResolver.isRootOrTail(focus)) {
returnList.addResolvedConceptReference(focus);
} else {
returnList = flattenRootList(focus);
}
return returnList;
}
private ResolvedConceptReferenceList flattenRootList(ResolvedConceptReference root) {
ResolvedConceptReferenceList returnList = new ResolvedConceptReferenceList();
if(root.getSourceOf() != null) {
for(Association assoc : root.getSourceOf().getAssociation()) {
for(AssociatedConcept ac : assoc.getAssociatedConcepts().getAssociatedConcept()) {
returnList.addResolvedConceptReference(ac);
}
}
}
if(root.getTargetOf() != null) {
for(Association assoc : root.getTargetOf().getAssociation()) {
for(AssociatedConcept ac : assoc.getAssociatedConcepts().getAssociatedConcept()) {
returnList.addResolvedConceptReference(ac);
}
}
}
return returnList;
}
/**
* Should resolve next level.
*
* @param depth the depth
*
* @return true, if successful
*/
private boolean shouldResolveNextLevel(int depth) {
return ! (depth == 0);
}
private NamespaceHandler getNamespaceHandler() {
return NamespaceHandlerFactory.getNamespaceHandler();
}
}
| true | true | public ResolvedConceptReferenceList doResolveAsValidatedParameterList(
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveCodedEntryDepth,
int resolveAssociationDepth,
LocalNameList propertyNames,
PropertyType[] propertyTypes,
SortOptionList sortOptions,
LocalNameList filterOptions,
int maxToReturn,
boolean keepLastAssociationLevelUnresolved,
CycleDetectingCallback cycleDetectingCallback) throws LBInvocationException, LBParameterException {
String codingSchemeUri = this.getCodingSchemeUri();
String version = this.getVersion();
String relationsContainerName = this.getRelationsContainerName();
GraphQueryBuilder graphQueryBuilder = this.getGraphQueryBuilder();
Filter[] filters = ServiceUtility.validateFilters(filterOptions);
if (graphFocus == null && resolveForward && resolveBackward) {
throw new LBParameterException(
"If you do not provide a focus node, you must choose resolve forward or resolve reverse, not both."
+ " Choose resolve forward to start at root nodes. Choose resolve reverse to start at tail nodes.");
}
ResolvedConceptReference focus = null;
boolean needToValidateFocusExistsInGraph = true;
if(graphFocus != null) {
if(StringUtils.isNotBlank(graphFocus.getCodeNamespace())
&&
StringUtils.isNotBlank(graphFocus.getCodingSchemeName())){
String codingSchemeName =
this.getNamespaceHandler().getCodingSchemeNameForNamespace(codingSchemeUri, version, graphFocus.getCodeNamespace());
if(! StringUtils.equals(graphFocus.getCodingSchemeName(), codingSchemeName)){
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("Based on the namespace provided as a focus (" + graphFocus.getCodeNamespace() + ")" +
" there is no match to the provided Coding Scheme Name (" + graphFocus.getCodingSchemeName() + ")." +
" If " + graphFocus.getCodeNamespace() + " is meant to be equivalent to the CodingScheme " + graphFocus.getCodingSchemeName() + ", " +
" this must be declared in the SupportedNamespaces."),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation());
}
}
focus =
LexEvsServiceLocator.getInstance().getDatabaseServiceManager().
getEntityService().
getResolvedCodedNodeReference(
codingSchemeUri,
version,
graphFocus.getCode(),
graphFocus.getCodeNamespace(),
this.shouldResolveNextLevel(resolveCodedEntryDepth),
DaoUtility.localNameListToString(propertyNames),
DaoUtility.propertyTypeArrayToString(propertyTypes));
if(focus == null) {
if(graphFocus.getCodeNamespace() != null) {
AbsoluteCodingSchemeVersionReference ref = null;
try {
ref = this.getNamespaceHandler().getCodingSchemeForNamespace(codingSchemeUri, version, graphFocus.getCodeNamespace());
} catch (LBParameterException e) {
LoggerFactory.getLogger().warn(e.getMessage());
}
if(ref != null) {
focus =
LexEvsServiceLocator.getInstance().getDatabaseServiceManager().
getEntityService().
getResolvedCodedNodeReference(
ref.getCodingSchemeURN(),
ref.getCodingSchemeVersion(),
graphFocus.getCode(),
graphFocus.getCodeNamespace(),
this.shouldResolveNextLevel(resolveCodedEntryDepth),
DaoUtility.localNameListToString(propertyNames),
DaoUtility.propertyTypeArrayToString(propertyTypes));
}
}
} else {
needToValidateFocusExistsInGraph = false;
}
if(focus == null) {
focus = new ResolvedConceptReference();
focus.setCode(graphFocus.getCode());
String namespace = graphFocus.getCodeNamespace();
String codingSchemeName = graphFocus.getCodingSchemeName();
if(StringUtils.isBlank(namespace)){
if(StringUtils.isBlank(codingSchemeName)) {
namespace = LexEvsServiceLocator.getInstance().getSystemResourceService().getInternalCodingSchemeNameForUserCodingSchemeName(codingSchemeUri, version);
} else {
List<String> namespaces = this.getNamespaceHandler().getNamespacesForCodingScheme(codingSchemeUri, version, codingSchemeName);
if(CollectionUtils.isEmpty(namespaces)) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("The provided focus did not contain a namespace, and information in the " +
"SupportedNamespaces was unable to generate the correct one."),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation());
}
if(namespaces.size() > 1) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("The provided focus did not contain a namespace, and information in the " +
"SupportedNamespaces did not provide a unique namespace. Please provide a namespace with the focus"),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation());
}
namespace = namespaces.get(0);
}
}
String expectedCodingSchemeName = this.getNamespaceHandler().getCodingSchemeNameForNamespace(codingSchemeUri, version, namespace);
if(StringUtils.isBlank(codingSchemeName)){
codingSchemeName = expectedCodingSchemeName;
} else {
if(!codingSchemeName.equals(expectedCodingSchemeName)) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("Based on the namespace provided as a focus (" + namespace + ")" +
" there is no match to the provided Coding Scheme Name (" + codingSchemeName + ")." +
" If " + namespace + " is meant to be equivalent to the CodingScheme " + codingSchemeName + ", " +
" this must be declared in the SupportedNamespaces."
),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation()
);
}
}
if(StringUtils.isBlank(codingSchemeName)) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("Could not determine a Coding Scheme for the requested Focus Code."),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation()
);
}
focus.setCodeNamespace(namespace);
focus.setCodingSchemeName(codingSchemeName);
}
boolean isValidFocus = PagedGraphUtils.checkFocus(
this.getCodingSchemeUri(),
this.getVersion(),
this.getRelationsContainerName(),
focus,
resolveForward,
resolveBackward,
filters,
this.getGraphQueryBuilder().getQuery(),
needToValidateFocusExistsInGraph);
if(! isValidFocus) {
return new ResolvedConceptReferenceList();
}
} else {
return new LazyLoadableResolvedConceptReferenceList(
new ValidatedParameterResolvingCallback() {
private static final long serialVersionUID = 1401783416514871042L;
@Override
public ResolvedConceptReferenceList doResolveAsValidatedParameterList(
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveCodedEntryDepth,
int resolveAssociationDepth,
LocalNameList propertyNames,
PropertyType[] propertyTypes,
SortOptionList sortOptions,
LocalNameList filterOptions,
int maxToReturn,
boolean keepLastAssociationLevelUnresolved,
CycleDetectingCallback cycleDetectingCallback) throws LBInvocationException, LBParameterException {
return this.doResolveAsValidatedParameterList(
graphFocus,
resolveForward,
resolveBackward,
resolveCodedEntryDepth,
resolveAssociationDepth,
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
maxToReturn,
keepLastAssociationLevelUnresolved,
cycleDetectingCallback);
}
},
this.getCodingSchemeUri(),
this.getVersion(),
this.getRelationsContainerName(),
resolveForward,
resolveBackward,
resolveAssociationDepth,
resolveCodedEntryDepth,
keepLastAssociationLevelUnresolved,
this.getGraphQueryBuilder().getQuery(),
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
cycleDetectingCallback,
maxToReturn);
}
int resolveForwardAssociationDepth = resolveAssociationDepth;
int resolveBackwardAssociationDepth = resolveAssociationDepth;
if(this.rootsResolver.isRootOrTail(focus) && resolveAssociationDepth >= 0) {
if(resolveForward) {
resolveForwardAssociationDepth++;
}
if(resolveBackward) {
resolveBackwardAssociationDepth++;
}
}
if(resolveForward && shouldResolveNextLevel(resolveForwardAssociationDepth)) {
focus.setSourceOf(
associationListBuilder.buildSourceOfAssociationList(
this.getCodingSchemeUri(),
this.getVersion(),
focus.getCode(),
focus.getCodeNamespace(),
relationsContainerName,
resolveForward,
resolveBackward,
resolveForwardAssociationDepth - 1,
resolveBackwardAssociationDepth,
resolveCodedEntryDepth,
graphQueryBuilder.getQuery(),
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
cycleDetectingCallback));
}
if(resolveBackward && shouldResolveNextLevel(resolveBackwardAssociationDepth)) {
focus.setTargetOf(
associationListBuilder.buildTargetOfAssociationList(
this.getCodingSchemeUri(),
this.getVersion(),
focus.getCode(),
focus.getCodeNamespace(),
relationsContainerName,
resolveForward,
resolveBackward,
resolveForwardAssociationDepth,
resolveBackwardAssociationDepth - 1,
resolveCodedEntryDepth,
graphQueryBuilder.getQuery(),
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
cycleDetectingCallback));
}
ResolvedConceptReferenceList returnList = new ResolvedConceptReferenceList();
if(! this.rootsResolver.isRootOrTail(focus)) {
returnList.addResolvedConceptReference(focus);
} else {
returnList = flattenRootList(focus);
}
return returnList;
}
| public ResolvedConceptReferenceList doResolveAsValidatedParameterList(
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveCodedEntryDepth,
int resolveAssociationDepth,
LocalNameList propertyNames,
PropertyType[] propertyTypes,
SortOptionList sortOptions,
LocalNameList filterOptions,
int maxToReturn,
boolean keepLastAssociationLevelUnresolved,
CycleDetectingCallback cycleDetectingCallback) throws LBInvocationException, LBParameterException {
String codingSchemeUri = this.getCodingSchemeUri();
String version = this.getVersion();
String relationsContainerName = this.getRelationsContainerName();
GraphQueryBuilder graphQueryBuilder = this.getGraphQueryBuilder();
Filter[] filters = ServiceUtility.validateFilters(filterOptions);
if (graphFocus == null && resolveForward && resolveBackward) {
throw new LBParameterException(
"If you do not provide a focus node, you must choose resolve forward or resolve reverse, not both."
+ " Choose resolve forward to start at root nodes. Choose resolve reverse to start at tail nodes.");
}
ResolvedConceptReference focus = null;
boolean needToValidateFocusExistsInGraph = true;
if(graphFocus != null) {
if(StringUtils.isNotBlank(graphFocus.getCodeNamespace())
&&
StringUtils.isNotBlank(graphFocus.getCodingSchemeName())){
String codingSchemeName =
this.getNamespaceHandler().getCodingSchemeNameForNamespace(codingSchemeUri, version, graphFocus.getCodeNamespace());
if(! StringUtils.equals(graphFocus.getCodingSchemeName(), codingSchemeName)){
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("Based on the namespace provided as a focus (" + graphFocus.getCodeNamespace() + ")" +
" there is no match to the provided Coding Scheme Name (" + graphFocus.getCodingSchemeName() + ")." +
" If " + graphFocus.getCodeNamespace() + " is meant to be equivalent to the CodingScheme " + graphFocus.getCodingSchemeName() + ", " +
" this must be declared in the SupportedNamespaces."),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation());
}
}
focus =
LexEvsServiceLocator.getInstance().getDatabaseServiceManager().
getEntityService().
getResolvedCodedNodeReference(
codingSchemeUri,
version,
graphFocus.getCode(),
graphFocus.getCodeNamespace(),
this.shouldResolveNextLevel(resolveCodedEntryDepth),
DaoUtility.localNameListToString(propertyNames),
DaoUtility.propertyTypeArrayToString(propertyTypes));
if(focus == null) {
if(graphFocus.getCodeNamespace() != null) {
AbsoluteCodingSchemeVersionReference ref = null;
try {
ref = this.getNamespaceHandler().getCodingSchemeForNamespace(codingSchemeUri, version, graphFocus.getCodeNamespace());
} catch (LBParameterException e) {
LoggerFactory.getLogger().warn(e.getMessage());
}
if(ref != null) {
focus =
LexEvsServiceLocator.getInstance().getDatabaseServiceManager().
getEntityService().
getResolvedCodedNodeReference(
ref.getCodingSchemeURN(),
ref.getCodingSchemeVersion(),
graphFocus.getCode(),
graphFocus.getCodeNamespace(),
this.shouldResolveNextLevel(resolveCodedEntryDepth),
DaoUtility.localNameListToString(propertyNames),
DaoUtility.propertyTypeArrayToString(propertyTypes));
}
}
} else {
needToValidateFocusExistsInGraph = false;
}
if(focus == null) {
focus = new ResolvedConceptReference();
focus.setCode(graphFocus.getCode());
String namespace = graphFocus.getCodeNamespace();
String codingSchemeName = graphFocus.getCodingSchemeName();
if(StringUtils.isBlank(namespace)){
if(StringUtils.isBlank(codingSchemeName)) {
namespace = LexEvsServiceLocator.getInstance().getSystemResourceService().getInternalCodingSchemeNameForUserCodingSchemeName(codingSchemeUri, version);
} else {
List<String> namespaces = this.getNamespaceHandler().getNamespacesForCodingScheme(codingSchemeUri, version, codingSchemeName);
if(CollectionUtils.isEmpty(namespaces)) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("The provided focus did not contain a namespace, and information in the " +
"SupportedNamespaces was unable to generate the correct one."),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation());
}
if(namespaces.size() > 1) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("The provided focus did not contain a namespace, and information in the " +
"SupportedNamespaces did not provide a unique namespace. Please provide a namespace with the focus"),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation());
}
namespace = namespaces.get(0);
}
}
String expectedCodingSchemeName = this.getNamespaceHandler().getCodingSchemeNameForNamespace(codingSchemeUri, version, namespace);
if(StringUtils.isBlank(codingSchemeName)){
codingSchemeName = expectedCodingSchemeName;
} else {
if(!codingSchemeName.equals(expectedCodingSchemeName)) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("Based on the namespace provided as a focus (" + namespace + ")" +
" there is no match to the provided Coding Scheme Name (" + codingSchemeName + ")." +
" If " + namespace + " is meant to be equivalent to the CodingScheme " + codingSchemeName + ", " +
" this must be declared in the SupportedNamespaces."
),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation()
);
}
}
if(StringUtils.isBlank(codingSchemeName)) {
return ServiceUtility.throwExceptionOrReturnDefault(
new LBParameterException("Could not determine a Coding Scheme for the requested Focus Code."),
new ResolvedConceptReferenceList(),
this.isStrictFocusValidation()
);
}
focus.setCodeNamespace(namespace);
focus.setCodingSchemeName(codingSchemeName);
}
boolean isValidFocus = PagedGraphUtils.checkFocus(
this.getCodingSchemeUri(),
this.getVersion(),
this.getRelationsContainerName(),
focus,
resolveForward,
resolveBackward,
filters,
this.getGraphQueryBuilder().getQuery(),
needToValidateFocusExistsInGraph);
if(! isValidFocus) {
return new ResolvedConceptReferenceList();
}
} else {
return new LazyLoadableResolvedConceptReferenceList(
new ValidatedParameterResolvingCallback() {
private static final long serialVersionUID = 1401783416514871042L;
@Override
public ResolvedConceptReferenceList doResolveAsValidatedParameterList(
ConceptReference graphFocus,
boolean resolveForward,
boolean resolveBackward,
int resolveCodedEntryDepth,
int resolveAssociationDepth,
LocalNameList propertyNames,
PropertyType[] propertyTypes,
SortOptionList sortOptions,
LocalNameList filterOptions,
int maxToReturn,
boolean keepLastAssociationLevelUnresolved,
CycleDetectingCallback cycleDetectingCallback) throws LBInvocationException, LBParameterException {
return PagingCodedNodeGraphImpl.this.doResolveAsValidatedParameterList(
graphFocus,
resolveForward,
resolveBackward,
resolveCodedEntryDepth,
resolveAssociationDepth,
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
maxToReturn,
keepLastAssociationLevelUnresolved,
cycleDetectingCallback);
}
},
this.getCodingSchemeUri(),
this.getVersion(),
this.getRelationsContainerName(),
resolveForward,
resolveBackward,
resolveAssociationDepth,
resolveCodedEntryDepth,
keepLastAssociationLevelUnresolved,
this.getGraphQueryBuilder().getQuery(),
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
cycleDetectingCallback,
maxToReturn);
}
int resolveForwardAssociationDepth = resolveAssociationDepth;
int resolveBackwardAssociationDepth = resolveAssociationDepth;
if(this.rootsResolver.isRootOrTail(focus) && resolveAssociationDepth >= 0) {
if(resolveForward) {
resolveForwardAssociationDepth++;
}
if(resolveBackward) {
resolveBackwardAssociationDepth++;
}
}
if(resolveForward && shouldResolveNextLevel(resolveForwardAssociationDepth)) {
focus.setSourceOf(
associationListBuilder.buildSourceOfAssociationList(
this.getCodingSchemeUri(),
this.getVersion(),
focus.getCode(),
focus.getCodeNamespace(),
relationsContainerName,
resolveForward,
resolveBackward,
resolveForwardAssociationDepth - 1,
resolveBackwardAssociationDepth,
resolveCodedEntryDepth,
graphQueryBuilder.getQuery(),
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
cycleDetectingCallback));
}
if(resolveBackward && shouldResolveNextLevel(resolveBackwardAssociationDepth)) {
focus.setTargetOf(
associationListBuilder.buildTargetOfAssociationList(
this.getCodingSchemeUri(),
this.getVersion(),
focus.getCode(),
focus.getCodeNamespace(),
relationsContainerName,
resolveForward,
resolveBackward,
resolveForwardAssociationDepth,
resolveBackwardAssociationDepth - 1,
resolveCodedEntryDepth,
graphQueryBuilder.getQuery(),
propertyNames,
propertyTypes,
sortOptions,
filterOptions,
cycleDetectingCallback));
}
ResolvedConceptReferenceList returnList = new ResolvedConceptReferenceList();
if(! this.rootsResolver.isRootOrTail(focus)) {
returnList.addResolvedConceptReference(focus);
} else {
returnList = flattenRootList(focus);
}
return returnList;
}
|
diff --git a/src/be/ibridge/kettle/core/Props.java b/src/be/ibridge/kettle/core/Props.java
index 79810bd6..4ccef423 100644
--- a/src/be/ibridge/kettle/core/Props.java
+++ b/src/be/ibridge/kettle/core/Props.java
@@ -1,1422 +1,1422 @@
/**********************************************************************
** **
** This code belongs to the KETTLE project. **
** **
** Kettle, from version 2.2 on, is released into the public domain **
** under the Lesser GNU Public License (LGPL). **
** **
** For more details, please read the document LICENSE.txt, included **
** in this project **
** **
** http://www.kettle.be **
** [email protected] **
** **
**********************************************************************/
package be.ibridge.kettle.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TableItem;
import be.ibridge.kettle.core.value.Value;
/**
* We use Props to store all kinds of user interactive information such as the favoroute colors, fonts, positions of windows, etc.
*
* @author Matt
* @since 15-12-2003
*
*/
public class Props implements Cloneable
{
private static Props props;
public static final String STRING_FONT_FIXED_NAME = "FontFixedName";
public static final String STRING_FONT_FIXED_SIZE = "FontFixedSize";
public static final String STRING_FONT_FIXED_STYLE = "FontFixedStyle";
public static final String STRING_FONT_DEFAULT_NAME = "FontDefaultName";
public static final String STRING_FONT_DEFAULT_SIZE = "FontDefaultSize";
public static final String STRING_FONT_DEFAULT_STYLE = "FontDefaultStyle";
public static final String STRING_FONT_GRAPH_NAME = "FontGraphName";
public static final String STRING_FONT_GRAPH_SIZE = "FontGraphSize";
public static final String STRING_FONT_GRAPH_STYLE = "FontGraphStyle";
public static final String STRING_FONT_GRID_NAME = "FontGridName";
public static final String STRING_FONT_GRID_SIZE = "FontGridSize";
public static final String STRING_FONT_GRID_STYLE = "FontGridStyle";
public static final String STRING_FONT_NOTE_NAME = "FontNoteName";
public static final String STRING_FONT_NOTE_SIZE = "FontNoteSize";
public static final String STRING_FONT_NOTE_STYLE = "FontNoteStyle";
public static final String STRING_BACKGROUND_COLOR_R = "BackgroundColorR";
public static final String STRING_BACKGROUND_COLOR_G = "BackgroundColorG";
public static final String STRING_BACKGROUND_COLOR_B = "BackgroundColorB";
public static final String STRING_GRAPH_COLOR_R = "GraphColorR";
public static final String STRING_GRAPH_COLOR_G = "GraphColorG";
public static final String STRING_GRAPH_COLOR_B = "GraphColorB";
public static final String STRING_TAB_COLOR_R = "TabColorR";
public static final String STRING_TAB_COLOR_G = "TabColorG";
public static final String STRING_TAB_COLOR_B = "TabColorB";
public static final String STRING_ICON_SIZE = "IconSize";
public static final String STRING_LINE_WIDTH = "LineWidth";
public static final String STRING_SHADOW_SIZE = "ShadowSize";
public static final String STRING_LOG_LEVEL = "LogLevel";
public static final String STRING_LOG_FILTER = "LogFilter";
public static final String STRING_MIDDLE_PCT = "MiddlePct";
public static final String STRING_LAST_PREVIEW_TRANS = "LastPreviewTrans";
public static final String STRING_LAST_PREVIEW_STEP = "LastPreviewStep";
public static final String STRING_LAST_PREVIEW_SIZE = "LastPreviewSize";
public static final String STRING_MAX_UNDO = "MaxUndo";
public static final String STRING_SIZE_MAX = "SizeMax";
public static final String STRING_SIZE_X = "SizeX";
public static final String STRING_SIZE_Y = "SizeY";
public static final String STRING_SIZE_W = "SizeW";
public static final String STRING_SIZE_H = "SizeH";
public static final String STRING_SASH_W1 = "SashWeight1";
public static final String STRING_SASH_W2 = "SashWeight2";
public static final String STRING_SHOW_TIPS = "ShowTips";
public static final String STRING_TIP_NR = "TipNr";
public static final String STRING_AUTO_SAVE = "AutoSave";
public static final String STRING_SAVE_CONF = "SaveConfirmation";
public static final String STRING_AUTO_SPLIT = "AutoSplit";
public static final String STRING_USE_DB_CACHE = "UseDBCache";
public static final String STRING_OPEN_LAST_FILE = "OpenLastFile";
public static final String STRING_LAST_REPOSITORY_LOGIN = "RepositoryLastLogin";
public static final String STRING_LAST_REPOSITORY = "RepositoryLast";
public static final String STRING_ONLY_ACTIVE_STEPS = "OnlyActiveSteps";
public static final String STRING_START_SHOW_REPOSITORIES = "ShowRepositoriesAtStartup";
public static final String STRING_ANTI_ALIASING = "EnableAntiAliasing";
public static final String STRING_SHOW_EXIT_WARNING = "ShowExitWarning";
public static final String STRING_SHOW_OS_LOOK = "ShowOSLook";
public static final String STRING_LAST_ARGUMENT = "LastArgument";
public static final String STRING_CUSTOM_PARAMETER = "CustomParameter";
public static final String STRING_PLUGIN_HISTORY = "PluginHistory";
public static final String STRING_DEFAULT_PREVIEW_SIZE = "DefaultPreviewSize";
public static final String STRING_ONLY_USED_DB_TO_XML = "SaveOnlyUsedConnectionsToXML";
private Properties properties;
private String lastfiles[];
private String lastdirs[];
private boolean lasttypes[];
private String lastrepos[];
private ArrayList pluginHistory;
private Display display;
/**
* Props also contains the clipboard as it has to be allocated only once!
* I don't want to put it in a seperate singleton just for this one member.
*/
private Clipboard clipboard;
private int type;
private Hashtable screens;
public static final int TYPE_PROPERTIES_EMPTY = 0;
public static final int TYPE_PROPERTIES_SPOON = 1;
public static final int TYPE_PROPERTIES_PAN = 2;
public static final int TYPE_PROPERTIES_CHEF = 3;
public static final int TYPE_PROPERTIES_KITCHEN = 4;
public static final int TYPE_PROPERTIES_MENU = 5;
public static final int TYPE_PROPERTIES_PLATE = 6;
public static final int WIDGET_STYLE_DEFAULT = 0;
public static final int WIDGET_STYLE_FIXED = 1;
public static final int WIDGET_STYLE_TABLE = 2;
public static final int WIDGET_STYLE_NOTEPAD = 3;
public static final int WIDGET_STYLE_GRAPH = 4;
public static final int WIDGET_STYLE_TAB = 5;
/**
* Initialize the properties: load from disk.
* @param display The Display
* @param t The type of properties file.
*/
public static final void init(Display display, int t)
{
if (props==null)
{
props = new Props(display, t);
// Also init the colors and fonts to use...
GUIResource.getInstance();
}
else
{
throw new RuntimeException("Properties, Kettle systems settings, already initialised!");
}
}
/**
* Check to see whether the Kettle properties where loaded.
* @return true if the Kettle properties where loaded.
*/
public static final boolean isInitialized()
{
return props!=null;
}
public static final Props getInstance()
{
if (props!=null) return props;
throw new RuntimeException("Properties, Kettle systems settings, not initialised!");
}
private Props(Display dis, int t)
{
display=dis;
properties = new Properties();
setDefault();
type=t;
clipboard = null;
pluginHistory = new ArrayList();
try
{
if (type!=TYPE_PROPERTIES_EMPTY)
{
properties.load(new FileInputStream(new File(getFilename())));
}
}
catch(IOException e)
{
}
lastfiles = getLastFiles();
lastdirs = getLastDirs();
lasttypes = getLastTypes();
lastrepos = getLastRepositories();
loadScreens();
loadPluginHistory();
}
public String getFilename()
{
String directory = Const.getKettleDirectory();
String filename = "";
// Try to create the directory...
File dir = new File(directory);
try { dir.mkdirs(); } catch(Exception e) { }
switch(type)
{
case TYPE_PROPERTIES_SPOON:
case TYPE_PROPERTIES_PAN:
filename=directory+Const.FILE_SEPARATOR+".spoonrc";
break;
case TYPE_PROPERTIES_CHEF:
case TYPE_PROPERTIES_KITCHEN:
filename=directory+Const.FILE_SEPARATOR+".chefrc";
break;
case TYPE_PROPERTIES_MENU:
filename=directory+Const.FILE_SEPARATOR+".menu";
break;
case TYPE_PROPERTIES_PLATE:
filename=directory+Const.FILE_SEPARATOR+".plate";
break;
default: break;
}
return filename;
}
public String getLicenseFilename()
{
String directory = Const.getKettleDirectory();
String filename = directory+Const.FILE_SEPARATOR+".licence";
// Try to create the directory...
File dir = new File(directory);
if (!dir.exists())
{
try { dir.mkdirs(); }
catch(Exception e) { }
}
return filename;
}
public boolean fileExists()
{
File f = new File(getFilename());
return f.exists();
}
public void setType(int t)
{
type=t;
}
public int getType()
{
return type;
}
/**
* @return Returns the clipboard.
*/
public Clipboard getNewClipboard()
{
if (clipboard!=null)
{
clipboard.dispose();
clipboard=null;
}
clipboard=new Clipboard(display);
return clipboard;
}
public void toClipboard(String cliptext)
{
if (cliptext==null) return;
getNewClipboard();
TextTransfer tran = TextTransfer.getInstance();
clipboard.setContents(new String[] { cliptext }, new Transfer[] { tran });
}
public String fromClipboard()
{
getNewClipboard();
TextTransfer tran = TextTransfer.getInstance();
return (String)clipboard.getContents(tran);
}
public void setDefault()
{
FontData fd;
RGB col;
lastfiles=new String[0];
lasttypes=new boolean[0];
lastrepos=new String[0];
screens = new Hashtable();
properties.setProperty(STRING_LOG_LEVEL, getLogLevel());
properties.setProperty(STRING_LOG_FILTER, getLogFilter());
if (display!=null)
{
fd=getFixedFont();
properties.setProperty(STRING_FONT_FIXED_NAME, fd.getName() );
properties.setProperty(STRING_FONT_FIXED_SIZE, ""+fd.getHeight() );
properties.setProperty(STRING_FONT_FIXED_STYLE, ""+fd.getStyle() );
fd=getDefaultFont();
properties.setProperty(STRING_FONT_DEFAULT_NAME, fd.getName());
properties.setProperty(STRING_FONT_DEFAULT_SIZE, ""+fd.getHeight() );
properties.setProperty(STRING_FONT_DEFAULT_STYLE, ""+fd.getStyle() );
fd=getDefaultFont();
properties.setProperty(STRING_FONT_GRAPH_NAME, fd.getName() );
properties.setProperty(STRING_FONT_GRAPH_SIZE, ""+fd.getHeight() );
properties.setProperty(STRING_FONT_GRAPH_STYLE, ""+fd.getStyle() );
fd=getDefaultFont();
properties.setProperty(STRING_FONT_GRID_NAME, fd.getName() );
properties.setProperty(STRING_FONT_GRID_SIZE, ""+fd.getHeight() );
properties.setProperty(STRING_FONT_GRID_STYLE, ""+fd.getStyle() );
fd=getDefaultFont();
properties.setProperty(STRING_FONT_NOTE_NAME, fd.getName() );
properties.setProperty(STRING_FONT_NOTE_SIZE, ""+fd.getHeight() );
properties.setProperty(STRING_FONT_NOTE_STYLE, ""+fd.getStyle() );
col=getBackgroundRGB();
properties.setProperty(STRING_BACKGROUND_COLOR_R, ""+col.red );
properties.setProperty(STRING_BACKGROUND_COLOR_G, ""+col.green);
properties.setProperty(STRING_BACKGROUND_COLOR_B, ""+col.blue );
col=getGraphColorRGB();
properties.setProperty(STRING_GRAPH_COLOR_R, ""+col.red );
properties.setProperty(STRING_GRAPH_COLOR_G, ""+col.green );
properties.setProperty(STRING_GRAPH_COLOR_B, ""+col.blue );
properties.setProperty(STRING_ICON_SIZE, ""+getIconSize());
properties.setProperty(STRING_LINE_WIDTH, ""+getLineWidth());
properties.setProperty(STRING_SHADOW_SIZE, ""+getShadowSize());
properties.setProperty(STRING_MAX_UNDO, ""+getMaxUndo());
setSashWeights(getSashWeights());
}
}
public boolean loadProps()
{
try
{
properties.load(new FileInputStream(getFilename()));
}
catch(Exception e)
{
return false;
}
return true;
}
public void storeScreens()
{
// Add screens hastable to properties..
Enumeration keys = screens.keys();
int nr=1;
while (keys.hasMoreElements())
{
String name = (String)keys.nextElement();
properties.setProperty("ScreenName"+nr, name);
WindowProperty winprop = (WindowProperty)screens.get(name);
properties.setProperty(STRING_SIZE_MAX+nr, winprop.isMaximized()?"Y":"N");
if (winprop.getRectangle()!=null)
{
properties.setProperty(STRING_SIZE_X+nr, ""+winprop.getX());
properties.setProperty(STRING_SIZE_Y+nr, ""+winprop.getY());
properties.setProperty(STRING_SIZE_W+nr, ""+winprop.getWidth());
properties.setProperty(STRING_SIZE_H+nr, ""+winprop.getHeight());
}
nr++;
}
}
public void loadScreens()
{
screens = new Hashtable();
int nr = 1;
String name = properties.getProperty("ScreenName"+nr);
while (name!=null)
{
boolean max = "Y".equalsIgnoreCase(properties.getProperty(STRING_SIZE_MAX+nr));
int x = Const.toInt(properties.getProperty(STRING_SIZE_X+nr), 0);
int y = Const.toInt(properties.getProperty(STRING_SIZE_Y+nr), 0);
int w = Const.toInt(properties.getProperty(STRING_SIZE_W+nr), 320);
int h = Const.toInt(properties.getProperty(STRING_SIZE_H+nr), 200);
WindowProperty winprop = new WindowProperty(name, max, x, y, w, h);
screens.put(name, winprop);
nr++;
name = properties.getProperty("ScreenName"+nr);
}
}
public void saveProps()
{
storeScreens();
try
{
properties.store(new FileOutputStream(new File(getFilename())), "Kettle Properties file");
// System.out.println("properties saved");
}
catch(IOException e)
{
;
}
}
public void setLastFiles(String lf[], String ld[], boolean lt[], String lr[])
{
if (lf.length>Const.MAX_FILE_HIST)
{
lastfiles=new String [Const.MAX_FILE_HIST];
lastdirs =new String [Const.MAX_FILE_HIST];
lasttypes=new boolean[Const.MAX_FILE_HIST];
lastrepos=new String [Const.MAX_FILE_HIST];
for (int i=0;i<Const.MAX_FILE_HIST;i++)
{
lastfiles[i]=lf[i];
lastdirs [i]=ld[i];
lasttypes[i]=lt[i];
lastrepos[i]=lr[i];
}
}
else
{
lastfiles=lf;
lastdirs =ld;
lasttypes=lt;
lastrepos=lr;
}
// Cap it off at Const.MAX_FILE_HIST
properties.setProperty("lastfiles", ""+lf.length);
for (int i=0;i<lf.length;i++)
{
properties.setProperty("lastfile"+(i+1), lf[i]==null?"":lf[i]);
properties.setProperty("lastdir"+(i+1), ld[i]==null?"":ld[i]);
properties.setProperty("lasttype"+(i+1), lt[i]?"Y":"N");
properties.setProperty("lastrepo"+(i+1), lr[i]==null?"":lr[i]);
}
}
/**
* Add a last opened file to the top of the recently used list.
* @param lf The name of the file or transformation
* @param ld The repository directory path, null in case lf is an XML file
* @param lt True if the file was loaded from repository, false if ld is an XML file.
* @param lr The name of the repository the file was loaded from or save to.
*/
public void addLastFile(int propType, String lf, String ld, boolean lt, String lr)
{
if (propType!=getType()) return;
// System.out.println("Add last file ("+lf+", "+ld+", "+lt+", "+lr+")");
boolean exists=false;
int idx=-1;
for (int i=0;i<lastfiles.length;i++)
{
if ( lf.equalsIgnoreCase(lastfiles[i]) &&
lasttypes[i]==lt &&
- ld!=null && ld.equalsIgnoreCase(lastdirs[i])
+ (ld==null || ld.equalsIgnoreCase(lastdirs[i]))
)
{
exists=true;
idx=i;
}
}
// System.out.println("exists = "+exists+" idx="+idx);
if (!exists)
{
String newlf[] = new String [lastfiles.length+1];
String newld[] = new String [lastfiles.length+1];
boolean newlt[] = new boolean[lastfiles.length+1];
String newlr[] = new String [lastfiles.length+1];
for (int i=0;i<newlf.length;i++)
{
if (i==0)
{
newlf[i] = lf;
newld[i] = ld;
newlt[i] = lt;
newlr[i] = lt?lr:"";
}
else
{
newlf[i] = lastfiles[i-1];
newld[i] = lastdirs [i-1];
newlt[i] = lasttypes[i-1];
newlr[i] = lastrepos[i-1];
}
}
setLastFiles(newlf, newld, newlt, newlr);
}
else
{
// put the last used item on top!
// This is item idx
String newlf[] = new String[lastfiles.length];
String newld[] = new String[lastfiles.length];
boolean newlt[] = new boolean[lastfiles.length];
String newlr[] = new String[lastfiles.length];
newlf[0] = lf; // At least one because one exists...
newld[0] = ld;
newlt[0] = lt;
newlr[0] = lt?lr:"";
// Move items down unless i>idx
for (int i=1;i<lastfiles.length;i++)
{
if (i<=idx)
{
newlf[i]=lastfiles[i-1];
newld[i]=lastdirs [i-1];
newlt[i]=lasttypes[i-1];
newlr[i]=lastrepos[i-1];
}
else
{
newlf[i]=lastfiles[i];
newld[i]=lastdirs [i];
newlt[i]=lasttypes[i];
newlr[i]=lastrepos[i];
}
}
setLastFiles(newlf, newld, newlt, newlr);
}
}
public String[] getLastFiles()
{
int nr = Const.toInt(properties.getProperty("lastfiles"), 0);
String lf[] = new String[nr];
for (int i=0;i<nr;i++)
{
lf[i] = properties.getProperty("lastfile"+(i+1), "");
}
return lf;
}
public String[] getLastDirs()
{
int nr = Const.toInt(properties.getProperty("lastfiles"), 0);
String ld[] = new String[nr];
for (int i=0;i<nr;i++)
{
ld[i] = properties.getProperty("lastdir"+(i+1), "");
}
return ld;
}
public boolean[] getLastTypes()
{
int nr = Const.toInt(properties.getProperty("lastfiles"), 0);
boolean lt[] = new boolean[nr];
for (int i=0;i<nr;i++)
{
lt[i] = "Y".equalsIgnoreCase(properties.getProperty("lasttype"+(i+1), "N"));
}
return lt;
}
public String[] getLastRepositories()
{
String snr = properties.getProperty("lastfiles");
int nr = Const.toInt(snr, 0);
String lr[] = new String[nr];
for (int i=0;i<nr;i++)
{
lr[i] = properties.getProperty("lastrepo"+(i+1));
}
return lr;
}
public void setLogLevel(String level)
{
properties.setProperty(STRING_LOG_LEVEL, level);
}
public String getLogLevel()
{
String level = properties.getProperty(STRING_LOG_LEVEL, "Basic");
return level;
}
public void setLogFilter(String filter)
{
properties.setProperty(STRING_LOG_FILTER, Const.NVL(filter, ""));
}
public String getLogFilter()
{
String level = properties.getProperty(STRING_LOG_FILTER, "");
return level;
}
public void setFixedFont(FontData fd)
{
properties.setProperty(STRING_FONT_FIXED_NAME, fd.getName() );
properties.setProperty(STRING_FONT_FIXED_SIZE, ""+fd.getHeight() );
properties.setProperty(STRING_FONT_FIXED_STYLE, ""+fd.getStyle() );
}
public FontData getFixedFont()
{
// Default:?
String name = properties.getProperty(STRING_FONT_FIXED_NAME, Const.FONT_FIXED_NAME);
String ssize = properties.getProperty(STRING_FONT_FIXED_SIZE);
String sstyle = properties.getProperty(STRING_FONT_FIXED_STYLE);
int size = Const.toInt(ssize, Const.FONT_FIXED_SIZE);
int style = Const.toInt(sstyle, Const.FONT_FIXED_TYPE);
FontData fd = new FontData(name, size, style);
return fd;
}
public void setDefaultFont(FontData fd)
{
if (fd!=null)
{
properties.setProperty(STRING_FONT_DEFAULT_NAME, fd.getName() );
properties.setProperty(STRING_FONT_DEFAULT_SIZE, ""+fd.getHeight() );
properties.setProperty(STRING_FONT_DEFAULT_STYLE, ""+fd.getStyle() );
}
}
public FontData getDefaultFont()
{
if (isOSLookShown()) return null;
FontData def = getDefaultFontData();
String name = properties.getProperty(STRING_FONT_DEFAULT_NAME);
String ssize = properties.getProperty(STRING_FONT_DEFAULT_SIZE);
String sstyle = properties.getProperty(STRING_FONT_DEFAULT_STYLE);
int size = Const.toInt(ssize, def.getHeight());
int style = Const.toInt(sstyle, def.getStyle());
if (name==null || name.length()==0)
{
name = def.getName();
size = def.getHeight();
style=def.getStyle();
}
// Still nothing?
if (name==null || name.length()==0)
{
name = "Arial";
size = 10;
style = SWT.NORMAL;
}
// System.out.println("Font default: ["+name+"], size="+size+", style="+style+", default font name = "+def.getName());
FontData fd = new FontData(name, size, style);
return fd;
}
public void setGraphFont(FontData fd)
{
properties.setProperty(STRING_FONT_GRAPH_NAME, fd.getName() );
properties.setProperty(STRING_FONT_GRAPH_SIZE, ""+fd.getHeight() );
properties.setProperty(STRING_FONT_GRAPH_STYLE, ""+fd.getStyle() );
}
public FontData getGraphFont()
{
FontData def = getDefaultFontData();
String name = properties.getProperty(STRING_FONT_GRAPH_NAME, def.getName());
String ssize = properties.getProperty(STRING_FONT_GRAPH_SIZE);
String sstyle = properties.getProperty(STRING_FONT_GRAPH_STYLE);
int size = Const.toInt(ssize, def.getHeight());
int style = Const.toInt(sstyle, def.getStyle());
FontData fd = new FontData(name, size, style);
return fd;
}
public void setGridFont(FontData fd)
{
properties.setProperty(STRING_FONT_GRID_NAME, fd.getName() );
properties.setProperty(STRING_FONT_GRID_SIZE, ""+fd.getHeight() );
properties.setProperty(STRING_FONT_GRID_STYLE, ""+fd.getStyle() );
}
public FontData getGridFont()
{
FontData def = getDefaultFontData();
String name = properties.getProperty(STRING_FONT_GRID_NAME, def.getName());
String ssize = properties.getProperty(STRING_FONT_GRID_SIZE);
String sstyle = properties.getProperty(STRING_FONT_GRID_STYLE);
int size = Const.toInt(ssize, def.getHeight());
int style = Const.toInt(sstyle, def.getStyle());
FontData fd = new FontData(name, size, style);
return fd;
}
public void setNoteFont(FontData fd)
{
properties.setProperty(STRING_FONT_NOTE_NAME, fd.getName() );
properties.setProperty(STRING_FONT_NOTE_SIZE, ""+fd.getHeight() );
properties.setProperty(STRING_FONT_NOTE_STYLE, ""+fd.getStyle() );
}
public FontData getNoteFont()
{
FontData def = getDefaultFontData();
String name = properties.getProperty(STRING_FONT_NOTE_NAME, def.getName());
String ssize = properties.getProperty(STRING_FONT_NOTE_SIZE);
String sstyle = properties.getProperty(STRING_FONT_NOTE_STYLE);
int size = Const.toInt(ssize, def.getHeight());
int style = Const.toInt(sstyle, def.getStyle());
FontData fd = new FontData(name, size, style);
return fd;
}
public void setBackgroundRGB(RGB c)
{
properties.setProperty(STRING_BACKGROUND_COLOR_R, c!=null?""+c.red:"" );
properties.setProperty(STRING_BACKGROUND_COLOR_G, c!=null?""+c.green:"" );
properties.setProperty(STRING_BACKGROUND_COLOR_B, c!=null?""+c.blue:"" );
}
public RGB getBackgroundRGB()
{
int r = Const.toInt(properties.getProperty(STRING_BACKGROUND_COLOR_R), Const.COLOR_BACKGROUND_RED); // Defaut:
int g = Const.toInt(properties.getProperty(STRING_BACKGROUND_COLOR_G), Const.COLOR_BACKGROUND_GREEN);
int b = Const.toInt(properties.getProperty(STRING_BACKGROUND_COLOR_B), Const.COLOR_BACKGROUND_BLUE);
RGB rgb = new RGB(r,g,b);
return rgb;
}
/**
* @deprecated
* @return The background RGB color.
*/
public RGB getBackupgroundRGB()
{
return getBackgroundRGB();
}
public void setGraphColorRGB(RGB c)
{
properties.setProperty(STRING_GRAPH_COLOR_R, ""+c.red );
properties.setProperty(STRING_GRAPH_COLOR_G, ""+c.green );
properties.setProperty(STRING_GRAPH_COLOR_B, ""+c.blue );
}
public RGB getGraphColorRGB()
{
int r = Const.toInt(properties.getProperty(STRING_GRAPH_COLOR_R), Const.COLOR_GRAPH_RED); // default White
int g = Const.toInt(properties.getProperty(STRING_GRAPH_COLOR_G), Const.COLOR_GRAPH_GREEN);
int b = Const.toInt(properties.getProperty(STRING_GRAPH_COLOR_B), Const.COLOR_GRAPH_BLUE);
RGB rgb = new RGB(r,g,b);
return rgb;
}
public void setTabColorRGB(RGB c)
{
properties.setProperty(STRING_TAB_COLOR_R, ""+c.red );
properties.setProperty(STRING_TAB_COLOR_G, ""+c.green );
properties.setProperty(STRING_TAB_COLOR_B, ""+c.blue );
}
public RGB getTabColorRGB()
{
int r = Const.toInt(properties.getProperty(STRING_TAB_COLOR_R), Const.COLOR_TAB_RED); // default White
int g = Const.toInt(properties.getProperty(STRING_TAB_COLOR_G), Const.COLOR_TAB_GREEN);
int b = Const.toInt(properties.getProperty(STRING_TAB_COLOR_B), Const.COLOR_TAB_BLUE);
RGB rgb = new RGB(r,g,b);
return rgb;
}
public void setIconSize(int size)
{
properties.setProperty(STRING_ICON_SIZE, ""+size );
}
public int getIconSize()
{
return Const.toInt(properties.getProperty(STRING_ICON_SIZE), Const.ICON_SIZE);
}
public void setLineWidth(int width)
{
properties.setProperty(STRING_LINE_WIDTH, ""+width );
}
public int getLineWidth()
{
return Const.toInt(properties.getProperty(STRING_LINE_WIDTH), Const.LINE_WIDTH);
}
public void setShadowSize(int size)
{
properties.setProperty(STRING_SHADOW_SIZE, ""+size );
}
public int getShadowSize()
{
return Const.toInt(properties.getProperty(STRING_SHADOW_SIZE), Const.SHADOW_SIZE);
}
/*
* LICENCE INFO...
*/
public void setLastTrans(String trans)
{
properties.setProperty(STRING_LAST_PREVIEW_TRANS, trans);
}
public String getLastTrans()
{
return properties.getProperty(STRING_LAST_PREVIEW_TRANS, "");
}
public void setLastPreview(String lastpreview[], int stepsize[])
{
properties.setProperty(STRING_LAST_PREVIEW_STEP, ""+lastpreview.length);
for (int i=0;i<lastpreview.length;i++)
{
properties.setProperty(STRING_LAST_PREVIEW_STEP+(i+1), lastpreview[i]);
properties.setProperty(STRING_LAST_PREVIEW_SIZE+(i+1), ""+stepsize[i]);
}
}
public String[] getLastPreview()
{
String snr = properties.getProperty(STRING_LAST_PREVIEW_STEP);
int nr = Const.toInt(snr, 0);
String lp[] = new String[nr];
for (int i=0;i<nr;i++)
{
lp[i] = properties.getProperty(STRING_LAST_PREVIEW_STEP+(i+1), "");
}
return lp;
}
public int[] getLastPreviewSize()
{
String snr = properties.getProperty(STRING_LAST_PREVIEW_STEP);
int nr = Const.toInt(snr, 0);
int si[] = new int[nr];
for (int i=0;i<nr;i++)
{
si[i] = Const.toInt(properties.getProperty(STRING_LAST_PREVIEW_SIZE+(i+1), ""), 0);
}
return si;
}
public FontData getDefaultFontData()
{
return display.getSystemFont().getFontData()[0];
}
public void setMaxUndo(int max)
{
properties.setProperty(STRING_MAX_UNDO, ""+max );
}
public int getMaxUndo()
{
return Const.toInt(properties.getProperty(STRING_MAX_UNDO), Const.MAX_UNDO);
}
public void setMiddlePct(int pct)
{
properties.setProperty(STRING_MIDDLE_PCT, ""+pct );
}
public int getMiddlePct()
{
return Const.toInt(properties.getProperty(STRING_MIDDLE_PCT), Const.MIDDLE_PCT);
}
public void setScreen(WindowProperty winprop)
{
screens.put(winprop.getName(), winprop);
}
public WindowProperty getScreen(String windowname)
{
if (windowname==null) return null;
return (WindowProperty)screens.get(windowname);
}
public void setSashWeights(int w[])
{
properties.setProperty(STRING_SASH_W1, ""+w[0]);
properties.setProperty(STRING_SASH_W2, ""+w[1]);
}
public int[] getSashWeights()
{
int w1 = Const.toInt(properties.getProperty(STRING_SASH_W1), 25);
int w2 = Const.toInt(properties.getProperty(STRING_SASH_W2), 75);
return new int[] { w1, w2 };
}
public void setTipNr(int nr)
{
properties.setProperty(STRING_TIP_NR, ""+nr);
}
public int getTipNr()
{
return Const.toInt(properties.getProperty(STRING_TIP_NR), 0);
}
public void setShowTips(boolean show)
{
properties.setProperty(STRING_SHOW_TIPS, show?"Y":"N");
}
public boolean showTips()
{
String show=properties.getProperty(STRING_SHOW_TIPS);
return !"N".equalsIgnoreCase(show);
}
public void setUseDBCache(boolean use)
{
properties.setProperty(STRING_USE_DB_CACHE, use?"Y":"N");
}
public boolean useDBCache()
{
String use=properties.getProperty(STRING_USE_DB_CACHE);
return !"N".equalsIgnoreCase(use);
}
public void setOpenLastFile(boolean open)
{
properties.setProperty(STRING_OPEN_LAST_FILE, open?"Y":"N");
}
public boolean openLastFile()
{
String open=properties.getProperty(STRING_OPEN_LAST_FILE);
return !"N".equalsIgnoreCase(open);
}
public void setLastRepository(String repname)
{
properties.setProperty(STRING_LAST_REPOSITORY, repname);
}
public String getLastRepository()
{
return properties.getProperty(STRING_LAST_REPOSITORY);
}
public void setLastRepositoryLogin(String login)
{
properties.setProperty(STRING_LAST_REPOSITORY_LOGIN, login);
}
public String getLastRepositoryLogin()
{
return properties.getProperty(STRING_LAST_REPOSITORY_LOGIN);
}
public void setAutoSave(boolean autosave)
{
properties.setProperty(STRING_AUTO_SAVE, autosave?"Y":"N");
}
public boolean getAutoSave()
{
String autosave=properties.getProperty(STRING_AUTO_SAVE);
return "Y".equalsIgnoreCase(autosave); // Default = OFF
}
public void setSaveConfirmation(boolean saveconf)
{
properties.setProperty(STRING_SAVE_CONF, saveconf?"Y":"N");
}
public boolean getSaveConfirmation()
{
String saveconf=properties.getProperty(STRING_SAVE_CONF);
return "Y".equalsIgnoreCase(saveconf); // Default = OFF
}
public void setAutoSplit(boolean autosplit)
{
properties.setProperty(STRING_AUTO_SPLIT, autosplit?"Y":"N");
}
public boolean getAutoSplit()
{
String autosplit=properties.getProperty(STRING_AUTO_SPLIT);
return "Y".equalsIgnoreCase(autosplit); // Default = OFF
}
public void setOnlyActiveSteps(boolean only)
{
properties.setProperty(STRING_ONLY_ACTIVE_STEPS, only?"Y":"N");
}
public boolean getOnlyActiveSteps()
{
String only = properties.getProperty(STRING_ONLY_ACTIVE_STEPS, "N");
return "Y".equalsIgnoreCase(only); // Default: show active steps.
}
/**
* @param parameterName The parameter name
* @param defaultValue The default value in case the parameter doesn't exist yet.
* @return The custom parameter
*/
public String getCustomParameter(String parameterName, String defaultValue)
{
return properties.getProperty(STRING_CUSTOM_PARAMETER+parameterName, defaultValue);
}
/**
* Set the custom parameter
* @param parameterName The name of the parameter
* @param value The value to be stored in the properties file.
*/
public void setCustomParameter(String parameterName, String value)
{
properties.setProperty(STRING_CUSTOM_PARAMETER+parameterName, value);
}
public void clearCustomParameters()
{
Enumeration keys = properties.keys();
while (keys.hasMoreElements())
{
String key = (String) keys.nextElement();
if (key.startsWith(STRING_CUSTOM_PARAMETER)) // Clear this one
{
properties.remove(key);
}
}
}
public boolean showRepositoriesDialogAtStartup()
{
String show = properties.getProperty(STRING_START_SHOW_REPOSITORIES, "Y");
return "Y".equalsIgnoreCase(show); // Default: show warning before tool exit.
}
public void setExitWarningShown(boolean show)
{
properties.setProperty(STRING_SHOW_EXIT_WARNING, show?"Y":"N");
}
public boolean isAntiAliasingEnabled()
{
String anti = properties.getProperty(STRING_ANTI_ALIASING, "N");
return "Y".equalsIgnoreCase(anti); // Default: don't do anti-aliasing
}
public void setAntiAliasingEnabled(boolean anti)
{
properties.setProperty(STRING_ANTI_ALIASING, anti?"Y":"N");
}
public boolean showExitWarning()
{
String show = properties.getProperty(STRING_SHOW_EXIT_WARNING, "Y");
return "Y".equalsIgnoreCase(show); // Default: show repositories dialog at startup
}
public void setRepositoriesDialogAtStartupShown(boolean show)
{
properties.setProperty(STRING_START_SHOW_REPOSITORIES, show?"Y":"N");
}
public boolean isOSLookShown()
{
String show = properties.getProperty(STRING_SHOW_OS_LOOK, "N");
return "Y".equalsIgnoreCase(show); // Default: don't show gray dialog boxes, show Kettle look.
}
public void setOSLookShown(boolean show)
{
properties.setProperty(STRING_SHOW_OS_LOOK, show?"Y":"N");
}
public static final void setGCFont(GC gc, Device device, FontData fontData)
{
if (Const.getOS().startsWith("Windows"))
{
Font font = new Font(device, fontData);
gc.setFont( font );
font.dispose();
}
else
{
gc.setFont( device.getSystemFont() );
}
}
public void setLook(Control widget)
{
setLook(widget, WIDGET_STYLE_DEFAULT);
}
public void setLook(Control control, int style)
{
if (!Const.getOS().startsWith("Windows")) return;
if (props.isOSLookShown()) return;
GUIResource gui = GUIResource.getInstance();
Font font = null;
Color background = null;
// Color tabColor = null;
switch(style)
{
case WIDGET_STYLE_DEFAULT :
background = gui.getColorBackground();
font = null; // GUIResource.getInstance().getFontDefault();
break;
case WIDGET_STYLE_FIXED :
background = gui.getColorBackground();
font = gui.getFontFixed();
break;
case WIDGET_STYLE_TABLE :
background = gui.getColorBackground();
font = null; // gui.getFontGrid();
break;
case WIDGET_STYLE_NOTEPAD :
background = gui.getColorBackground();
font = gui.getFontNote();
break;
case WIDGET_STYLE_GRAPH :
background = gui.getColorBackground();
font = gui.getFontGraph();
break;
case WIDGET_STYLE_TAB :
background = gui.getColorBackground();
// font = gui.getFontDefault();
((CTabFolder)control).setSimple(false);
((CTabFolder)control).setBorderVisible(false);
((CTabFolder)control).setSelectionBackground(display.getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND_GRADIENT));
break;
default :
background = gui.getColorBackground();
font = null; // gui.getFontDefault();
break;
}
if (font!=null)
{
control.setFont(font);
}
if (background!=null)
{
control.setBackground(background);
}
}
public static void setTableItemLook(TableItem item, Display disp)
{
if (!Const.getOS().startsWith("Windows")) return;
Font gridFont = null; // GUIResource.getInstance().getFontGrid();
Color background = GUIResource.getInstance().getColorBackground();
if (gridFont!=null)
{
item.setFont(gridFont);
}
if (background!=null)
{
item.setBackground(background);
}
}
/**
* Convert "argument 1" to 1
* @param value The value to determine the argument number for
* @return The argument number
*/
public static final int getArgumentNumber(Value value)
{
if (value!=null && value.getName().startsWith("Argument "))
{
return Const.toInt(value.getName().substring("Argument ".length()), -1);
}
return -1;
}
public static final String[] convertArguments(Row row)
{
String args[] = new String[10];
for (int i=0;i<row.size();i++)
{
Value value = row.getValue(i);
int argNr = getArgumentNumber(value);
if (argNr>=0 && argNr<10)
{
args[argNr] = value.getString();
}
}
return args;
}
/**
* Set the last arguments so that we can recall it the next time...
*
* @param args the arguments to save
*/
public void setLastArguments(String args[])
{
for (int i=0;i<args.length;i++)
{
if (args[i]!=null)
{
properties.setProperty(STRING_LAST_ARGUMENT+"_"+i, args[i]);
}
}
}
/** Get the last entered arguments...
*
* @return the last entered arguments...
*/
public String[] getLastArguments()
{
String args[] = new String[10];
for (int i=0;i<args.length;i++)
{
args[i] = properties.getProperty(STRING_LAST_ARGUMENT+"_"+i);
}
return args;
}
/**
* Get the list of recently used step
* @return a list of strings: the plugin IDs
*/
public List getPluginHistory()
{
return pluginHistory;
}
/**
* Set the last plugin used in the plugin history
* @param pluginID The last plugin ID
*/
public void addPluginHistory(String pluginID)
{
// Add at the front
pluginHistory.add(0, pluginID);
// Remove in the rest of the list
for (int i=pluginHistory.size()-1;i>0;i--)
{
String id = (String)pluginHistory.get(i);
if (id.equalsIgnoreCase(pluginID)) pluginHistory.remove(i);
}
savePluginHistory();
}
/**
* Load the plugin history from the properties file
*
*/
private void loadPluginHistory()
{
pluginHistory = new ArrayList();
int i=0;
String pluginID = properties.getProperty(STRING_PLUGIN_HISTORY+"_"+i);
while (pluginID!=null)
{
pluginHistory.add(pluginID);
i++;
pluginID = properties.getProperty(STRING_PLUGIN_HISTORY+"_"+i);
}
}
private void savePluginHistory()
{
for (int i=0;i<pluginHistory.size();i++)
{
String id = (String) pluginHistory.get(i);
properties.setProperty(STRING_PLUGIN_HISTORY+"_"+i, id);
}
}
/**
* @return Returns the display.
*/
public Display getDisplay()
{
return display;
}
/**
* @param display The display to set.
*/
public void setDisplay(Display display)
{
this.display = display;
}
public void setDefaultPreviewSize(int size)
{
properties.setProperty(STRING_DEFAULT_PREVIEW_SIZE, ""+size);
}
public int getDefaultPreviewSize()
{
return Const.toInt(properties.getProperty(STRING_DEFAULT_PREVIEW_SIZE), 100);
}
public boolean areOnlyUsedConnectionsSavedToXML()
{
String show = properties.getProperty(STRING_ONLY_USED_DB_TO_XML, "N");
return !"N".equalsIgnoreCase(show); // Default: save all connections
}
public void setOnlyUsedConnectionsSavedToXML(boolean onlyUsedConnections)
{
properties.setProperty(STRING_ONLY_USED_DB_TO_XML, onlyUsedConnections?"Y":"N");
}
}
| true | true | public void addLastFile(int propType, String lf, String ld, boolean lt, String lr)
{
if (propType!=getType()) return;
// System.out.println("Add last file ("+lf+", "+ld+", "+lt+", "+lr+")");
boolean exists=false;
int idx=-1;
for (int i=0;i<lastfiles.length;i++)
{
if ( lf.equalsIgnoreCase(lastfiles[i]) &&
lasttypes[i]==lt &&
ld!=null && ld.equalsIgnoreCase(lastdirs[i])
)
{
exists=true;
idx=i;
}
}
// System.out.println("exists = "+exists+" idx="+idx);
if (!exists)
{
String newlf[] = new String [lastfiles.length+1];
String newld[] = new String [lastfiles.length+1];
boolean newlt[] = new boolean[lastfiles.length+1];
String newlr[] = new String [lastfiles.length+1];
for (int i=0;i<newlf.length;i++)
{
if (i==0)
{
newlf[i] = lf;
newld[i] = ld;
newlt[i] = lt;
newlr[i] = lt?lr:"";
}
else
{
newlf[i] = lastfiles[i-1];
newld[i] = lastdirs [i-1];
newlt[i] = lasttypes[i-1];
newlr[i] = lastrepos[i-1];
}
}
setLastFiles(newlf, newld, newlt, newlr);
}
else
{
// put the last used item on top!
// This is item idx
String newlf[] = new String[lastfiles.length];
String newld[] = new String[lastfiles.length];
boolean newlt[] = new boolean[lastfiles.length];
String newlr[] = new String[lastfiles.length];
newlf[0] = lf; // At least one because one exists...
newld[0] = ld;
newlt[0] = lt;
newlr[0] = lt?lr:"";
// Move items down unless i>idx
for (int i=1;i<lastfiles.length;i++)
{
if (i<=idx)
{
newlf[i]=lastfiles[i-1];
newld[i]=lastdirs [i-1];
newlt[i]=lasttypes[i-1];
newlr[i]=lastrepos[i-1];
}
else
{
newlf[i]=lastfiles[i];
newld[i]=lastdirs [i];
newlt[i]=lasttypes[i];
newlr[i]=lastrepos[i];
}
}
setLastFiles(newlf, newld, newlt, newlr);
}
}
| public void addLastFile(int propType, String lf, String ld, boolean lt, String lr)
{
if (propType!=getType()) return;
// System.out.println("Add last file ("+lf+", "+ld+", "+lt+", "+lr+")");
boolean exists=false;
int idx=-1;
for (int i=0;i<lastfiles.length;i++)
{
if ( lf.equalsIgnoreCase(lastfiles[i]) &&
lasttypes[i]==lt &&
(ld==null || ld.equalsIgnoreCase(lastdirs[i]))
)
{
exists=true;
idx=i;
}
}
// System.out.println("exists = "+exists+" idx="+idx);
if (!exists)
{
String newlf[] = new String [lastfiles.length+1];
String newld[] = new String [lastfiles.length+1];
boolean newlt[] = new boolean[lastfiles.length+1];
String newlr[] = new String [lastfiles.length+1];
for (int i=0;i<newlf.length;i++)
{
if (i==0)
{
newlf[i] = lf;
newld[i] = ld;
newlt[i] = lt;
newlr[i] = lt?lr:"";
}
else
{
newlf[i] = lastfiles[i-1];
newld[i] = lastdirs [i-1];
newlt[i] = lasttypes[i-1];
newlr[i] = lastrepos[i-1];
}
}
setLastFiles(newlf, newld, newlt, newlr);
}
else
{
// put the last used item on top!
// This is item idx
String newlf[] = new String[lastfiles.length];
String newld[] = new String[lastfiles.length];
boolean newlt[] = new boolean[lastfiles.length];
String newlr[] = new String[lastfiles.length];
newlf[0] = lf; // At least one because one exists...
newld[0] = ld;
newlt[0] = lt;
newlr[0] = lt?lr:"";
// Move items down unless i>idx
for (int i=1;i<lastfiles.length;i++)
{
if (i<=idx)
{
newlf[i]=lastfiles[i-1];
newld[i]=lastdirs [i-1];
newlt[i]=lasttypes[i-1];
newlr[i]=lastrepos[i-1];
}
else
{
newlf[i]=lastfiles[i];
newld[i]=lastdirs [i];
newlt[i]=lasttypes[i];
newlr[i]=lastrepos[i];
}
}
setLastFiles(newlf, newld, newlt, newlr);
}
}
|
diff --git a/src/WorldManager.java b/src/WorldManager.java
index 6126e17..142420b 100644
--- a/src/WorldManager.java
+++ b/src/WorldManager.java
@@ -1,80 +1,80 @@
import java.io.File;
import java.util.logging.Logger;
public class WorldManager extends Plugin {
public static final String NAME = "WorldManager";
public static final String VERSION = "0.0.1";
public static final String AUTHOR = "MrTimeShadow";
public static final Logger mclogger = Logger.getLogger("Minecraft");
private WMCommandListener commandListener = new WMCommandListener();
@Override
/**
* Registers the Listener for the needed Hooks
*/
public void initialize() {
this.setName("WorldManager v0.0.1 by MrTimeShadow");
mclogger.info("[WorldManager] Initializing WorldManager!");
PluginLoader loader = etc.getLoader();
this.addCommandListeners(loader);
mclogger.info("[WorldManager] Successfully enabled WorldManager");
mclogger.info("[WorldManager] Loading Worlds...");
loadWorldsOnStartup();
mclogger.info("[WorldManager] Successfully loaded Worlds!");
}
@Override
/**
* Registers the commands
*/
public void enable() {
mclogger.info("[WorldManager] Enabling WorldManager!");
etc.getInstance().addCommand("/wm", "Displays the Help of WorldManager"); //Adds the Command to the help list
}
@Override
/**
* Removes the commands
*/
public void disable() {
etc.getInstance().removeCommand("/wm"); //Removes the Command from the Help list
mclogger.info("[WorldManager] Successfully disabled WorldManager!");
WMWorldConfiguration.saveConfigs();
}
private void addCommandListeners(PluginLoader loader) {
loader.addListener(PluginLoader.Hook.COMMAND, commandListener, this, PluginListener.Priority.MEDIUM);
loader.addListener(PluginLoader.Hook.COMMAND_CHECK, commandListener, this, PluginListener.Priority.MEDIUM);
loader.addListener(PluginLoader.Hook.SERVERCOMMAND, commandListener, this, PluginListener.Priority.MEDIUM);
}
public void loadWorldsOnStartup() {
File path = new File("config/worldmanager/worlds/");
if(!path.isDirectory() || !path.exists()) {
path.mkdirs();
return;
}
for(File f : path.listFiles()) {
if(f.getName().endsWith(".properties")) {
PropertiesFile pf = new PropertiesFile(f.getPath());
boolean load = pf.getBoolean("auto-load");
if(load) {
- String worldname = f.getName().substring(0, f.getName().lastIndexOf('.') - 1);
+ String worldname = f.getName().substring(0, f.getName().lastIndexOf('.'));
mclogger.info("[WorldManager] Loading world " + worldname + "...");
World[] world = etc.getServer().loadWorld(worldname);
new WMWorldConfiguration(world);
}
}
}
}
}
| true | true | public void loadWorldsOnStartup() {
File path = new File("config/worldmanager/worlds/");
if(!path.isDirectory() || !path.exists()) {
path.mkdirs();
return;
}
for(File f : path.listFiles()) {
if(f.getName().endsWith(".properties")) {
PropertiesFile pf = new PropertiesFile(f.getPath());
boolean load = pf.getBoolean("auto-load");
if(load) {
String worldname = f.getName().substring(0, f.getName().lastIndexOf('.') - 1);
mclogger.info("[WorldManager] Loading world " + worldname + "...");
World[] world = etc.getServer().loadWorld(worldname);
new WMWorldConfiguration(world);
}
}
}
}
| public void loadWorldsOnStartup() {
File path = new File("config/worldmanager/worlds/");
if(!path.isDirectory() || !path.exists()) {
path.mkdirs();
return;
}
for(File f : path.listFiles()) {
if(f.getName().endsWith(".properties")) {
PropertiesFile pf = new PropertiesFile(f.getPath());
boolean load = pf.getBoolean("auto-load");
if(load) {
String worldname = f.getName().substring(0, f.getName().lastIndexOf('.'));
mclogger.info("[WorldManager] Loading world " + worldname + "...");
World[] world = etc.getServer().loadWorld(worldname);
new WMWorldConfiguration(world);
}
}
}
}
|
diff --git a/src/com/JTFTP/FileBlocksWriter.java b/src/com/JTFTP/FileBlocksWriter.java
index c0b5bc2..f935e39 100644
--- a/src/com/JTFTP/FileBlocksWriter.java
+++ b/src/com/JTFTP/FileBlocksWriter.java
@@ -1,89 +1,89 @@
package com.JTFTP;
import java.io.*;
/**
* This class write blocks in a file.
*/
public class FileBlocksWriter {
private int index;
private FileOutputStream output;
private int blockLength;
private boolean end;
/**
* Creates a FileBlocksWriter of file specified in filename and writes with blocks of length blockLength
* @param filename is the name of the file.
* @param overwrite indicates wheter overwrite the file if it's exists.
* @param blockLength is the length of blocks
* @throws FileFoundException if file exists and overwrite is false.
* @throws FileNotFoundException if file cannot be opened for any reason.
* @throws SecurityException if can write or create file specified in filename.
*/
public FileBlocksWriter(String filename, boolean overwrite, int blockLength) throws FileFoundException, FileNotFoundException, SecurityException {
File file = new File(filename);
if(file.exists() && !overwrite) {
throw new FileFoundException("File " + filename + "already exists.");
}
if(!file.exists()) {
try {
file.createNewFile();
}catch(IOException e) {
- throw new SecurityException("Can create file " + filename);
+ throw new SecurityException("Can't create file " + filename);
}
}
if(!file.canWrite()) {
- throw new SecurityException("Can write to file " + filename);
+ throw new SecurityException("Can't write to file " + filename);
}
this.blockLength = blockLength;
index = 0;
output = new FileOutputStream(file);
end = false;
}
/**
* Free all resources used.
* @throws IOException if there are any problem.
*/
public void close() throws IOException {
output.close();
}
/**
* Tells if the last block already was writted.
* @return if the last block already was writted.
*/
public boolean hasNext() {
return !end;
}
/**
* Return the next bloc index.
* @return the next index.
*/
public int nextIndex() {
return index;
}
/**
* Write the block b to the file.
* @param b is the block to write.
* @throws EOFException if the last block of file already was writted.
* @throws IOException if a general error ocurred while writting.
*/
public void write(byte[] b) throws IOException {
if(end) {
throw new EOFException("The last block of file already was writted.");
}
if(b.length != blockLength) {
end = true;
if(b.length == 0) {
return;
}
}
output.write(b);
index++;
}
}
| false | true | public FileBlocksWriter(String filename, boolean overwrite, int blockLength) throws FileFoundException, FileNotFoundException, SecurityException {
File file = new File(filename);
if(file.exists() && !overwrite) {
throw new FileFoundException("File " + filename + "already exists.");
}
if(!file.exists()) {
try {
file.createNewFile();
}catch(IOException e) {
throw new SecurityException("Can create file " + filename);
}
}
if(!file.canWrite()) {
throw new SecurityException("Can write to file " + filename);
}
this.blockLength = blockLength;
index = 0;
output = new FileOutputStream(file);
end = false;
}
| public FileBlocksWriter(String filename, boolean overwrite, int blockLength) throws FileFoundException, FileNotFoundException, SecurityException {
File file = new File(filename);
if(file.exists() && !overwrite) {
throw new FileFoundException("File " + filename + "already exists.");
}
if(!file.exists()) {
try {
file.createNewFile();
}catch(IOException e) {
throw new SecurityException("Can't create file " + filename);
}
}
if(!file.canWrite()) {
throw new SecurityException("Can't write to file " + filename);
}
this.blockLength = blockLength;
index = 0;
output = new FileOutputStream(file);
end = false;
}
|
diff --git a/crypto/src/org/bouncycastle/crypto/tls/TlsProtocolHandler.java b/crypto/src/org/bouncycastle/crypto/tls/TlsProtocolHandler.java
index 7b05b7a7..04a2de36 100644
--- a/crypto/src/org/bouncycastle/crypto/tls/TlsProtocolHandler.java
+++ b/crypto/src/org/bouncycastle/crypto/tls/TlsProtocolHandler.java
@@ -1,1171 +1,1171 @@
package org.bouncycastle.crypto.tls;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.crypto.prng.ThreadedSeedGenerator;
import org.bouncycastle.util.Arrays;
/**
* An implementation of all high level protocols in TLS 1.0.
*/
public class TlsProtocolHandler
{
private static final Integer EXT_RenegotiationInfo = Integer.valueOf(ExtensionType.renegotiation_info);
/*
* Our Connection states
*/
private static final short CS_CLIENT_HELLO_SEND = 1;
private static final short CS_SERVER_HELLO_RECEIVED = 2;
private static final short CS_SERVER_CERTIFICATE_RECEIVED = 3;
private static final short CS_SERVER_KEY_EXCHANGE_RECEIVED = 4;
private static final short CS_CERTIFICATE_REQUEST_RECEIVED = 5;
private static final short CS_SERVER_HELLO_DONE_RECEIVED = 6;
private static final short CS_CLIENT_KEY_EXCHANGE_SEND = 7;
private static final short CS_CERTIFICATE_VERIFY_SEND = 8;
private static final short CS_CLIENT_CHANGE_CIPHER_SPEC_SEND = 9;
private static final short CS_CLIENT_FINISHED_SEND = 10;
private static final short CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED = 11;
private static final short CS_DONE = 12;
private static final byte[] emptybuf = new byte[0];
private static final String TLS_ERROR_MESSAGE = "Internal TLS error, this could be an attack";
/*
* Queues for data from some protocols.
*/
private ByteQueue applicationDataQueue = new ByteQueue();
private ByteQueue changeCipherSpecQueue = new ByteQueue();
private ByteQueue alertQueue = new ByteQueue();
private ByteQueue handshakeQueue = new ByteQueue();
/*
* The Record Stream we use
*/
private RecordStream rs;
private SecureRandom random;
private TlsInputStream tlsInputStream = null;
private TlsOutputStream tlsOutputStream = null;
private boolean closed = false;
private boolean failedWithError = false;
private boolean appDataReady = false;
private Hashtable clientExtensions;
private SecurityParameters securityParameters = null;
private TlsClient tlsClient = null;
private int[] offeredCipherSuites = null;
private short[] offeredCompressionMethods = null;
private TlsKeyExchange keyExchange = null;
private short connection_state = 0;
private static SecureRandom createSecureRandom()
{
/*
* We use our threaded seed generator to generate a good random seed. If the user
* has a better random seed, he should use the constructor with a SecureRandom.
*/
ThreadedSeedGenerator tsg = new ThreadedSeedGenerator();
SecureRandom random = new SecureRandom();
/*
* Hopefully, 20 bytes in fast mode are good enough.
*/
random.setSeed(tsg.generateSeed(20, true));
return random;
}
public TlsProtocolHandler(InputStream is, OutputStream os)
{
this(is, os, createSecureRandom());
}
public TlsProtocolHandler(InputStream is, OutputStream os, SecureRandom sr)
{
this.rs = new RecordStream(this, is, os);
this.random = sr;
}
SecureRandom getRandom()
{
return random;
}
protected void processData(short protocol, byte[] buf, int offset, int len) throws IOException
{
/*
* Have a look at the protocol type, and add it to the correct queue.
*/
switch (protocol)
{
case ContentType.change_cipher_spec:
changeCipherSpecQueue.addData(buf, offset, len);
processChangeCipherSpec();
break;
case ContentType.alert:
alertQueue.addData(buf, offset, len);
processAlert();
break;
case ContentType.handshake:
handshakeQueue.addData(buf, offset, len);
processHandshake();
break;
case ContentType.application_data:
if (!appDataReady)
{
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
applicationDataQueue.addData(buf, offset, len);
processApplicationData();
break;
default:
/*
* Uh, we don't know this protocol.
*
* RFC2246 defines on page 13, that we should ignore this.
*/
}
}
private void processHandshake() throws IOException
{
boolean read;
do
{
read = false;
/*
* We need the first 4 bytes, they contain type and length of the message.
*/
if (handshakeQueue.size() >= 4)
{
byte[] beginning = new byte[4];
handshakeQueue.read(beginning, 0, 4, 0);
ByteArrayInputStream bis = new ByteArrayInputStream(beginning);
short type = TlsUtils.readUint8(bis);
int len = TlsUtils.readUint24(bis);
/*
* Check if we have enough bytes in the buffer to read the full message.
*/
if (handshakeQueue.size() >= (len + 4))
{
/*
* Read the message.
*/
byte[] buf = new byte[len];
handshakeQueue.read(buf, 0, len, 4);
handshakeQueue.removeData(len + 4);
/*
* RFC 2246 7.4.9. The value handshake_messages includes all handshake
* messages starting at client hello up to, but not including, this
* finished message. [..] Note: [Also,] Hello Request messages are
* omitted from handshake hashes.
*/
switch (type)
{
case HandshakeType.hello_request:
case HandshakeType.finished:
break;
default:
rs.updateHandshakeData(beginning, 0, 4);
rs.updateHandshakeData(buf, 0, len);
break;
}
/*
* Now, parse the message.
*/
processHandshakeMessage(type, buf);
read = true;
}
}
}
while (read);
}
private void processHandshakeMessage(short type, byte[] buf) throws IOException
{
ByteArrayInputStream is = new ByteArrayInputStream(buf);
switch (type)
{
case HandshakeType.certificate:
{
switch (connection_state)
{
case CS_SERVER_HELLO_RECEIVED:
{
// Parse the Certificate message and send to cipher suite
Certificate serverCertificate = Certificate.parse(is);
assertEmpty(is);
this.keyExchange.processServerCertificate(serverCertificate);
break;
}
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
connection_state = CS_SERVER_CERTIFICATE_RECEIVED;
break;
}
case HandshakeType.finished:
switch (connection_state)
{
case CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED:
/*
* Read the checksum from the finished message, it has always 12
* bytes.
*/
byte[] serverVerifyData = new byte[12];
TlsUtils.readFully(serverVerifyData, is);
assertEmpty(is);
/*
* Calculate our own checksum.
*/
byte[] expectedServerVerifyData = TlsUtils.PRF(
securityParameters.masterSecret, "server finished",
rs.getCurrentHash(), 12);
/*
* Compare both checksums.
*/
if (!Arrays.constantTimeAreEqual(expectedServerVerifyData, serverVerifyData))
{
/*
* Wrong checksum in the finished message.
*/
this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
}
connection_state = CS_DONE;
/*
* We are now ready to receive application data.
*/
this.appDataReady = true;
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
break;
case HandshakeType.server_hello:
switch (connection_state)
{
case CS_CLIENT_HELLO_SEND:
/*
* Read the server hello message
*/
TlsUtils.checkVersion(is, this);
/*
* Read the server random
*/
securityParameters.serverRandom = new byte[32];
TlsUtils.readFully(securityParameters.serverRandom, is);
byte[] sessionID = TlsUtils.readOpaque8(is);
if (sessionID.length > 32)
{
this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
}
this.tlsClient.notifySessionID(sessionID);
/*
* Find out which CipherSuite the server has chosen and check that
* it was one of the offered ones.
*/
int selectedCipherSuite = TlsUtils.readUint16(is);
if (!arrayContains(offeredCipherSuites, selectedCipherSuite)
|| selectedCipherSuite == CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
{
this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
}
this.tlsClient.notifySelectedCipherSuite(selectedCipherSuite);
/*
* Find out which CompressionMethod the server has chosen and check that
* it was one of the offered ones.
*/
short selectedCompressionMethod = TlsUtils.readUint8(is);
if (!arrayContains(offeredCompressionMethods, selectedCompressionMethod))
{
this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
}
this.tlsClient.notifySelectedCompressionMethod(selectedCompressionMethod);
/*
* RFC3546 2.2 The extended server hello message format MAY be
* sent in place of the server hello message when the client has
* requested extended functionality via the extended client hello
* message specified in Section 2.1. ... Note that the extended
* server hello message is only sent in response to an extended
* client hello message. This prevents the possibility that the
* extended server hello message could "break" existing TLS 1.0
* clients.
*/
/*
* TODO RFC 3546 2.3 If [...] the older session is resumed, then
* the server MUST ignore extensions appearing in the client
* hello, and send a server hello containing no extensions.
*/
// Integer -> byte[]
Hashtable serverExtensions = new Hashtable();
if (is.available() > 0)
{
// Process extensions from extended server hello
byte[] extBytes = TlsUtils.readOpaque16(is);
ByteArrayInputStream ext = new ByteArrayInputStream(extBytes);
while (ext.available() > 0)
{
Integer extType = new Integer(TlsUtils.readUint16(ext));
byte[] extValue = TlsUtils.readOpaque16(ext);
/*
* RFC 5746 Note that sending a "renegotiation_info"
* extension in response to a ClientHello containing only
* the SCSV is an explicit exception to the prohibition in
* RFC 5246, Section 7.4.1.4, on the server sending
* unsolicited extensions and is only allowed because the
* client is signaling its willingness to receive the
* extension via the TLS_EMPTY_RENEGOTIATION_INFO_SCSV
* SCSV. TLS implementations MUST continue to comply with
* Section 7.4.1.4 for all other extensions.
*/
if (!extType.equals(EXT_RenegotiationInfo)
&& clientExtensions.get(extType) == null)
{
/*
* RFC 3546 2.3 Note that for all extension types
* (including those defined in future), the extension
* type MUST NOT appear in the extended server hello
* unless the same extension type appeared in the
* corresponding client hello. Thus clients MUST abort
* the handshake if they receive an extension type in
* the extended server hello that they did not request
* in the associated (extended) client hello.
*/
this.failWithError(AlertLevel.fatal,
AlertDescription.unsupported_extension);
}
if (serverExtensions.containsKey(extType))
{
/*
* RFC 3546 2.3 Also note that when multiple
* extensions of different types are present in the
* extended client hello or the extended server hello,
* the extensions may appear in any order. There MUST
* NOT be more than one extension of the same type.
*/
this.failWithError(AlertLevel.fatal,
AlertDescription.illegal_parameter);
}
serverExtensions.put(extType, extValue);
}
}
assertEmpty(is);
/*
* RFC 5746 3.4. When a ServerHello is received, the client MUST
* check if it includes the "renegotiation_info" extension:
*/
{
boolean secure_negotiation = serverExtensions.containsKey(EXT_RenegotiationInfo);
/*
* If the extension is present, set the secure_renegotiation
* flag to TRUE. The client MUST then verify that the length
* of the "renegotiated_connection" field is zero, and if it
* is not, MUST abort the handshake (by sending a fatal
* handshake_failure alert).
*/
if (secure_negotiation)
{
byte[] renegExtValue = (byte[])serverExtensions.get(EXT_RenegotiationInfo);
if (!Arrays.constantTimeAreEqual(renegExtValue,
createRenegotiationInfo(emptybuf)))
{
this.failWithError(AlertLevel.fatal,
AlertDescription.handshake_failure);
}
}
tlsClient.notifySecureRenegotiation(secure_negotiation);
}
if (clientExtensions != null)
{
tlsClient.processServerExtensions(serverExtensions);
}
this.keyExchange = tlsClient.createKeyExchange();
connection_state = CS_SERVER_HELLO_RECEIVED;
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
break;
case HandshakeType.server_hello_done:
switch (connection_state)
{
case CS_SERVER_CERTIFICATE_RECEIVED:
// There was no server key exchange message; check it's OK
this.keyExchange.skipServerKeyExchange();
// NB: Fall through to next case label
case CS_SERVER_KEY_EXCHANGE_RECEIVED:
case CS_CERTIFICATE_REQUEST_RECEIVED:
assertEmpty(is);
boolean isClientCertificateRequested = (connection_state == CS_CERTIFICATE_REQUEST_RECEIVED);
connection_state = CS_SERVER_HELLO_DONE_RECEIVED;
if (isClientCertificateRequested)
{
sendClientCertificate(tlsClient.getCertificate());
}
/*
* Send the client key exchange message, depending on the key
- * exchange we are using in our ciphersuite.
+ * exchange we are using in our CipherSuite.
*/
sendClientKeyExchange();
connection_state = CS_CLIENT_KEY_EXCHANGE_SEND;
if (isClientCertificateRequested)
{
byte[] clientCertificateSignature = tlsClient.generateCertificateSignature(rs.getCurrentHash());
if (clientCertificateSignature != null)
{
sendCertificateVerify(clientCertificateSignature);
connection_state = CS_CERTIFICATE_VERIFY_SEND;
}
}
/*
* Now, we send change cipher state
*/
byte[] cmessage = new byte[1];
cmessage[0] = 1;
rs.writeMessage(ContentType.change_cipher_spec, cmessage, 0,
cmessage.length);
connection_state = CS_CLIENT_CHANGE_CIPHER_SPEC_SEND;
/*
* Calculate the master_secret
*/
byte[] pms = this.keyExchange.generatePremasterSecret();
securityParameters.masterSecret = TlsUtils.PRF(pms, "master secret",
TlsUtils.concat(securityParameters.clientRandom,
securityParameters.serverRandom), 48);
// TODO Is there a way to ensure the data is really overwritten?
/*
* RFC 2246 8.1. The pre_master_secret should be deleted from
* memory once the master_secret has been computed.
*/
Arrays.fill(pms, (byte)0);
/*
* Initialize our cipher suite
*/
rs.clientCipherSpecDecided(tlsClient.createCipher(securityParameters));
/*
* Send our finished message.
*/
byte[] clientVerifyData = TlsUtils.PRF(securityParameters.masterSecret,
"client finished", rs.getCurrentHash(), 12);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HandshakeType.finished, bos);
TlsUtils.writeOpaque24(clientVerifyData, bos);
byte[] message = bos.toByteArray();
rs.writeMessage(ContentType.handshake, message, 0, message.length);
this.connection_state = CS_CLIENT_FINISHED_SEND;
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
}
break;
case HandshakeType.server_key_exchange:
{
switch (connection_state)
{
case CS_SERVER_HELLO_RECEIVED:
// There was no server certificate message; check it's OK
this.keyExchange.skipServerCertificate();
// NB: Fall through to next case label
case CS_SERVER_CERTIFICATE_RECEIVED:
this.keyExchange.processServerKeyExchange(is, securityParameters);
assertEmpty(is);
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED;
break;
}
case HandshakeType.certificate_request:
{
switch (connection_state)
{
case CS_SERVER_CERTIFICATE_RECEIVED:
// There was no server key exchange message; check it's OK
this.keyExchange.skipServerKeyExchange();
// NB: Fall through to next case label
case CS_SERVER_KEY_EXCHANGE_RECEIVED:
{
byte[] types = TlsUtils.readOpaque8(is);
byte[] authorities = TlsUtils.readOpaque16(is);
assertEmpty(is);
short[] certificateTypes = new short[types.length];
for (int i = 0; i < types.length; ++i)
{
certificateTypes[i] = (short)(types[i] & 0xff);
}
Vector authorityDNs = new Vector();
ByteArrayInputStream bis = new ByteArrayInputStream(authorities);
while (bis.available() > 0)
{
byte[] dnBytes = TlsUtils.readOpaque16(bis);
authorityDNs.add(X509Name.getInstance(ASN1Object.fromByteArray(dnBytes)));
}
this.tlsClient.processServerCertificateRequest(certificateTypes,
authorityDNs);
break;
}
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
this.connection_state = CS_CERTIFICATE_REQUEST_RECEIVED;
break;
}
case HandshakeType.hello_request:
/*
* RFC 2246 7.4.1.1 Hello request This message will be ignored by the
* client if the client is currently negotiating a session. This message
* may be ignored by the client if it does not wish to renegotiate a
* session, or the client may, if it wishes, respond with a
* no_renegotiation alert.
*/
if (connection_state == CS_DONE)
{
// Renegotiation not supported yet
sendAlert(AlertLevel.warning, AlertDescription.no_renegotiation);
}
break;
case HandshakeType.client_key_exchange:
case HandshakeType.certificate_verify:
case HandshakeType.client_hello:
default:
// We do not support this!
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
break;
}
}
private void processApplicationData()
{
/*
* There is nothing we need to do here.
*
* This function could be used for callbacks when application data arrives in the
* future.
*/
}
private void processAlert() throws IOException
{
while (alertQueue.size() >= 2)
{
/*
* An alert is always 2 bytes. Read the alert.
*/
byte[] tmp = new byte[2];
alertQueue.read(tmp, 0, 2, 0);
alertQueue.removeData(2);
short level = tmp[0];
short description = tmp[1];
if (level == AlertLevel.fatal)
{
/*
* This is a fatal error.
*/
this.failedWithError = true;
this.closed = true;
/*
* Now try to close the stream, ignore errors.
*/
try
{
rs.close();
}
catch (Exception e)
{
}
throw new IOException(TLS_ERROR_MESSAGE);
}
else
{
/*
* This is just a warning.
*/
if (description == AlertDescription.close_notify)
{
/*
* Close notify
*/
this.failWithError(AlertLevel.warning, AlertDescription.close_notify);
}
/*
* If it is just a warning, we continue.
*/
}
}
}
/**
* This method is called, when a change cipher spec message is received.
*
* @throws IOException If the message has an invalid content or the handshake is not
* in the correct state.
*/
private void processChangeCipherSpec() throws IOException
{
while (changeCipherSpecQueue.size() > 0)
{
/*
* A change cipher spec message is only one byte with the value 1.
*/
byte[] b = new byte[1];
changeCipherSpecQueue.read(b, 0, 1, 0);
changeCipherSpecQueue.removeData(1);
if (b[0] != 1)
{
/*
* This should never happen.
*/
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
/*
* Check if we are in the correct connection state.
*/
if (this.connection_state != CS_CLIENT_FINISHED_SEND)
{
this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
}
rs.serverClientSpecReceived();
this.connection_state = CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED;
}
}
private void sendClientCertificate(Certificate clientCert) throws IOException
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HandshakeType.certificate, bos);
clientCert.encode(bos);
byte[] message = bos.toByteArray();
rs.writeMessage(ContentType.handshake, message, 0, message.length);
}
private void sendClientKeyExchange() throws IOException
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HandshakeType.client_key_exchange, bos);
this.keyExchange.generateClientKeyExchange(bos);
byte[] message = bos.toByteArray();
rs.writeMessage(ContentType.handshake, message, 0, message.length);
}
private void sendCertificateVerify(byte[] data) throws IOException
{
/*
* Send signature of handshake messages so far to prove we are the owner of the
* cert See RFC 2246 sections 4.7, 7.4.3 and 7.4.8
*/
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HandshakeType.certificate_verify, bos);
TlsUtils.writeUint24(data.length + 2, bos);
TlsUtils.writeOpaque16(data, bos);
byte[] message = bos.toByteArray();
rs.writeMessage(ContentType.handshake, message, 0, message.length);
}
/**
* Connects to the remote system.
*
* @param verifyer Will be used when a certificate is received to verify that this
* certificate is accepted by the client.
* @throws IOException If handshake was not successful.
*/
// TODO Deprecate
public void connect(CertificateVerifyer verifyer) throws IOException
{
this.connect(new DefaultTlsClient(verifyer));
}
// public void connect(CertificateVerifyer verifyer, Certificate clientCertificate,
// AsymmetricKeyParameter clientPrivateKey) throws IOException
// {
// DefaultTlsClient client = new DefaultTlsClient(verifyer);
// client.enableClientAuthentication(clientCertificate, clientPrivateKey);
//
// this.connect(client);
// }
/**
* Connects to the remote system using client authentication
*
* @param verifyer Will be used when a certificate is received to verify that this
* certificate is accepted by the client.
* @param clientCertificate The client's certificate to be provided to the remote
* system
* @param clientPrivateKey The client's private key for the certificate to
* authenticate to the remote system (RSA or DSA)
* @throws IOException If handshake was not successful.
*/
// TODO Make public
void connect(TlsClient tlsClient) throws IOException
{
if (tlsClient == null)
{
throw new IllegalArgumentException("'tlsClient' cannot be null");
}
if (this.tlsClient != null)
{
throw new IllegalStateException("connect can only be called once");
}
this.tlsClient = tlsClient;
this.tlsClient.init(this);
/*
* Send Client hello
*
* First, generate some random data.
*/
securityParameters = new SecurityParameters();
securityParameters.clientRandom = new byte[32];
random.nextBytes(securityParameters.clientRandom);
TlsUtils.writeGMTUnixTime(securityParameters.clientRandom, 0);
ByteArrayOutputStream os = new ByteArrayOutputStream();
TlsUtils.writeVersion(os);
os.write(securityParameters.clientRandom);
/*
* Length of Session id
*/
TlsUtils.writeUint8((short)0, os);
/*
* Cipher suites
*/
this.offeredCipherSuites = this.tlsClient.getCipherSuites();
// Integer -> byte[]
this.clientExtensions = this.tlsClient.generateClientExtensions();
// Cipher Suites (and SCSV)
{
/*
* RFC 5746 3.4. The client MUST include either an empty "renegotiation_info"
* extension, or the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite
* value in the ClientHello. Including both is NOT RECOMMENDED.
*/
boolean noRenegExt = clientExtensions == null
|| clientExtensions.get(EXT_RenegotiationInfo) == null;
int count = offeredCipherSuites.length;
if (noRenegExt)
{
// Note: 1 extra slot for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
++count;
}
TlsUtils.writeUint16(2 * count, os);
TlsUtils.writeUint16Array(offeredCipherSuites, os);
if (noRenegExt)
{
TlsUtils.writeUint16(CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV, os);
}
}
/*
* Compression methods, just the null method.
*/
this.offeredCompressionMethods = this.tlsClient.getCompressionMethods();
TlsUtils.writeUint8((short)offeredCompressionMethods.length, os);
TlsUtils.writeUint8Array(offeredCompressionMethods, os);
// Extensions
if (clientExtensions != null)
{
ByteArrayOutputStream ext = new ByteArrayOutputStream();
Enumeration keys = clientExtensions.keys();
while (keys.hasMoreElements())
{
Integer extType = (Integer)keys.nextElement();
writeExtension(ext, extType, (byte[])clientExtensions.get(extType));
}
TlsUtils.writeOpaque16(ext.toByteArray(), os);
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HandshakeType.client_hello, bos);
TlsUtils.writeUint24(os.size(), bos);
bos.write(os.toByteArray());
byte[] message = bos.toByteArray();
rs.writeMessage(ContentType.handshake, message, 0, message.length);
connection_state = CS_CLIENT_HELLO_SEND;
/*
* We will now read data, until we have completed the handshake.
*/
while (connection_state != CS_DONE)
{
// TODO Should we send fatal alerts in the event of an exception
// (see readApplicationData)
rs.readData();
}
this.tlsInputStream = new TlsInputStream(this);
this.tlsOutputStream = new TlsOutputStream(this);
}
/**
* Read data from the network. The method will return immediately, if there is still
* some data left in the buffer, or block until some application data has been read
* from the network.
*
* @param buf The buffer where the data will be copied to.
* @param offset The position where the data will be placed in the buffer.
* @param len The maximum number of bytes to read.
* @return The number of bytes read.
* @throws IOException If something goes wrong during reading data.
*/
protected int readApplicationData(byte[] buf, int offset, int len) throws IOException
{
while (applicationDataQueue.size() == 0)
{
/*
* We need to read some data.
*/
if (this.closed)
{
if (this.failedWithError)
{
/*
* Something went terribly wrong, we should throw an IOException
*/
throw new IOException(TLS_ERROR_MESSAGE);
}
/*
* Connection has been closed, there is no more data to read.
*/
return -1;
}
try
{
rs.readData();
}
catch (IOException e)
{
if (!this.closed)
{
this.failWithError(AlertLevel.fatal, AlertDescription.internal_error);
}
throw e;
}
catch (RuntimeException e)
{
if (!this.closed)
{
this.failWithError(AlertLevel.fatal, AlertDescription.internal_error);
}
throw e;
}
}
len = Math.min(len, applicationDataQueue.size());
applicationDataQueue.read(buf, offset, len, 0);
applicationDataQueue.removeData(len);
return len;
}
/**
* Send some application data to the remote system.
* <p/>
* The method will handle fragmentation internally.
*
* @param buf The buffer with the data.
* @param offset The position in the buffer where the data is placed.
* @param len The length of the data.
* @throws IOException If something goes wrong during sending.
*/
protected void writeData(byte[] buf, int offset, int len) throws IOException
{
if (this.closed)
{
if (this.failedWithError)
{
throw new IOException(TLS_ERROR_MESSAGE);
}
throw new IOException("Sorry, connection has been closed, you cannot write more data");
}
/*
* Protect against known IV attack!
*
* DO NOT REMOVE THIS LINE, EXCEPT YOU KNOW EXACTLY WHAT YOU ARE DOING HERE.
*/
rs.writeMessage(ContentType.application_data, emptybuf, 0, 0);
do
{
/*
* We are only allowed to write fragments up to 2^14 bytes.
*/
int toWrite = Math.min(len, 1 << 14);
try
{
rs.writeMessage(ContentType.application_data, buf, offset, toWrite);
}
catch (IOException e)
{
if (!closed)
{
this.failWithError(AlertLevel.fatal, AlertDescription.internal_error);
}
throw e;
}
catch (RuntimeException e)
{
if (!closed)
{
this.failWithError(AlertLevel.fatal, AlertDescription.internal_error);
}
throw e;
}
offset += toWrite;
len -= toWrite;
}
while (len > 0);
}
/**
* @return An OutputStream which can be used to send data.
*/
public OutputStream getOutputStream()
{
return this.tlsOutputStream;
}
/**
* @return An InputStream which can be used to read data.
*/
public InputStream getInputStream()
{
return this.tlsInputStream;
}
/**
* Terminate this connection with an alert.
* <p/>
* Can be used for normal closure too.
*
* @param alertLevel The level of the alert, an be AlertLevel.fatal or AL_warning.
* @param alertDescription The exact alert message.
* @throws IOException If alert was fatal.
*/
protected void failWithError(short alertLevel, short alertDescription) throws IOException
{
/*
* Check if the connection is still open.
*/
if (!closed)
{
/*
* Prepare the message
*/
this.closed = true;
if (alertLevel == AlertLevel.fatal)
{
/*
* This is a fatal message.
*/
this.failedWithError = true;
}
sendAlert(alertLevel, alertDescription);
rs.close();
if (alertLevel == AlertLevel.fatal)
{
throw new IOException(TLS_ERROR_MESSAGE);
}
}
else
{
throw new IOException(TLS_ERROR_MESSAGE);
}
}
private void sendAlert(short alertLevel, short alertDescription) throws IOException
{
byte[] error = new byte[2];
error[0] = (byte)alertLevel;
error[1] = (byte)alertDescription;
rs.writeMessage(ContentType.alert, error, 0, 2);
}
/**
* Closes this connection.
*
* @throws IOException If something goes wrong during closing.
*/
public void close() throws IOException
{
if (!closed)
{
this.failWithError(AlertLevel.warning, AlertDescription.close_notify);
}
}
/**
* Make sure the InputStream is now empty. Fail otherwise.
*
* @param is The InputStream to check.
* @throws IOException If is is not empty.
*/
protected void assertEmpty(ByteArrayInputStream is) throws IOException
{
if (is.available() > 0)
{
this.failWithError(AlertLevel.fatal, AlertDescription.decode_error);
}
}
protected void flush() throws IOException
{
rs.flush();
}
private static boolean arrayContains(short[] a, short n)
{
for (int i = 0; i < a.length; ++i)
{
if (a[i] == n)
{
return true;
}
}
return false;
}
private static boolean arrayContains(int[] a, int n)
{
for (int i = 0; i < a.length; ++i)
{
if (a[i] == n)
{
return true;
}
}
return false;
}
private static byte[] createRenegotiationInfo(byte[] renegotiated_connection)
throws IOException
{
ByteArrayOutputStream buf = new ByteArrayOutputStream();
TlsUtils.writeOpaque8(renegotiated_connection, buf);
return buf.toByteArray();
}
private static void writeExtension(OutputStream output, Integer extType, byte[] extValue)
throws IOException
{
TlsUtils.writeUint16(extType.intValue(), output);
TlsUtils.writeOpaque16(extValue, output);
}
}
| true | true | private void processHandshakeMessage(short type, byte[] buf) throws IOException
{
ByteArrayInputStream is = new ByteArrayInputStream(buf);
switch (type)
{
case HandshakeType.certificate:
{
switch (connection_state)
{
case CS_SERVER_HELLO_RECEIVED:
{
// Parse the Certificate message and send to cipher suite
Certificate serverCertificate = Certificate.parse(is);
assertEmpty(is);
this.keyExchange.processServerCertificate(serverCertificate);
break;
}
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
connection_state = CS_SERVER_CERTIFICATE_RECEIVED;
break;
}
case HandshakeType.finished:
switch (connection_state)
{
case CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED:
/*
* Read the checksum from the finished message, it has always 12
* bytes.
*/
byte[] serverVerifyData = new byte[12];
TlsUtils.readFully(serverVerifyData, is);
assertEmpty(is);
/*
* Calculate our own checksum.
*/
byte[] expectedServerVerifyData = TlsUtils.PRF(
securityParameters.masterSecret, "server finished",
rs.getCurrentHash(), 12);
/*
* Compare both checksums.
*/
if (!Arrays.constantTimeAreEqual(expectedServerVerifyData, serverVerifyData))
{
/*
* Wrong checksum in the finished message.
*/
this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
}
connection_state = CS_DONE;
/*
* We are now ready to receive application data.
*/
this.appDataReady = true;
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
break;
case HandshakeType.server_hello:
switch (connection_state)
{
case CS_CLIENT_HELLO_SEND:
/*
* Read the server hello message
*/
TlsUtils.checkVersion(is, this);
/*
* Read the server random
*/
securityParameters.serverRandom = new byte[32];
TlsUtils.readFully(securityParameters.serverRandom, is);
byte[] sessionID = TlsUtils.readOpaque8(is);
if (sessionID.length > 32)
{
this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
}
this.tlsClient.notifySessionID(sessionID);
/*
* Find out which CipherSuite the server has chosen and check that
* it was one of the offered ones.
*/
int selectedCipherSuite = TlsUtils.readUint16(is);
if (!arrayContains(offeredCipherSuites, selectedCipherSuite)
|| selectedCipherSuite == CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
{
this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
}
this.tlsClient.notifySelectedCipherSuite(selectedCipherSuite);
/*
* Find out which CompressionMethod the server has chosen and check that
* it was one of the offered ones.
*/
short selectedCompressionMethod = TlsUtils.readUint8(is);
if (!arrayContains(offeredCompressionMethods, selectedCompressionMethod))
{
this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
}
this.tlsClient.notifySelectedCompressionMethod(selectedCompressionMethod);
/*
* RFC3546 2.2 The extended server hello message format MAY be
* sent in place of the server hello message when the client has
* requested extended functionality via the extended client hello
* message specified in Section 2.1. ... Note that the extended
* server hello message is only sent in response to an extended
* client hello message. This prevents the possibility that the
* extended server hello message could "break" existing TLS 1.0
* clients.
*/
/*
* TODO RFC 3546 2.3 If [...] the older session is resumed, then
* the server MUST ignore extensions appearing in the client
* hello, and send a server hello containing no extensions.
*/
// Integer -> byte[]
Hashtable serverExtensions = new Hashtable();
if (is.available() > 0)
{
// Process extensions from extended server hello
byte[] extBytes = TlsUtils.readOpaque16(is);
ByteArrayInputStream ext = new ByteArrayInputStream(extBytes);
while (ext.available() > 0)
{
Integer extType = new Integer(TlsUtils.readUint16(ext));
byte[] extValue = TlsUtils.readOpaque16(ext);
/*
* RFC 5746 Note that sending a "renegotiation_info"
* extension in response to a ClientHello containing only
* the SCSV is an explicit exception to the prohibition in
* RFC 5246, Section 7.4.1.4, on the server sending
* unsolicited extensions and is only allowed because the
* client is signaling its willingness to receive the
* extension via the TLS_EMPTY_RENEGOTIATION_INFO_SCSV
* SCSV. TLS implementations MUST continue to comply with
* Section 7.4.1.4 for all other extensions.
*/
if (!extType.equals(EXT_RenegotiationInfo)
&& clientExtensions.get(extType) == null)
{
/*
* RFC 3546 2.3 Note that for all extension types
* (including those defined in future), the extension
* type MUST NOT appear in the extended server hello
* unless the same extension type appeared in the
* corresponding client hello. Thus clients MUST abort
* the handshake if they receive an extension type in
* the extended server hello that they did not request
* in the associated (extended) client hello.
*/
this.failWithError(AlertLevel.fatal,
AlertDescription.unsupported_extension);
}
if (serverExtensions.containsKey(extType))
{
/*
* RFC 3546 2.3 Also note that when multiple
* extensions of different types are present in the
* extended client hello or the extended server hello,
* the extensions may appear in any order. There MUST
* NOT be more than one extension of the same type.
*/
this.failWithError(AlertLevel.fatal,
AlertDescription.illegal_parameter);
}
serverExtensions.put(extType, extValue);
}
}
assertEmpty(is);
/*
* RFC 5746 3.4. When a ServerHello is received, the client MUST
* check if it includes the "renegotiation_info" extension:
*/
{
boolean secure_negotiation = serverExtensions.containsKey(EXT_RenegotiationInfo);
/*
* If the extension is present, set the secure_renegotiation
* flag to TRUE. The client MUST then verify that the length
* of the "renegotiated_connection" field is zero, and if it
* is not, MUST abort the handshake (by sending a fatal
* handshake_failure alert).
*/
if (secure_negotiation)
{
byte[] renegExtValue = (byte[])serverExtensions.get(EXT_RenegotiationInfo);
if (!Arrays.constantTimeAreEqual(renegExtValue,
createRenegotiationInfo(emptybuf)))
{
this.failWithError(AlertLevel.fatal,
AlertDescription.handshake_failure);
}
}
tlsClient.notifySecureRenegotiation(secure_negotiation);
}
if (clientExtensions != null)
{
tlsClient.processServerExtensions(serverExtensions);
}
this.keyExchange = tlsClient.createKeyExchange();
connection_state = CS_SERVER_HELLO_RECEIVED;
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
break;
case HandshakeType.server_hello_done:
switch (connection_state)
{
case CS_SERVER_CERTIFICATE_RECEIVED:
// There was no server key exchange message; check it's OK
this.keyExchange.skipServerKeyExchange();
// NB: Fall through to next case label
case CS_SERVER_KEY_EXCHANGE_RECEIVED:
case CS_CERTIFICATE_REQUEST_RECEIVED:
assertEmpty(is);
boolean isClientCertificateRequested = (connection_state == CS_CERTIFICATE_REQUEST_RECEIVED);
connection_state = CS_SERVER_HELLO_DONE_RECEIVED;
if (isClientCertificateRequested)
{
sendClientCertificate(tlsClient.getCertificate());
}
/*
* Send the client key exchange message, depending on the key
* exchange we are using in our ciphersuite.
*/
sendClientKeyExchange();
connection_state = CS_CLIENT_KEY_EXCHANGE_SEND;
if (isClientCertificateRequested)
{
byte[] clientCertificateSignature = tlsClient.generateCertificateSignature(rs.getCurrentHash());
if (clientCertificateSignature != null)
{
sendCertificateVerify(clientCertificateSignature);
connection_state = CS_CERTIFICATE_VERIFY_SEND;
}
}
/*
* Now, we send change cipher state
*/
byte[] cmessage = new byte[1];
cmessage[0] = 1;
rs.writeMessage(ContentType.change_cipher_spec, cmessage, 0,
cmessage.length);
connection_state = CS_CLIENT_CHANGE_CIPHER_SPEC_SEND;
/*
* Calculate the master_secret
*/
byte[] pms = this.keyExchange.generatePremasterSecret();
securityParameters.masterSecret = TlsUtils.PRF(pms, "master secret",
TlsUtils.concat(securityParameters.clientRandom,
securityParameters.serverRandom), 48);
// TODO Is there a way to ensure the data is really overwritten?
/*
* RFC 2246 8.1. The pre_master_secret should be deleted from
* memory once the master_secret has been computed.
*/
Arrays.fill(pms, (byte)0);
/*
* Initialize our cipher suite
*/
rs.clientCipherSpecDecided(tlsClient.createCipher(securityParameters));
/*
* Send our finished message.
*/
byte[] clientVerifyData = TlsUtils.PRF(securityParameters.masterSecret,
"client finished", rs.getCurrentHash(), 12);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HandshakeType.finished, bos);
TlsUtils.writeOpaque24(clientVerifyData, bos);
byte[] message = bos.toByteArray();
rs.writeMessage(ContentType.handshake, message, 0, message.length);
this.connection_state = CS_CLIENT_FINISHED_SEND;
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
}
break;
case HandshakeType.server_key_exchange:
{
switch (connection_state)
{
case CS_SERVER_HELLO_RECEIVED:
// There was no server certificate message; check it's OK
this.keyExchange.skipServerCertificate();
// NB: Fall through to next case label
case CS_SERVER_CERTIFICATE_RECEIVED:
this.keyExchange.processServerKeyExchange(is, securityParameters);
assertEmpty(is);
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED;
break;
}
case HandshakeType.certificate_request:
{
switch (connection_state)
{
case CS_SERVER_CERTIFICATE_RECEIVED:
// There was no server key exchange message; check it's OK
this.keyExchange.skipServerKeyExchange();
// NB: Fall through to next case label
case CS_SERVER_KEY_EXCHANGE_RECEIVED:
{
byte[] types = TlsUtils.readOpaque8(is);
byte[] authorities = TlsUtils.readOpaque16(is);
assertEmpty(is);
short[] certificateTypes = new short[types.length];
for (int i = 0; i < types.length; ++i)
{
certificateTypes[i] = (short)(types[i] & 0xff);
}
Vector authorityDNs = new Vector();
ByteArrayInputStream bis = new ByteArrayInputStream(authorities);
while (bis.available() > 0)
{
byte[] dnBytes = TlsUtils.readOpaque16(bis);
authorityDNs.add(X509Name.getInstance(ASN1Object.fromByteArray(dnBytes)));
}
this.tlsClient.processServerCertificateRequest(certificateTypes,
authorityDNs);
break;
}
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
this.connection_state = CS_CERTIFICATE_REQUEST_RECEIVED;
break;
}
case HandshakeType.hello_request:
/*
* RFC 2246 7.4.1.1 Hello request This message will be ignored by the
* client if the client is currently negotiating a session. This message
* may be ignored by the client if it does not wish to renegotiate a
* session, or the client may, if it wishes, respond with a
* no_renegotiation alert.
*/
if (connection_state == CS_DONE)
{
// Renegotiation not supported yet
sendAlert(AlertLevel.warning, AlertDescription.no_renegotiation);
}
break;
case HandshakeType.client_key_exchange:
case HandshakeType.certificate_verify:
case HandshakeType.client_hello:
default:
// We do not support this!
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
break;
}
}
| private void processHandshakeMessage(short type, byte[] buf) throws IOException
{
ByteArrayInputStream is = new ByteArrayInputStream(buf);
switch (type)
{
case HandshakeType.certificate:
{
switch (connection_state)
{
case CS_SERVER_HELLO_RECEIVED:
{
// Parse the Certificate message and send to cipher suite
Certificate serverCertificate = Certificate.parse(is);
assertEmpty(is);
this.keyExchange.processServerCertificate(serverCertificate);
break;
}
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
connection_state = CS_SERVER_CERTIFICATE_RECEIVED;
break;
}
case HandshakeType.finished:
switch (connection_state)
{
case CS_SERVER_CHANGE_CIPHER_SPEC_RECEIVED:
/*
* Read the checksum from the finished message, it has always 12
* bytes.
*/
byte[] serverVerifyData = new byte[12];
TlsUtils.readFully(serverVerifyData, is);
assertEmpty(is);
/*
* Calculate our own checksum.
*/
byte[] expectedServerVerifyData = TlsUtils.PRF(
securityParameters.masterSecret, "server finished",
rs.getCurrentHash(), 12);
/*
* Compare both checksums.
*/
if (!Arrays.constantTimeAreEqual(expectedServerVerifyData, serverVerifyData))
{
/*
* Wrong checksum in the finished message.
*/
this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
}
connection_state = CS_DONE;
/*
* We are now ready to receive application data.
*/
this.appDataReady = true;
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
break;
case HandshakeType.server_hello:
switch (connection_state)
{
case CS_CLIENT_HELLO_SEND:
/*
* Read the server hello message
*/
TlsUtils.checkVersion(is, this);
/*
* Read the server random
*/
securityParameters.serverRandom = new byte[32];
TlsUtils.readFully(securityParameters.serverRandom, is);
byte[] sessionID = TlsUtils.readOpaque8(is);
if (sessionID.length > 32)
{
this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
}
this.tlsClient.notifySessionID(sessionID);
/*
* Find out which CipherSuite the server has chosen and check that
* it was one of the offered ones.
*/
int selectedCipherSuite = TlsUtils.readUint16(is);
if (!arrayContains(offeredCipherSuites, selectedCipherSuite)
|| selectedCipherSuite == CipherSuite.TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
{
this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
}
this.tlsClient.notifySelectedCipherSuite(selectedCipherSuite);
/*
* Find out which CompressionMethod the server has chosen and check that
* it was one of the offered ones.
*/
short selectedCompressionMethod = TlsUtils.readUint8(is);
if (!arrayContains(offeredCompressionMethods, selectedCompressionMethod))
{
this.failWithError(AlertLevel.fatal, AlertDescription.illegal_parameter);
}
this.tlsClient.notifySelectedCompressionMethod(selectedCompressionMethod);
/*
* RFC3546 2.2 The extended server hello message format MAY be
* sent in place of the server hello message when the client has
* requested extended functionality via the extended client hello
* message specified in Section 2.1. ... Note that the extended
* server hello message is only sent in response to an extended
* client hello message. This prevents the possibility that the
* extended server hello message could "break" existing TLS 1.0
* clients.
*/
/*
* TODO RFC 3546 2.3 If [...] the older session is resumed, then
* the server MUST ignore extensions appearing in the client
* hello, and send a server hello containing no extensions.
*/
// Integer -> byte[]
Hashtable serverExtensions = new Hashtable();
if (is.available() > 0)
{
// Process extensions from extended server hello
byte[] extBytes = TlsUtils.readOpaque16(is);
ByteArrayInputStream ext = new ByteArrayInputStream(extBytes);
while (ext.available() > 0)
{
Integer extType = new Integer(TlsUtils.readUint16(ext));
byte[] extValue = TlsUtils.readOpaque16(ext);
/*
* RFC 5746 Note that sending a "renegotiation_info"
* extension in response to a ClientHello containing only
* the SCSV is an explicit exception to the prohibition in
* RFC 5246, Section 7.4.1.4, on the server sending
* unsolicited extensions and is only allowed because the
* client is signaling its willingness to receive the
* extension via the TLS_EMPTY_RENEGOTIATION_INFO_SCSV
* SCSV. TLS implementations MUST continue to comply with
* Section 7.4.1.4 for all other extensions.
*/
if (!extType.equals(EXT_RenegotiationInfo)
&& clientExtensions.get(extType) == null)
{
/*
* RFC 3546 2.3 Note that for all extension types
* (including those defined in future), the extension
* type MUST NOT appear in the extended server hello
* unless the same extension type appeared in the
* corresponding client hello. Thus clients MUST abort
* the handshake if they receive an extension type in
* the extended server hello that they did not request
* in the associated (extended) client hello.
*/
this.failWithError(AlertLevel.fatal,
AlertDescription.unsupported_extension);
}
if (serverExtensions.containsKey(extType))
{
/*
* RFC 3546 2.3 Also note that when multiple
* extensions of different types are present in the
* extended client hello or the extended server hello,
* the extensions may appear in any order. There MUST
* NOT be more than one extension of the same type.
*/
this.failWithError(AlertLevel.fatal,
AlertDescription.illegal_parameter);
}
serverExtensions.put(extType, extValue);
}
}
assertEmpty(is);
/*
* RFC 5746 3.4. When a ServerHello is received, the client MUST
* check if it includes the "renegotiation_info" extension:
*/
{
boolean secure_negotiation = serverExtensions.containsKey(EXT_RenegotiationInfo);
/*
* If the extension is present, set the secure_renegotiation
* flag to TRUE. The client MUST then verify that the length
* of the "renegotiated_connection" field is zero, and if it
* is not, MUST abort the handshake (by sending a fatal
* handshake_failure alert).
*/
if (secure_negotiation)
{
byte[] renegExtValue = (byte[])serverExtensions.get(EXT_RenegotiationInfo);
if (!Arrays.constantTimeAreEqual(renegExtValue,
createRenegotiationInfo(emptybuf)))
{
this.failWithError(AlertLevel.fatal,
AlertDescription.handshake_failure);
}
}
tlsClient.notifySecureRenegotiation(secure_negotiation);
}
if (clientExtensions != null)
{
tlsClient.processServerExtensions(serverExtensions);
}
this.keyExchange = tlsClient.createKeyExchange();
connection_state = CS_SERVER_HELLO_RECEIVED;
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
break;
case HandshakeType.server_hello_done:
switch (connection_state)
{
case CS_SERVER_CERTIFICATE_RECEIVED:
// There was no server key exchange message; check it's OK
this.keyExchange.skipServerKeyExchange();
// NB: Fall through to next case label
case CS_SERVER_KEY_EXCHANGE_RECEIVED:
case CS_CERTIFICATE_REQUEST_RECEIVED:
assertEmpty(is);
boolean isClientCertificateRequested = (connection_state == CS_CERTIFICATE_REQUEST_RECEIVED);
connection_state = CS_SERVER_HELLO_DONE_RECEIVED;
if (isClientCertificateRequested)
{
sendClientCertificate(tlsClient.getCertificate());
}
/*
* Send the client key exchange message, depending on the key
* exchange we are using in our CipherSuite.
*/
sendClientKeyExchange();
connection_state = CS_CLIENT_KEY_EXCHANGE_SEND;
if (isClientCertificateRequested)
{
byte[] clientCertificateSignature = tlsClient.generateCertificateSignature(rs.getCurrentHash());
if (clientCertificateSignature != null)
{
sendCertificateVerify(clientCertificateSignature);
connection_state = CS_CERTIFICATE_VERIFY_SEND;
}
}
/*
* Now, we send change cipher state
*/
byte[] cmessage = new byte[1];
cmessage[0] = 1;
rs.writeMessage(ContentType.change_cipher_spec, cmessage, 0,
cmessage.length);
connection_state = CS_CLIENT_CHANGE_CIPHER_SPEC_SEND;
/*
* Calculate the master_secret
*/
byte[] pms = this.keyExchange.generatePremasterSecret();
securityParameters.masterSecret = TlsUtils.PRF(pms, "master secret",
TlsUtils.concat(securityParameters.clientRandom,
securityParameters.serverRandom), 48);
// TODO Is there a way to ensure the data is really overwritten?
/*
* RFC 2246 8.1. The pre_master_secret should be deleted from
* memory once the master_secret has been computed.
*/
Arrays.fill(pms, (byte)0);
/*
* Initialize our cipher suite
*/
rs.clientCipherSpecDecided(tlsClient.createCipher(securityParameters));
/*
* Send our finished message.
*/
byte[] clientVerifyData = TlsUtils.PRF(securityParameters.masterSecret,
"client finished", rs.getCurrentHash(), 12);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
TlsUtils.writeUint8(HandshakeType.finished, bos);
TlsUtils.writeOpaque24(clientVerifyData, bos);
byte[] message = bos.toByteArray();
rs.writeMessage(ContentType.handshake, message, 0, message.length);
this.connection_state = CS_CLIENT_FINISHED_SEND;
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.handshake_failure);
}
break;
case HandshakeType.server_key_exchange:
{
switch (connection_state)
{
case CS_SERVER_HELLO_RECEIVED:
// There was no server certificate message; check it's OK
this.keyExchange.skipServerCertificate();
// NB: Fall through to next case label
case CS_SERVER_CERTIFICATE_RECEIVED:
this.keyExchange.processServerKeyExchange(is, securityParameters);
assertEmpty(is);
break;
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
this.connection_state = CS_SERVER_KEY_EXCHANGE_RECEIVED;
break;
}
case HandshakeType.certificate_request:
{
switch (connection_state)
{
case CS_SERVER_CERTIFICATE_RECEIVED:
// There was no server key exchange message; check it's OK
this.keyExchange.skipServerKeyExchange();
// NB: Fall through to next case label
case CS_SERVER_KEY_EXCHANGE_RECEIVED:
{
byte[] types = TlsUtils.readOpaque8(is);
byte[] authorities = TlsUtils.readOpaque16(is);
assertEmpty(is);
short[] certificateTypes = new short[types.length];
for (int i = 0; i < types.length; ++i)
{
certificateTypes[i] = (short)(types[i] & 0xff);
}
Vector authorityDNs = new Vector();
ByteArrayInputStream bis = new ByteArrayInputStream(authorities);
while (bis.available() > 0)
{
byte[] dnBytes = TlsUtils.readOpaque16(bis);
authorityDNs.add(X509Name.getInstance(ASN1Object.fromByteArray(dnBytes)));
}
this.tlsClient.processServerCertificateRequest(certificateTypes,
authorityDNs);
break;
}
default:
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
}
this.connection_state = CS_CERTIFICATE_REQUEST_RECEIVED;
break;
}
case HandshakeType.hello_request:
/*
* RFC 2246 7.4.1.1 Hello request This message will be ignored by the
* client if the client is currently negotiating a session. This message
* may be ignored by the client if it does not wish to renegotiate a
* session, or the client may, if it wishes, respond with a
* no_renegotiation alert.
*/
if (connection_state == CS_DONE)
{
// Renegotiation not supported yet
sendAlert(AlertLevel.warning, AlertDescription.no_renegotiation);
}
break;
case HandshakeType.client_key_exchange:
case HandshakeType.certificate_verify:
case HandshakeType.client_hello:
default:
// We do not support this!
this.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message);
break;
}
}
|
diff --git a/src/java/net/sf/picard/io/FastLineReader.java b/src/java/net/sf/picard/io/FastLineReader.java
index 6395844..0da120a 100644
--- a/src/java/net/sf/picard/io/FastLineReader.java
+++ b/src/java/net/sf/picard/io/FastLineReader.java
@@ -1,171 +1,171 @@
/*
* The MIT License
*
* Copyright (c) 2009 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.sf.picard.io;
import net.sf.picard.PicardException;
import net.sf.samtools.util.CloserUtil;
import java.io.InputStream;
import java.io.IOException;
/**
* Line-oriented InputStream reader that uses one buffer for disk buffering and line-termination-finding,
* in order to improve performance.
*
* Implementation detail: All public methods must leave the input buffer in a non-empty state, unless at EOF.
*
* @author [email protected]
*/
public class FastLineReader {
private InputStream in;
private byte[] fileBuffer = new byte[512000];
// Next byte to read in fileBuffer
private int nextByte = 0;
// Number of bytes in fileBuffer
private int numBytes = 0;
private boolean atEof;
public FastLineReader(final InputStream in) {
this.in = in;
ensureBufferNotEmpty();
}
/**
* @return true if input is exhausted
*/
public boolean eof() {
return atEof;
}
/**
* @return peeks at the next byte in the stream and returns true if it is CR or LF. Returns false if EOF or
* next byte is not CR or LF.
*/
public boolean atEoln() {
return ensureBufferNotEmpty() && (fileBuffer[nextByte] == '\n' || fileBuffer[nextByte] == '\r');
}
/**
* Advance over any EOLN chars (CR or LF)
* @return true if saw one or more CR or LFs
*/
public boolean skipNewlines() {
boolean sawEoln = false;
while (atEoln()) {
sawEoln = true;
++nextByte;
}
return sawEoln;
}
public void close() {
CloserUtil.close(in);
in = null;
fileBuffer = null;
}
/**
* @return Next byte from the input. Do not call if at EOF.
*/
public byte getByte() {
final byte ret = peekByte();
++nextByte;
ensureBufferNotEmpty();
return ret;
}
/**
* @return Next byte from the input, without advancing over that byte. Do not call if at EOF.
*/
public byte peekByte() {
if (eof()) {
throw new IllegalStateException("Cannot getByte() if EOF.");
}
return fileBuffer[nextByte];
}
/**
* Read from input until input is exhausted, EOLN is seen, or output buffer is filled
* @param outputBuffer where to put bytes read
* @param startOutputIndex where to start putting bytes read
* @return number of bytes read
*/
public int readToEndOfOutputBufferOrEoln(final byte[] outputBuffer, final int startOutputIndex) {
boolean sawNewline;
int totalGrabbed = 0;
do {
if (!ensureBufferNotEmpty()) {
break;
}
final int startInputIndex = nextByte;
sawNewline = advanceToEobOrEoln();
int lengthOfChunk = nextByte - startInputIndex;
// Roll back if went past the amount that can be stored in the output buffer.
// Assumption is that lines are relatively short so this won't happen very often.
- if (lengthOfChunk > outputBuffer.length - startOutputIndex) {
- lengthOfChunk = outputBuffer.length - startOutputIndex;
+ if (lengthOfChunk > outputBuffer.length - (startOutputIndex + totalGrabbed)) {
+ lengthOfChunk = outputBuffer.length - (startOutputIndex + totalGrabbed);
nextByte = startInputIndex + lengthOfChunk;
}
System.arraycopy(fileBuffer, startInputIndex, outputBuffer, startOutputIndex + totalGrabbed, lengthOfChunk);
totalGrabbed += lengthOfChunk;
} while (!sawNewline && totalGrabbed < outputBuffer.length - startOutputIndex);
ensureBufferNotEmpty();
return totalGrabbed;
}
/**
* Advance nextByte to end of currently-buffered input or to line terminator
* @return true if saw a line terminator
*/
private boolean advanceToEobOrEoln() {
while (nextByte < numBytes) {
if (atEoln()) {
return true;
}
++nextByte;
}
return false;
}
/**
* Ensure that fileBuffer has at least one byte available in it. Potentially wipes out
* what is in fileBuffer so everything from fileBuffer[0..nextByte] should already have been pulled out.
* @return false if EOF, else true
*/
private boolean ensureBufferNotEmpty() {
try {
if (nextByte < numBytes) {
return true;
}
nextByte = 0;
numBytes = in.read(fileBuffer);
atEof = (numBytes < 1);
return !atEof;
} catch (IOException e) {
throw new PicardException("Exception reading InputStream", e);
}
}
}
| true | true | public int readToEndOfOutputBufferOrEoln(final byte[] outputBuffer, final int startOutputIndex) {
boolean sawNewline;
int totalGrabbed = 0;
do {
if (!ensureBufferNotEmpty()) {
break;
}
final int startInputIndex = nextByte;
sawNewline = advanceToEobOrEoln();
int lengthOfChunk = nextByte - startInputIndex;
// Roll back if went past the amount that can be stored in the output buffer.
// Assumption is that lines are relatively short so this won't happen very often.
if (lengthOfChunk > outputBuffer.length - startOutputIndex) {
lengthOfChunk = outputBuffer.length - startOutputIndex;
nextByte = startInputIndex + lengthOfChunk;
}
System.arraycopy(fileBuffer, startInputIndex, outputBuffer, startOutputIndex + totalGrabbed, lengthOfChunk);
totalGrabbed += lengthOfChunk;
} while (!sawNewline && totalGrabbed < outputBuffer.length - startOutputIndex);
ensureBufferNotEmpty();
return totalGrabbed;
}
| public int readToEndOfOutputBufferOrEoln(final byte[] outputBuffer, final int startOutputIndex) {
boolean sawNewline;
int totalGrabbed = 0;
do {
if (!ensureBufferNotEmpty()) {
break;
}
final int startInputIndex = nextByte;
sawNewline = advanceToEobOrEoln();
int lengthOfChunk = nextByte - startInputIndex;
// Roll back if went past the amount that can be stored in the output buffer.
// Assumption is that lines are relatively short so this won't happen very often.
if (lengthOfChunk > outputBuffer.length - (startOutputIndex + totalGrabbed)) {
lengthOfChunk = outputBuffer.length - (startOutputIndex + totalGrabbed);
nextByte = startInputIndex + lengthOfChunk;
}
System.arraycopy(fileBuffer, startInputIndex, outputBuffer, startOutputIndex + totalGrabbed, lengthOfChunk);
totalGrabbed += lengthOfChunk;
} while (!sawNewline && totalGrabbed < outputBuffer.length - startOutputIndex);
ensureBufferNotEmpty();
return totalGrabbed;
}
|
diff --git a/src/pt/up/fe/dceg/neptus/console/actions/SaveMissionAsConsoleAction.java b/src/pt/up/fe/dceg/neptus/console/actions/SaveMissionAsConsoleAction.java
index eafc73d0a..f9cabd928 100644
--- a/src/pt/up/fe/dceg/neptus/console/actions/SaveMissionAsConsoleAction.java
+++ b/src/pt/up/fe/dceg/neptus/console/actions/SaveMissionAsConsoleAction.java
@@ -1,91 +1,91 @@
/*
* Copyright (c) 2004-2013 Universidade do Porto - Faculdade de Engenharia
* Laboratório de Sistemas e Tecnologia Subaquática (LSTS)
* All rights reserved.
* Rua Dr. Roberto Frias s/n, sala I203, 4200-465 Porto, Portugal
*
* This file is part of Neptus, Command and Control Framework.
*
* Commercial Licence Usage
* Licencees holding valid commercial Neptus licences may use this file
* in accordance with the commercial licence agreement provided with the
* Software or, alternatively, in accordance with the terms contained in a
* written agreement between you and Universidade do Porto. For licensing
* terms, conditions, and further information contact [email protected].
*
* European Union Public Licence - EUPL v.1.1 Usage
* Alternatively, this file may be used under the terms of the EUPL,
* Version 1.1 only (the "Licence"), appearing in the file LICENCE.md
* included in the packaging of this file. You may not use this work
* except in compliance with the Licence. Unless required by applicable
* law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the Licence for the specific
* language governing permissions and limitations at
* https://www.lsts.pt/neptus/licence.
*
* For more information please see <http://lsts.fe.up.pt/neptus>.
*
* Author: Hugo Dias
* Oct 17, 2012
*/
package pt.up.fe.dceg.neptus.console.actions;
import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import pt.up.fe.dceg.neptus.console.ConsoleLayout;
import pt.up.fe.dceg.neptus.i18n.I18n;
import pt.up.fe.dceg.neptus.types.map.MapGroup;
import pt.up.fe.dceg.neptus.util.GuiUtils;
import pt.up.fe.dceg.neptus.util.ImageUtils;
import pt.up.fe.dceg.neptus.util.NameNormalizer;
/**
* @author Hugo
*
*/
@SuppressWarnings("serial")
public class SaveMissionAsConsoleAction extends ConsoleAction{
protected ConsoleLayout console;
public SaveMissionAsConsoleAction(ConsoleLayout console) {
super(I18n.text("Save Mission As..."), new ImageIcon(ImageUtils.getImage("images/menus/saveas.png")));
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Event.CTRL_MASK
+ java.awt.Event.ALT_MASK, true));
this.console = console;
- this.setEnabled(false);
+ this.setEnabled(true);
}
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser(console.getMission().getMissionFile());
chooser.setFileFilter(GuiUtils.getCustomFileFilter("Mission Files ('nmisz')", new String[] { "nmisz" }));
int resp = chooser.showDialog(console, "Save");
if (resp == JFileChooser.APPROVE_OPTION) {
if (chooser.getSelectedFile().exists()) {
resp = JOptionPane.showConfirmDialog(console,
I18n.text("Do you want to overwrite the existing file?"),
I18n.text("Save Mission As..."), JOptionPane.YES_NO_CANCEL_OPTION);
if (resp != JOptionPane.YES_OPTION) {
return;
}
}
File dst = chooser.getSelectedFile();
if (!dst.getAbsolutePath().endsWith(".nmisz")) {
dst = new File(dst.getAbsolutePath() + ".nmisz");
}
console.getMission().setMissionFile(dst);
console.getMission().setId(NameNormalizer.getRandomID());
console.getMission().save(false);
MapGroup.resetMissionInstance(console.getMission());
}
}
}
| true | true | public SaveMissionAsConsoleAction(ConsoleLayout console) {
super(I18n.text("Save Mission As..."), new ImageIcon(ImageUtils.getImage("images/menus/saveas.png")));
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Event.CTRL_MASK
+ java.awt.Event.ALT_MASK, true));
this.console = console;
this.setEnabled(false);
}
| public SaveMissionAsConsoleAction(ConsoleLayout console) {
super(I18n.text("Save Mission As..."), new ImageIcon(ImageUtils.getImage("images/menus/saveas.png")));
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.Event.CTRL_MASK
+ java.awt.Event.ALT_MASK, true));
this.console = console;
this.setEnabled(true);
}
|
diff --git a/src/com/edinarobotics/utils/gamepad/FilteredGamepad.java b/src/com/edinarobotics/utils/gamepad/FilteredGamepad.java
index 72b5ffa..c0b3f30 100644
--- a/src/com/edinarobotics/utils/gamepad/FilteredGamepad.java
+++ b/src/com/edinarobotics/utils/gamepad/FilteredGamepad.java
@@ -1,99 +1,100 @@
package com.edinarobotics.utils.gamepad;
import com.edinarobotics.utils.gamepad.gamepadfilters.GamepadFilterSet;
import com.edinarobotics.utils.math.Vector2;
/**
* Implements a Gamepad that filters all of its joystick axis values through
* a given GamepadFilterSet.
*/
public class FilteredGamepad extends Gamepad{
GamepadFilterSet filters;
/**
* Constructs a new FilteredGamepad that will send the axis results
* of the gamepad on the given port through the given GamepadFilterSet.
* @param port The port of the gamepad that is to be wrapped by this
* FilteredGamepad.
* @param filterSet The GamepadFilterSet through which all joystick
* values are to be sent.
*/
public FilteredGamepad(int port, GamepadFilterSet filterSet){
super(port);
+ this.filters = filterSet;
}
/**
* Returns the state of the left joystick as a Vector2.
* This vector 2 contains the state of the x- and y- axis of the joystick.
* @return A Vector2 representing the state of the left joystick after
* being filtered by the given GamepadFilterSet.
*/
public Vector2 getLeftJoystick(){
return filters.filter(super.getGamepadAxisState()).getLeftJoystick();
}
/**
* Returns the state of the right joystick as a Vector2.
* This vector 2 contains the state of the x- and y- axis of the joystick.
* @return A Vector2 representing the state of the right joystick after
* being filtered by the given GamepadFilterSet.
*/
public Vector2 getRightJoystick(){
return filters.filter(super.getGamepadAxisState()).getRightJoystick();
}
/**
* Returns the state of the gamepad's joysticks together in a
* GamepadAxisState. The values in this object have been filtered
* by the given GamepadFilterSet.
* @return A GamepadAxisState object containing the states of all the
* joystick axes on this Gamepad.
*/
public GamepadAxisState getAxisState(){
return filters.filter(super.getGamepadAxisState());
}
/**
* Returns the current value of the x-axis of the left joystick. <br/>
* A value of {@code -1} indicates that the joystick is fully left.<br/>
* A value of {@code 1} indicates that the joystick is fully right.
* @return The current value of the x-axis of the left joystick after
* being sent through the given GamepadFilterSet.
*/
public double getLeftX(){
return getLeftJoystick().getX();
}
/**
* Returns the current value of the y-axis of the left joystick. <br/>
* A value of {@code -1} indicates that the joystick is fully down.<br/>
* A value of {@code 1} indicates that the joystick is fully up.
* @return The current value of the y-axis of the left joystick after
* being sent through the given GamepadFilterSet.
*/
public double getLeftY(){
return getLeftJoystick().getY();
}
/**
* Returns the current value of the x-axis of the right joystick. <br/>
* A value of {@code -1} indicates that the joystick is fully left.<br/>
* A value of {@code 1} indicates that the joystick is fully right.
* @return The current value of the x-axis of the right joystick after
* being sent through the given GamepadFilterSet.
*/
public double getRightX(){
return getRightJoystick().getX();
}
/**
* Returns the current value of the y-axis of the right joystick. <br/>
* A value of {@code -1} indicates that the joystick is fully down.<br/>
* A value of {@code 1} indicates that the joystick is fully up.
* @return The current value of the y-axis of the right joystick after
* being sent through the given GamepadFilterSet.
*/
public double getRightY(){
return getRightJoystick().getY();
}
}
| true | true | public FilteredGamepad(int port, GamepadFilterSet filterSet){
super(port);
}
| public FilteredGamepad(int port, GamepadFilterSet filterSet){
super(port);
this.filters = filterSet;
}
|
diff --git a/sql12/app/src/net/sourceforge/squirrel_sql/client/gui/mainframe/MainFrame.java b/sql12/app/src/net/sourceforge/squirrel_sql/client/gui/mainframe/MainFrame.java
index cae7c1886..41beaeacb 100644
--- a/sql12/app/src/net/sourceforge/squirrel_sql/client/gui/mainframe/MainFrame.java
+++ b/sql12/app/src/net/sourceforge/squirrel_sql/client/gui/mainframe/MainFrame.java
@@ -1,570 +1,569 @@
package net.sourceforge.squirrel_sql.client.gui.mainframe;
/*
* Copyright (C) 2001-2004 Colin Bell
* [email protected]
*
* Modifications Copyright (C) 2003-2004 Jason Height
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyVetoException;
import java.util.prefs.Preferences;
import javax.swing.*;
import net.sourceforge.squirrel_sql.fw.gui.CascadeInternalFramePositioner;
import net.sourceforge.squirrel_sql.fw.gui.Dialogs;
import net.sourceforge.squirrel_sql.fw.gui.GUIUtils;
import net.sourceforge.squirrel_sql.fw.gui.IInternalFramePositioner;
import net.sourceforge.squirrel_sql.fw.util.StringManager;
import net.sourceforge.squirrel_sql.fw.util.StringManagerFactory;
import net.sourceforge.squirrel_sql.fw.util.log.ILogger;
import net.sourceforge.squirrel_sql.fw.util.log.LoggerController;
import net.sourceforge.squirrel_sql.fw.datasetviewer.IMainFrame;
import net.sourceforge.squirrel_sql.client.IApplication;
import net.sourceforge.squirrel_sql.client.Version;
import net.sourceforge.squirrel_sql.client.gui.ScrollableDesktopPane;
import net.sourceforge.squirrel_sql.client.gui.session.SessionInternalFrame;
import net.sourceforge.squirrel_sql.client.preferences.SquirrelPreferences;
import net.sourceforge.squirrel_sql.client.resources.SquirrelResources;
import net.sourceforge.squirrel_sql.client.session.MessagePanel;
public class MainFrame extends JFrame implements IMainFrame //BaseMDIParentFrame
{
public interface IMenuIDs extends MainFrameMenuBar.IMenuIDs
{
// Empty body.
}
/** Logger for this class. */
private final ILogger s_log = LoggerController.createLogger(MainFrame.class);
/** Internationalized strings for this class. */
private static final StringManager s_stringMgr =
StringManagerFactory.getStringManager(MainFrame.class);
/** Application API. */
private final IApplication _app;
// private AliasesListInternalFrame _aliasesListWindow;
// private DriversListInternalFrame _driversListWindow;
/** Toolbar at top of window. */
private MainFrameToolBar _toolBar;
/** Status bar at bottom of window. */
private MainFrameStatusBar _statusBar;
/** Message panel at bottom of window. */
// JASON: Should be part of status bar?
private MessagePanel _msgPnl;
/** If <TT>true</TT> then status bar is visible. */
private boolean _statusBarVisible = false;
private JDesktopPane _desktop;
private final IInternalFramePositioner _internalFramePositioner = new CascadeInternalFramePositioner();
// private Map _children = new HashMap();
private static final String PREFS_KEY_MESSAGEPANEL_HEIGHT = "squirrelSql_msgPanel_height";
private boolean m_hasBeenVisible;
private JSplitPane _splitPn;
/**
* Ctor.
*
* @param app Application API.
*
* @throws IllegalArgumentException
* Thrown if <TT>null</TT> <TT>IApplication</TT>
* passed.
*/
public MainFrame(IApplication app)
{
super(Version.getVersion());
if (app == null)
{
throw new IllegalArgumentException("Null IApplication passed");
}
_app = app;
_desktop = new ScrollableDesktopPane();
createUserInterface();
preferencesHaveChanged(null); // Initial load of prefs.
_app.getSquirrelPreferences().addPropertyChangeListener(new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent evt)
{
synchronized (MainFrame.this)
{
preferencesHaveChanged(evt);
}
}
});
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
ScrollableDesktopPane comp = (ScrollableDesktopPane)getDesktopPane();
comp.setPreferredSize(comp.getRequiredSize());
comp.revalidate();
}
});
}
public void dispose()
{
boolean shouldDispose = true;
if (!_app.shutdown())
{
String msg = s_stringMgr.getString("MainFrame.errorOnClose");
shouldDispose = Dialogs.showYesNo(_app.getMainFrame(), msg);
}
if (shouldDispose)
{
closeAllToolWindows();
super.dispose();
System.exit(0);
}
}
public void pack()
{
// Don't call super. Packing this frame causes problems.
}
public IApplication getApplication()
{
return _app;
}
public JDesktopPane getDesktopPane()
{
return _desktop;
}
/**
* Add the passed internal frame to this MDI frame.
* Calls <TT>addInternalFrame(child, createMenuItem, null)</TT>.
*
* @param child The internal frame to be added.
* @param createMenuItem If <TT>true</TT> add an item to the MDI
* Window menu to select the passed internal frame.
*
* @throws IllegalArgumentException if null <TT>JInternalFrame</TT> passed.
*/
public void addInternalFrame(JInternalFrame child, boolean createMenuItem)
{
addInternalFrame(child, createMenuItem, null);
}
public void addInternalFrame(JInternalFrame child, boolean addToWindowMenu, Action action)
{
addInternalFrame(child, addToWindowMenu, action, null);
}
public void addInternalFrame(JInternalFrame child, boolean addToWindowMenu, Action action, Integer layer)
{
if (!GUIUtils.isToolWindow(child))
{
Dimension cs = getDesktopPane().getSize();
// Cast to int required as Dimension::setSize(double,double)
// doesn't appear to do anything in JDK1.2.2.
cs.setSize((int) (cs.width * 0.8d), (int) (cs.height * 0.8d));
child.setSize(cs);
}
if (child == null)
{
throw new IllegalArgumentException("Null JInternalFrame added");
}
if(null != layer)
{
_desktop.add(child, layer);
}
else
{
_desktop.add(child);
}
if (!GUIUtils.isToolWindow(child))
{
positionNewInternalFrame(child);
}
// JInternalFrame[] frames = GUIUtils.getOpenNonToolWindows(getDesktopPane().getAllFrames());
// _app.getActionCollection().internalFrameOpenedOrClosed(frames.length);
// Size non-tool child window.
if (!GUIUtils.isToolWindow(child))
{
if (child.isMaximizable() &&
_app.getSquirrelPreferences().getMaximizeSessionSheetOnOpen())
{
try
{
child.setMaximum(true);
}
catch (PropertyVetoException ex)
{
s_log.error("Unable to maximize window", ex);
}
}
}
}
public JMenu getSessionMenu()
{
return ((MainFrameMenuBar) getJMenuBar()).getSessionMenu();
}
public void addToMenu(int menuId, JMenu menu)
{
if (menu == null)
{
throw new IllegalArgumentException("Null JMenu passed");
}
((MainFrameMenuBar)getJMenuBar()).addToMenu(menuId, menu);
}
public void addToMenu(int menuId, Action action)
{
if (action == null)
{
throw new IllegalArgumentException("Null BaseAction passed");
}
((MainFrameMenuBar)getJMenuBar()).addToMenu(menuId, action);
}
/**
* Add component to the status bar.
*
* @param comp Component to add.
*
* @throws IllegalArgumentException
* Thrown if <TT>null</TT> <TT>JComponent</TT> passed.
*/
public void addToStatusBar(JComponent comp)
{
if (comp == null)
{
throw new IllegalArgumentException("JComponent == null");
}
_statusBar.addJComponent(comp);
}
/**
* Remove component to the main frames status bar.
*
* @param comp Component to remove.
*/
public void removeFromStatusBar(JComponent comp)
{
if (comp == null)
{
throw new IllegalArgumentException("JComponent == null");
}
_statusBar.remove(comp);
}
public MessagePanel getMessagePanel()
{
return _msgPnl;
}
private void preferencesHaveChanged(PropertyChangeEvent evt)
{
String propName = evt != null ? evt.getPropertyName() : null;
final SquirrelPreferences prefs = _app.getSquirrelPreferences();
if (propName == null
|| propName.equals(
SquirrelPreferences.IPropertyNames.SHOW_CONTENTS_WHEN_DRAGGING))
{
if (prefs.getShowContentsWhenDragging())
{
getDesktopPane().putClientProperty("JDesktopPane.dragMode", null);
}
else
{
getDesktopPane().putClientProperty("JDesktopPane.dragMode", "outline");
}
}
if (propName == null
|| propName.equals(SquirrelPreferences.IPropertyNames.SHOW_MAIN_STATUS_BAR))
{
final boolean show = prefs.getShowMainStatusBar();
if (!show && _statusBarVisible)
{
getContentPane().remove(_statusBar);
_statusBarVisible = false;
}
else if (show && !_statusBarVisible)
{
getContentPane().add(_statusBar, BorderLayout.SOUTH);
_statusBarVisible = true;
}
}
if (propName == null
|| propName.equals(SquirrelPreferences.IPropertyNames.SHOW_MAIN_TOOL_BAR))
{
final boolean show = prefs.getShowMainToolBar();
if (!show && _toolBar != null)
{
getContentPane().remove(_toolBar);
_toolBar = null;
}
else if (show && _toolBar == null)
{
_toolBar = new MainFrameToolBar(_app);
getContentPane().add(_toolBar, BorderLayout.NORTH);
}
}
}
private void closeAllToolWindows()
{
JInternalFrame[] frames =
GUIUtils.getOpenToolWindows(getDesktopPane().getAllFrames());
for (int i = 0; i < frames.length; ++i)
{
frames[i].dispose();
}
}
private void createUserInterface()
{
setVisible(false);
setDefaultCloseOperation(MainFrame.DO_NOTHING_ON_CLOSE);
final SquirrelResources rsrc = _app.getResources();
getDesktopPane().setDesktopManager(new MyDesktopManager());
final Container content = getContentPane();
// _aliasesToolWindow = new AliasesListInternalFrame(_app);
// _driversToolWindow = new DriversListInternalFrame(_app);
// preLoadActions();
content.setLayout(new BorderLayout());
final JScrollPane sp = new JScrollPane(getDesktopPane());
sp.setBorder(BorderFactory.createEmptyBorder());
_msgPnl = new MessagePanel()
{
public void setSize(int width, int height)
{
super.setSize(width, height);
if(0 < width && 0 < height)
{
// The call here is the result of a desperate fight
// to find a place where the components in the split
// had not height = 0. If someone knows a better way
// please tell me I'll apreciate any advice.
// [email protected]
resizeSplitOnStartup();
}
}
};
_msgPnl.setEditable(false);
_splitPn = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
_splitPn.add(sp);
_splitPn.add(new JScrollPane(_msgPnl));
_splitPn.setResizeWeight(1);
//i18n[MainFrame.saveSize=Save size]
String key = s_stringMgr.getString("MainFrame.saveSize");
Action splitDividerLocAction = new AbstractAction(key)
{
public void actionPerformed(ActionEvent e)
{
int msgPanelHeight = _splitPn.getBottomComponent().getSize().height;
Preferences.userRoot().putInt(PREFS_KEY_MESSAGEPANEL_HEIGHT, msgPanelHeight);
}
};
_msgPnl.addToMessagePanelPopup(splitDividerLocAction);
//i18n[MainFrame.restoreSize=Restore saved size]
- key = s_stringMgr.getString("MainFrame.restoreSize=Restore saved size");
+ key = s_stringMgr.getString("MainFrame.restoreSize");
- Action setSplitDividerLocAction =
- new AbstractAction(s_stringMgr.getString("MainFrame.restoreSize"))
+ Action setSplitDividerLocAction = new AbstractAction(key)
{
public void actionPerformed(ActionEvent e)
{
int prefMsgPanelHeight = Preferences.userRoot().getInt(PREFS_KEY_MESSAGEPANEL_HEIGHT, -1);
if(-1 != prefMsgPanelHeight)
{
int divLoc = getDividerLocation(prefMsgPanelHeight, _splitPn);
_splitPn.setDividerLocation(divLoc);
}
}
};
_msgPnl.addToMessagePanelPopup(setSplitDividerLocAction);
content.add(_splitPn, BorderLayout.CENTER);
_statusBar = new MainFrameStatusBar(_app);
final Font fn = _app.getFontInfoStore().getStatusBarFontInfo().createFont();
_statusBar.setFont(fn);
setJMenuBar(new MainFrameMenuBar(_app, getDesktopPane(), _app.getActionCollection()));
setupFromPreferences();
final ImageIcon icon = rsrc.getIcon(SquirrelResources.IImageNames.APPLICATION_ICON);
if (icon != null)
{
setIconImage(icon.getImage());
}
else
{
s_log.error("Missing icon for mainframe");
}
// On Win 2000 & XP mnemonics are normally hidden. To make them
// visible you press the alt key. Under the Windows L&F pressing
// alt may not work. This code is a workaround. See bug report
// 4736093 for more information.
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ALT, Event.ALT_MASK, false),
"repaint");
validate();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
dispose();
}
});
}
public void resizeSplitOnStartup()
{
if(false == m_hasBeenVisible)
{
m_hasBeenVisible = true;
final int prefMsgPanelHeight = Preferences.userRoot().getInt(PREFS_KEY_MESSAGEPANEL_HEIGHT, -1);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
if (-1 == prefMsgPanelHeight)
{
int divLoc = getDividerLocation(50, _splitPn);
_splitPn.setDividerLocation(divLoc);
}
else
{
int divLoc = getDividerLocation(prefMsgPanelHeight, _splitPn);
_splitPn.setDividerLocation(divLoc);
}
}
});
}
}
private int getDividerLocation(int wantedBottomComponentHeight, JSplitPane splitPn)
{
int splitBarSize =
splitPn.getSize().height -
splitPn.getBottomComponent().getSize().height -
splitPn.getTopComponent().getSize().height - 1;
int divLoc = splitPn.getSize().height - wantedBottomComponentHeight - splitBarSize;
return divLoc;
}
private void setupFromPreferences()
{
final SquirrelPreferences prefs = _app.getSquirrelPreferences();
MainFrameWindowState ws = prefs.getMainFrameWindowState();
// Position window to where it was when last closed. If this is not
// on the screen, move it back on to the screen.
setBounds(ws.getBounds().createRectangle());
if (!GUIUtils.isWithinParent(this))
{
setLocation(new Point(10, 10));
}
}
private void positionNewInternalFrame(JInternalFrame child)
{
_internalFramePositioner.positionInternalFrame(child);
}
public JMenu getWindowsMenu()
{
return ((MainFrameMenuBar)getJMenuBar()).getWindowsMenu();
}
public void addToToolBar(Action act)
{
_toolBar.add(act);
}
private class MyDesktopManager extends DefaultDesktopManager
{
public void activateFrame(JInternalFrame f)
{
super.activateFrame(f);
_app.getActionCollection().activationChanged(f);
}
public void deactivateFrame(JInternalFrame f)
{
super.deactivateFrame(f);
_app.getActionCollection().deactivationChanged(f);
}
}
}
| false | true | private void createUserInterface()
{
setVisible(false);
setDefaultCloseOperation(MainFrame.DO_NOTHING_ON_CLOSE);
final SquirrelResources rsrc = _app.getResources();
getDesktopPane().setDesktopManager(new MyDesktopManager());
final Container content = getContentPane();
// _aliasesToolWindow = new AliasesListInternalFrame(_app);
// _driversToolWindow = new DriversListInternalFrame(_app);
// preLoadActions();
content.setLayout(new BorderLayout());
final JScrollPane sp = new JScrollPane(getDesktopPane());
sp.setBorder(BorderFactory.createEmptyBorder());
_msgPnl = new MessagePanel()
{
public void setSize(int width, int height)
{
super.setSize(width, height);
if(0 < width && 0 < height)
{
// The call here is the result of a desperate fight
// to find a place where the components in the split
// had not height = 0. If someone knows a better way
// please tell me I'll apreciate any advice.
// [email protected]
resizeSplitOnStartup();
}
}
};
_msgPnl.setEditable(false);
_splitPn = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
_splitPn.add(sp);
_splitPn.add(new JScrollPane(_msgPnl));
_splitPn.setResizeWeight(1);
//i18n[MainFrame.saveSize=Save size]
String key = s_stringMgr.getString("MainFrame.saveSize");
Action splitDividerLocAction = new AbstractAction(key)
{
public void actionPerformed(ActionEvent e)
{
int msgPanelHeight = _splitPn.getBottomComponent().getSize().height;
Preferences.userRoot().putInt(PREFS_KEY_MESSAGEPANEL_HEIGHT, msgPanelHeight);
}
};
_msgPnl.addToMessagePanelPopup(splitDividerLocAction);
//i18n[MainFrame.restoreSize=Restore saved size]
key = s_stringMgr.getString("MainFrame.restoreSize=Restore saved size");
Action setSplitDividerLocAction =
new AbstractAction(s_stringMgr.getString("MainFrame.restoreSize"))
{
public void actionPerformed(ActionEvent e)
{
int prefMsgPanelHeight = Preferences.userRoot().getInt(PREFS_KEY_MESSAGEPANEL_HEIGHT, -1);
if(-1 != prefMsgPanelHeight)
{
int divLoc = getDividerLocation(prefMsgPanelHeight, _splitPn);
_splitPn.setDividerLocation(divLoc);
}
}
};
_msgPnl.addToMessagePanelPopup(setSplitDividerLocAction);
content.add(_splitPn, BorderLayout.CENTER);
_statusBar = new MainFrameStatusBar(_app);
final Font fn = _app.getFontInfoStore().getStatusBarFontInfo().createFont();
_statusBar.setFont(fn);
setJMenuBar(new MainFrameMenuBar(_app, getDesktopPane(), _app.getActionCollection()));
setupFromPreferences();
final ImageIcon icon = rsrc.getIcon(SquirrelResources.IImageNames.APPLICATION_ICON);
if (icon != null)
{
setIconImage(icon.getImage());
}
else
{
s_log.error("Missing icon for mainframe");
}
// On Win 2000 & XP mnemonics are normally hidden. To make them
// visible you press the alt key. Under the Windows L&F pressing
// alt may not work. This code is a workaround. See bug report
// 4736093 for more information.
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ALT, Event.ALT_MASK, false),
"repaint");
validate();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
dispose();
}
});
}
| private void createUserInterface()
{
setVisible(false);
setDefaultCloseOperation(MainFrame.DO_NOTHING_ON_CLOSE);
final SquirrelResources rsrc = _app.getResources();
getDesktopPane().setDesktopManager(new MyDesktopManager());
final Container content = getContentPane();
// _aliasesToolWindow = new AliasesListInternalFrame(_app);
// _driversToolWindow = new DriversListInternalFrame(_app);
// preLoadActions();
content.setLayout(new BorderLayout());
final JScrollPane sp = new JScrollPane(getDesktopPane());
sp.setBorder(BorderFactory.createEmptyBorder());
_msgPnl = new MessagePanel()
{
public void setSize(int width, int height)
{
super.setSize(width, height);
if(0 < width && 0 < height)
{
// The call here is the result of a desperate fight
// to find a place where the components in the split
// had not height = 0. If someone knows a better way
// please tell me I'll apreciate any advice.
// [email protected]
resizeSplitOnStartup();
}
}
};
_msgPnl.setEditable(false);
_splitPn = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
_splitPn.add(sp);
_splitPn.add(new JScrollPane(_msgPnl));
_splitPn.setResizeWeight(1);
//i18n[MainFrame.saveSize=Save size]
String key = s_stringMgr.getString("MainFrame.saveSize");
Action splitDividerLocAction = new AbstractAction(key)
{
public void actionPerformed(ActionEvent e)
{
int msgPanelHeight = _splitPn.getBottomComponent().getSize().height;
Preferences.userRoot().putInt(PREFS_KEY_MESSAGEPANEL_HEIGHT, msgPanelHeight);
}
};
_msgPnl.addToMessagePanelPopup(splitDividerLocAction);
//i18n[MainFrame.restoreSize=Restore saved size]
key = s_stringMgr.getString("MainFrame.restoreSize");
Action setSplitDividerLocAction = new AbstractAction(key)
{
public void actionPerformed(ActionEvent e)
{
int prefMsgPanelHeight = Preferences.userRoot().getInt(PREFS_KEY_MESSAGEPANEL_HEIGHT, -1);
if(-1 != prefMsgPanelHeight)
{
int divLoc = getDividerLocation(prefMsgPanelHeight, _splitPn);
_splitPn.setDividerLocation(divLoc);
}
}
};
_msgPnl.addToMessagePanelPopup(setSplitDividerLocAction);
content.add(_splitPn, BorderLayout.CENTER);
_statusBar = new MainFrameStatusBar(_app);
final Font fn = _app.getFontInfoStore().getStatusBarFontInfo().createFont();
_statusBar.setFont(fn);
setJMenuBar(new MainFrameMenuBar(_app, getDesktopPane(), _app.getActionCollection()));
setupFromPreferences();
final ImageIcon icon = rsrc.getIcon(SquirrelResources.IImageNames.APPLICATION_ICON);
if (icon != null)
{
setIconImage(icon.getImage());
}
else
{
s_log.error("Missing icon for mainframe");
}
// On Win 2000 & XP mnemonics are normally hidden. To make them
// visible you press the alt key. Under the Windows L&F pressing
// alt may not work. This code is a workaround. See bug report
// 4736093 for more information.
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ALT, Event.ALT_MASK, false),
"repaint");
validate();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
dispose();
}
});
}
|
diff --git a/src/uk/org/ownage/dmdirc/parser/callbacks/CallbackOnAwayStateOther.java b/src/uk/org/ownage/dmdirc/parser/callbacks/CallbackOnAwayStateOther.java
index 6784cf4bc..f1cafb489 100644
--- a/src/uk/org/ownage/dmdirc/parser/callbacks/CallbackOnAwayStateOther.java
+++ b/src/uk/org/ownage/dmdirc/parser/callbacks/CallbackOnAwayStateOther.java
@@ -1,77 +1,77 @@
/*
* Copyright (c) 2006-2007 Chris Smith, Shane Mc Cormack
*
* 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.
*
* SVN: $Id: CallbackOnAwayStateOther.java 719 2007-03-28 13:20:56Z ShaneMcC $
*/
package uk.org.ownage.dmdirc.parser.callbacks;
import uk.org.ownage.dmdirc.parser.IRCParser;
import uk.org.ownage.dmdirc.parser.ClientInfo;
import uk.org.ownage.dmdirc.parser.ParserError;
import uk.org.ownage.dmdirc.parser.callbacks.interfaces.IAwayStateOther;
/**
* Callback to all objects implementing the IAwayStateOther Interface.
*/
public final class CallbackOnAwayStateOther extends CallbackObjectSpecific {
/**
* Create a new instance of the Callback Object.
*
* @param parser IRCParser That owns this callback
* @param manager CallbackManager that is in charge of this callback
*/
public CallbackOnAwayStateOther(final IRCParser parser, final CallbackManager manager) { super(parser, manager); }
/**
* Callback to all objects implementing the IAwayStateOther Interface.
*
* @param client Client this is for
* @param state Away State (true if away, false if here)
* @see IAwayStateOther
* @return true if a callback was called, else false
*/
public boolean call(ClientInfo client, boolean state) {
boolean bResult = false;
IAwayStateOther eMethod = null;
for (int i = 0; i < callbackInfo.size(); i++) {
eMethod = (IAwayStateOther) callbackInfo.get(i);
- if (!this.isValidUser(eMethod, sHost)) { continue; }
+ if (!this.isValidUser(eMethod, client.getNickname())) { continue; }
try {
eMethod.onAwayStateOther(myParser, client, state);
} catch (Exception e) {
final ParserError ei = new ParserError(ParserError.ERROR_ERROR, "Exception in onAwayStateOther");
ei.setException(e);
callErrorInfo(ei);
}
bResult = true;
}
return bResult;
}
/**
* Get SVN Version information.
*
* @return SVN Version String
*/
public static String getSvnInfo() { return "$Id: CallbackOnAwayStateOther.java 719 2007-03-28 13:20:56Z ShaneMcC $"; }
}
| true | true | public boolean call(ClientInfo client, boolean state) {
boolean bResult = false;
IAwayStateOther eMethod = null;
for (int i = 0; i < callbackInfo.size(); i++) {
eMethod = (IAwayStateOther) callbackInfo.get(i);
if (!this.isValidUser(eMethod, sHost)) { continue; }
try {
eMethod.onAwayStateOther(myParser, client, state);
} catch (Exception e) {
final ParserError ei = new ParserError(ParserError.ERROR_ERROR, "Exception in onAwayStateOther");
ei.setException(e);
callErrorInfo(ei);
}
bResult = true;
}
return bResult;
}
| public boolean call(ClientInfo client, boolean state) {
boolean bResult = false;
IAwayStateOther eMethod = null;
for (int i = 0; i < callbackInfo.size(); i++) {
eMethod = (IAwayStateOther) callbackInfo.get(i);
if (!this.isValidUser(eMethod, client.getNickname())) { continue; }
try {
eMethod.onAwayStateOther(myParser, client, state);
} catch (Exception e) {
final ParserError ei = new ParserError(ParserError.ERROR_ERROR, "Exception in onAwayStateOther");
ei.setException(e);
callErrorInfo(ei);
}
bResult = true;
}
return bResult;
}
|
diff --git a/atlas-web/src/main/java/ae3/anatomogram/Anatomogram.java b/atlas-web/src/main/java/ae3/anatomogram/Anatomogram.java
index 483aa3bc1..9f83d7a01 100644
--- a/atlas-web/src/main/java/ae3/anatomogram/Anatomogram.java
+++ b/atlas-web/src/main/java/ae3/anatomogram/Anatomogram.java
@@ -1,299 +1,300 @@
/*
* Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package ae3.anatomogram;
import org.apache.batik.dom.util.DOMUtilities;
import org.apache.batik.parser.PathHandler;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.batik.transcoder.image.PNGTranscoder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* This code originally extracted from the Annotator.java...
*
* @author Olga Melnichuk
* Date: Dec 13, 2010
*/
public class Anatomogram {
static class Annotation {
private String id;
private String caption;
private int up;
private int dn;
private float x;
private float y;
public Annotation(String id, String caption, int up, int dn, float x, float y) {
this.id = id;
this.caption = caption;
this.up = up;
this.dn = dn;
this.x = x;
this.y = y;
}
}
public static enum Encoding {
Svg, Jpeg, Png
}
static enum HeatmapStyle {
UpDn, Up, Dn, Blank;
public static HeatmapStyle forUpDnValues(int up, int dn) {
if ((up > 0) && (dn > 0)) {
return UpDn;
} else if (up > 0) {
return Up;
} else if (dn > 0) {
return Dn;
}
return Blank;
}
}
public static final int MAX_ANNOTATIONS = 9;
private final Document svgDocument;
private List<Annotation> annotations = new ArrayList<Annotation>();
private List<AnatomogramArea> map = new ArrayList<AnatomogramArea>();
public Anatomogram(Document svgDocument) {
this.svgDocument = svgDocument;
}
public void writePngToStream(OutputStream outputStream) throws IOException, TranscoderException {
writeToStream(Encoding.Png, outputStream);
}
public void writeToStream(Encoding encoding, OutputStream outputStream) throws IOException, TranscoderException {
if (outputStream == null) {
return;
}
switch (encoding) {
case Svg: {
DOMUtilities.writeDocument(svgDocument, new OutputStreamWriter(outputStream));
break;
}
case Jpeg: {
JPEGTranscoder t = new JPEGTranscoder();
// t.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(. 8));
TranscoderInput input = new TranscoderInput(svgDocument);
TranscoderOutput output = new TranscoderOutput(outputStream);
t.transcode(input, output);
break;
}
case Png: {
PNGTranscoder t = new PNGTranscoder();
//t.addTranscodingHint(JPEGTranscoder.KEY_WIDTH, new Float(350));
//t.addTranscodingHint(JPEGTranscoder.KEY_HEIGHT, new Float(150));
TranscoderInput input = new TranscoderInput(svgDocument);
TranscoderOutput output = new TranscoderOutput(outputStream);
t.transcode(input, output);
break;
}
default:
throw new IllegalStateException("unknown encoding");
}
}
public List<AnatomogramArea> getAreaMap() {
List<AnatomogramArea> list = new ArrayList<AnatomogramArea>();
list.addAll(map);
return list;
}
public void addAnnotation(String id, String caption, int up, int dn) {
if (map.size() >= MAX_ANNOTATIONS) {
return;
}
Element elem = svgDocument.getElementById(id);
if (elem != null) {
AnnotationPathHandler pathHandler = new AnnotationPathHandler();
parseElement(elem, pathHandler);
annotations.add(new Annotation(id, caption, up, dn, pathHandler.getCenterX(), pathHandler.getCenterY()));
applyChanges();
}
}
public boolean isEmpty() {
return annotations.isEmpty();
}
private void applyChanges() {
map.clear();
Collections.sort(annotations, new Comparator<Annotation>() {
public int compare(Annotation a1, Annotation a2) {
return Float.compare(a1.y, a2.y);
}
});
Editor editor = new Editor(svgDocument);
for (int i = 1; i <= MAX_ANNOTATIONS; i++) {
String index = formatInt(i);
final String calloutId = "pathCallout" + index;
final String rectId = "rectCallout" + index;
final String triangleId = "triangleCallout" + index;
final String textCalloutUpId = "textCalloutUp" + index;
final String textCalloutDnId = "textCalloutDn" + index;
final String textCalloutCenterId = "textCalloutCenter" + index;
final String textCalloutCaptionId = "textCalloutCaption" + index;
boolean noAnnotation = i >= annotations.size();
String visibility = noAnnotation ? "hidden" : "visible";
editor.setVisibility(calloutId, visibility);
editor.setVisibility(rectId, visibility);
editor.setVisibility(triangleId, visibility);
editor.setVisibility(textCalloutUpId, visibility);
editor.setVisibility(textCalloutDnId, visibility);
editor.setVisibility(textCalloutCenterId, visibility);
editor.setVisibility(textCalloutCaptionId, visibility);
if (noAnnotation) {
continue;
}
Element calloutEl = svgDocument.getElementById(calloutId);
if (null == calloutEl)
throw new IllegalStateException("can not find element" + calloutId);
- Annotation currAn = annotations.get(i);
+ // NB. i-1 because while indexing in svg file starts from 1, java arrays are indexed from 0
+ Annotation currAn = annotations.get(i-1);
CalloutPathHandler calloutPathHandler = new CalloutPathHandler();
parseElement(calloutEl, calloutPathHandler);
final float X = calloutPathHandler.getRightmostX();
final float Y = calloutPathHandler.getRightmostY();
String calloutPath = String.format("M %f,%f L %f,%f"
, currAn.x
, currAn.y
, X
, Y);
calloutEl.setAttributeNS(null, "d", calloutPath);
final HeatmapStyle style = HeatmapStyle.forUpDnValues(currAn.up, currAn.dn);
switch (style) {
case UpDn:
editor.fill(rectId, "blue");
editor.fill(triangleId, "red");
editor.setTextAndAlign(textCalloutUpId, formatInt(currAn.up));
editor.setTextAndAlign(textCalloutDnId, formatInt(currAn.dn));
editor.setVisibility(textCalloutCenterId, "hidden");
editor.fill(currAn.id, "grey");
editor.setOpacity(currAn.id, "0.5");
break;
case Up:
editor.fill(rectId, "red");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.up));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "red");
editor.setOpacity(currAn.id, "0.5");
break;
case Dn:
editor.fill(rectId, "blue");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.dn));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "blue");
editor.setOpacity(currAn.id, "0.5");
break;
case Blank:
editor.fill(rectId, "none");
editor.setVisibility(triangleId, "hidden");
editor.setText(textCalloutCenterId, formatInt(0));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.setStroke(textCalloutCenterId, "black");
editor.setOpacity(currAn.id, "0.5");
break;
}
editor.setText(textCalloutCaptionId, currAn.caption);
Element rectEl = svgDocument.getElementById(rectId);
Float x = Float.parseFloat(rectEl.getAttribute("x"));
Float y = Float.parseFloat(rectEl.getAttribute("y"));
Float height = Float.parseFloat(rectEl.getAttribute("height"));
Float width = Float.parseFloat(rectEl.getAttribute("width"));
AnatomogramArea area = new AnatomogramArea();
area.x0 = x.intValue();
area.x1 = Math.round(x + width + 200);
area.y0 = y.intValue();
area.y1 = Math.round(y + height);
area.name = currAn.caption;
area.efo = currAn.id;
map.add(area);
}
}
private void parseElement(Element elem, PathHandler pathHandler) {
String s_efo0 = elem.getAttribute("d");
org.apache.batik.parser.PathParser pa = new org.apache.batik.parser.PathParser();
pa.setPathHandler(pathHandler);
pa.parse(s_efo0);
}
private static String formatInt(int i) {
return String.format("%1$d", i);
}
}
| true | true | private void applyChanges() {
map.clear();
Collections.sort(annotations, new Comparator<Annotation>() {
public int compare(Annotation a1, Annotation a2) {
return Float.compare(a1.y, a2.y);
}
});
Editor editor = new Editor(svgDocument);
for (int i = 1; i <= MAX_ANNOTATIONS; i++) {
String index = formatInt(i);
final String calloutId = "pathCallout" + index;
final String rectId = "rectCallout" + index;
final String triangleId = "triangleCallout" + index;
final String textCalloutUpId = "textCalloutUp" + index;
final String textCalloutDnId = "textCalloutDn" + index;
final String textCalloutCenterId = "textCalloutCenter" + index;
final String textCalloutCaptionId = "textCalloutCaption" + index;
boolean noAnnotation = i >= annotations.size();
String visibility = noAnnotation ? "hidden" : "visible";
editor.setVisibility(calloutId, visibility);
editor.setVisibility(rectId, visibility);
editor.setVisibility(triangleId, visibility);
editor.setVisibility(textCalloutUpId, visibility);
editor.setVisibility(textCalloutDnId, visibility);
editor.setVisibility(textCalloutCenterId, visibility);
editor.setVisibility(textCalloutCaptionId, visibility);
if (noAnnotation) {
continue;
}
Element calloutEl = svgDocument.getElementById(calloutId);
if (null == calloutEl)
throw new IllegalStateException("can not find element" + calloutId);
Annotation currAn = annotations.get(i);
CalloutPathHandler calloutPathHandler = new CalloutPathHandler();
parseElement(calloutEl, calloutPathHandler);
final float X = calloutPathHandler.getRightmostX();
final float Y = calloutPathHandler.getRightmostY();
String calloutPath = String.format("M %f,%f L %f,%f"
, currAn.x
, currAn.y
, X
, Y);
calloutEl.setAttributeNS(null, "d", calloutPath);
final HeatmapStyle style = HeatmapStyle.forUpDnValues(currAn.up, currAn.dn);
switch (style) {
case UpDn:
editor.fill(rectId, "blue");
editor.fill(triangleId, "red");
editor.setTextAndAlign(textCalloutUpId, formatInt(currAn.up));
editor.setTextAndAlign(textCalloutDnId, formatInt(currAn.dn));
editor.setVisibility(textCalloutCenterId, "hidden");
editor.fill(currAn.id, "grey");
editor.setOpacity(currAn.id, "0.5");
break;
case Up:
editor.fill(rectId, "red");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.up));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "red");
editor.setOpacity(currAn.id, "0.5");
break;
case Dn:
editor.fill(rectId, "blue");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.dn));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "blue");
editor.setOpacity(currAn.id, "0.5");
break;
case Blank:
editor.fill(rectId, "none");
editor.setVisibility(triangleId, "hidden");
editor.setText(textCalloutCenterId, formatInt(0));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.setStroke(textCalloutCenterId, "black");
editor.setOpacity(currAn.id, "0.5");
break;
}
editor.setText(textCalloutCaptionId, currAn.caption);
Element rectEl = svgDocument.getElementById(rectId);
Float x = Float.parseFloat(rectEl.getAttribute("x"));
Float y = Float.parseFloat(rectEl.getAttribute("y"));
Float height = Float.parseFloat(rectEl.getAttribute("height"));
Float width = Float.parseFloat(rectEl.getAttribute("width"));
AnatomogramArea area = new AnatomogramArea();
area.x0 = x.intValue();
area.x1 = Math.round(x + width + 200);
area.y0 = y.intValue();
area.y1 = Math.round(y + height);
area.name = currAn.caption;
area.efo = currAn.id;
map.add(area);
}
}
| private void applyChanges() {
map.clear();
Collections.sort(annotations, new Comparator<Annotation>() {
public int compare(Annotation a1, Annotation a2) {
return Float.compare(a1.y, a2.y);
}
});
Editor editor = new Editor(svgDocument);
for (int i = 1; i <= MAX_ANNOTATIONS; i++) {
String index = formatInt(i);
final String calloutId = "pathCallout" + index;
final String rectId = "rectCallout" + index;
final String triangleId = "triangleCallout" + index;
final String textCalloutUpId = "textCalloutUp" + index;
final String textCalloutDnId = "textCalloutDn" + index;
final String textCalloutCenterId = "textCalloutCenter" + index;
final String textCalloutCaptionId = "textCalloutCaption" + index;
boolean noAnnotation = i >= annotations.size();
String visibility = noAnnotation ? "hidden" : "visible";
editor.setVisibility(calloutId, visibility);
editor.setVisibility(rectId, visibility);
editor.setVisibility(triangleId, visibility);
editor.setVisibility(textCalloutUpId, visibility);
editor.setVisibility(textCalloutDnId, visibility);
editor.setVisibility(textCalloutCenterId, visibility);
editor.setVisibility(textCalloutCaptionId, visibility);
if (noAnnotation) {
continue;
}
Element calloutEl = svgDocument.getElementById(calloutId);
if (null == calloutEl)
throw new IllegalStateException("can not find element" + calloutId);
// NB. i-1 because while indexing in svg file starts from 1, java arrays are indexed from 0
Annotation currAn = annotations.get(i-1);
CalloutPathHandler calloutPathHandler = new CalloutPathHandler();
parseElement(calloutEl, calloutPathHandler);
final float X = calloutPathHandler.getRightmostX();
final float Y = calloutPathHandler.getRightmostY();
String calloutPath = String.format("M %f,%f L %f,%f"
, currAn.x
, currAn.y
, X
, Y);
calloutEl.setAttributeNS(null, "d", calloutPath);
final HeatmapStyle style = HeatmapStyle.forUpDnValues(currAn.up, currAn.dn);
switch (style) {
case UpDn:
editor.fill(rectId, "blue");
editor.fill(triangleId, "red");
editor.setTextAndAlign(textCalloutUpId, formatInt(currAn.up));
editor.setTextAndAlign(textCalloutDnId, formatInt(currAn.dn));
editor.setVisibility(textCalloutCenterId, "hidden");
editor.fill(currAn.id, "grey");
editor.setOpacity(currAn.id, "0.5");
break;
case Up:
editor.fill(rectId, "red");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.up));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "red");
editor.setOpacity(currAn.id, "0.5");
break;
case Dn:
editor.fill(rectId, "blue");
editor.setVisibility(triangleId, "hidden");
editor.setTextAndAlign(textCalloutCenterId, formatInt(currAn.dn));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.fill(currAn.id, "blue");
editor.setOpacity(currAn.id, "0.5");
break;
case Blank:
editor.fill(rectId, "none");
editor.setVisibility(triangleId, "hidden");
editor.setText(textCalloutCenterId, formatInt(0));
editor.setVisibility(textCalloutUpId, "hidden");
editor.setVisibility(textCalloutDnId, "hidden");
editor.setStroke(textCalloutCenterId, "black");
editor.setOpacity(currAn.id, "0.5");
break;
}
editor.setText(textCalloutCaptionId, currAn.caption);
Element rectEl = svgDocument.getElementById(rectId);
Float x = Float.parseFloat(rectEl.getAttribute("x"));
Float y = Float.parseFloat(rectEl.getAttribute("y"));
Float height = Float.parseFloat(rectEl.getAttribute("height"));
Float width = Float.parseFloat(rectEl.getAttribute("width"));
AnatomogramArea area = new AnatomogramArea();
area.x0 = x.intValue();
area.x1 = Math.round(x + width + 200);
area.y0 = y.intValue();
area.y1 = Math.round(y + height);
area.name = currAn.caption;
area.efo = currAn.id;
map.add(area);
}
}
|
diff --git a/shell/src/main/java/org/jboss/seam/forge/shell/plugins/builtin/LsPlugin.java b/shell/src/main/java/org/jboss/seam/forge/shell/plugins/builtin/LsPlugin.java
index 07edaa90..b9d9cebd 100644
--- a/shell/src/main/java/org/jboss/seam/forge/shell/plugins/builtin/LsPlugin.java
+++ b/shell/src/main/java/org/jboss/seam/forge/shell/plugins/builtin/LsPlugin.java
@@ -1,117 +1,120 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2010, 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.jboss.seam.forge.shell.plugins.builtin;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.jboss.seam.forge.project.Resource;
import org.jboss.seam.forge.project.services.ResourceFactory;
import org.jboss.seam.forge.shell.Shell;
import org.jboss.seam.forge.shell.plugins.DefaultCommand;
import org.jboss.seam.forge.shell.plugins.Help;
import org.jboss.seam.forge.shell.plugins.Option;
import org.jboss.seam.forge.shell.plugins.Plugin;
/**
* @author <a href="mailto:[email protected]">Lincoln Baxter, III</a>
* @author Mike Brock
*/
@Named("ls")
@Help("Prints the contents current directory.")
public class LsPlugin implements Plugin
{
private final Shell shell;
private final ResourceFactory resourceFactory;
private final DateFormat format = new SimpleDateFormat("MMM WW HH:mm");
@Inject
public LsPlugin(ResourceFactory resourceFactory, Shell shell)
{
this.resourceFactory = resourceFactory;
this.shell = shell;
}
@DefaultCommand
public void run(@Option(flagOnly = true, name = "all", shortName = "a", required = false) boolean showAll)
{
Resource<?> resource = shell.getCurrentResource();
int width = shell.getWidth();
List<Resource<?>> childResources = resource.listResources(resourceFactory);
List<String> listData = new LinkedList<String>();
int maxLength = 0;
String el;
for (Resource r : childResources)
{
el = r.toString();
- if (showAll || !el.startsWith(".")) listData.add(el);
- if (el.length() > maxLength) maxLength = el.length();
+ if (showAll || !el.startsWith("."))
+ {
+ listData.add(el);
+ if (el.length() > maxLength) maxLength = el.length();
+ }
}
int cols = width / (maxLength + 4);
int colSize = width / cols;
if (cols == 0)
{
colSize = width;
cols = 1;
}
int i = 0;
for (String s : listData)
{
shell.print(s);
shell.print(pad(colSize - s.length()));
if (++i == cols)
{
shell.println();
i = 0;
}
}
shell.println();
}
private String pad(int amount)
{
char[] padding = new char[amount];
for (int i = 0; i < amount; i++)
{
padding[i] = ' ';
}
return new String(padding);
}
}
| true | true | public void run(@Option(flagOnly = true, name = "all", shortName = "a", required = false) boolean showAll)
{
Resource<?> resource = shell.getCurrentResource();
int width = shell.getWidth();
List<Resource<?>> childResources = resource.listResources(resourceFactory);
List<String> listData = new LinkedList<String>();
int maxLength = 0;
String el;
for (Resource r : childResources)
{
el = r.toString();
if (showAll || !el.startsWith(".")) listData.add(el);
if (el.length() > maxLength) maxLength = el.length();
}
int cols = width / (maxLength + 4);
int colSize = width / cols;
if (cols == 0)
{
colSize = width;
cols = 1;
}
int i = 0;
for (String s : listData)
{
shell.print(s);
shell.print(pad(colSize - s.length()));
if (++i == cols)
{
shell.println();
i = 0;
}
}
shell.println();
}
| public void run(@Option(flagOnly = true, name = "all", shortName = "a", required = false) boolean showAll)
{
Resource<?> resource = shell.getCurrentResource();
int width = shell.getWidth();
List<Resource<?>> childResources = resource.listResources(resourceFactory);
List<String> listData = new LinkedList<String>();
int maxLength = 0;
String el;
for (Resource r : childResources)
{
el = r.toString();
if (showAll || !el.startsWith("."))
{
listData.add(el);
if (el.length() > maxLength) maxLength = el.length();
}
}
int cols = width / (maxLength + 4);
int colSize = width / cols;
if (cols == 0)
{
colSize = width;
cols = 1;
}
int i = 0;
for (String s : listData)
{
shell.print(s);
shell.print(pad(colSize - s.length()));
if (++i == cols)
{
shell.println();
i = 0;
}
}
shell.println();
}
|
diff --git a/src/nrider/debug/SimController.java b/src/nrider/debug/SimController.java
index f2703f3..ae21dff 100644
--- a/src/nrider/debug/SimController.java
+++ b/src/nrider/debug/SimController.java
@@ -1,137 +1,137 @@
/*
* Copyright (c) 2009 David McIntosh ([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 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package nrider.debug;
import gnu.io.PortInUseException;
import nrider.event.EventPublisher;
import nrider.event.IEvent;
import nrider.io.*;
import java.io.IOException;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
*
*/
public class SimController implements IWorkoutController, IPerformanceDataSource, IControlDataSource
{
private String _identifier;
private double _load;
private TrainerMode _trainerMode;
private boolean _active;
private EventPublisher<IPerformanceDataListener> _performancePublisher = EventPublisher.directPublisher();
private Timer _timer = new Timer();
public SimController( String identifier )
{
_identifier = identifier;
_timer.scheduleAtFixedRate( new DataOutputTask(), 0, 1000 );
}
public String getType()
{
return "Simulator";
}
public String getIdentifier()
{
return _identifier;
}
public void setLoad( double load )
{
_load = load;
}
public double getLoad()
{
return _load;
}
public void setMode( TrainerMode mode )
{
_trainerMode = mode;
}
public TrainerMode getMode()
{
return _trainerMode;
}
public void disconnect() throws IOException
{
_active = false;
}
public void connect() throws PortInUseException
{
_active = true;
}
public void close() throws IOException
{
_active = false;
}
public void addPerformanceDataListener( IPerformanceDataListener listener )
{
_performancePublisher.addListener( listener );
}
public void addControlDataListener( IControlDataListener listener )
{
}
public void publishPerformanceData( final PerformanceData data )
{
_performancePublisher.publishEvent(
new IEvent<IPerformanceDataListener>()
{
public void trigger( IPerformanceDataListener target )
{
target.handlePerformanceData( getIdentifier(), data );
}
}
);
}
class DataOutputTask extends TimerTask
{
private double _currentPower;
private double _currentSpeed = 21/2.237;
@Override
public void run()
{
if( _active )
{
if( _currentPower != _load )
{
_currentPower += ( _load - _currentPower ) / 2;
}
publishPerformanceData( new PerformanceData( PerformanceData.Type.POWER, (float) _currentPower ) );
- publishPerformanceData( new PerformanceData( PerformanceData.Type.SPEED, (float) _currentSpeed + ( new Random( ).nextFloat() * 2 - 1 ) ) );
+ publishPerformanceData( new PerformanceData( PerformanceData.Type.SPEED, (float) ( _currentSpeed + ( ( new Random( ).nextFloat() * 2 - 1 ) / 2.237 ) ) ) );
}
}
}
}
| true | true | public void run()
{
if( _active )
{
if( _currentPower != _load )
{
_currentPower += ( _load - _currentPower ) / 2;
}
publishPerformanceData( new PerformanceData( PerformanceData.Type.POWER, (float) _currentPower ) );
publishPerformanceData( new PerformanceData( PerformanceData.Type.SPEED, (float) _currentSpeed + ( new Random( ).nextFloat() * 2 - 1 ) ) );
}
}
| public void run()
{
if( _active )
{
if( _currentPower != _load )
{
_currentPower += ( _load - _currentPower ) / 2;
}
publishPerformanceData( new PerformanceData( PerformanceData.Type.POWER, (float) _currentPower ) );
publishPerformanceData( new PerformanceData( PerformanceData.Type.SPEED, (float) ( _currentSpeed + ( ( new Random( ).nextFloat() * 2 - 1 ) / 2.237 ) ) ) );
}
}
|
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/adapters/DeleteHandlerDelegate.java b/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/adapters/DeleteHandlerDelegate.java
index d64745a56..0b7888343 100644
--- a/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/adapters/DeleteHandlerDelegate.java
+++ b/target_explorer/plugins/org.eclipse.tcf.te.tcf.filesystem/src/org/eclipse/tcf/te/tcf/filesystem/internal/adapters/DeleteHandlerDelegate.java
@@ -1,128 +1,128 @@
/*******************************************************************************
* Copyright (c) 2012 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.te.tcf.filesystem.internal.adapters;
import java.util.List;
import java.util.UUID;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.tcf.te.runtime.interfaces.callback.ICallback;
import org.eclipse.tcf.te.runtime.interfaces.properties.IPropertiesContainer;
import org.eclipse.tcf.te.tcf.filesystem.interfaces.IConfirmCallback;
import org.eclipse.tcf.te.tcf.filesystem.internal.operations.FSDelete;
import org.eclipse.tcf.te.tcf.filesystem.model.FSTreeNode;
import org.eclipse.tcf.te.tcf.filesystem.nls.Messages;
import org.eclipse.tcf.te.ui.views.interfaces.handler.IDeleteHandlerDelegate;
import org.eclipse.ui.PlatformUI;
/**
* File System tree node delete handler delegate implementation.
*/
public class DeleteHandlerDelegate implements IDeleteHandlerDelegate, IConfirmCallback {
// The key to access the selection in the state.
private static final String KEY_SELECTION = "selection"; //$NON-NLS-1$
// The key to access the processed state in the state.
private static final String KEY_PROCESSED = "processed"; //$NON-NLS-1$
// The confirmation callback
private IConfirmCallback confirmCallback;
/**
* Constructor
*/
public DeleteHandlerDelegate() {
confirmCallback = this;
}
/**
* Set the confirmation callback
*
* @param confirmCallback The confirmation callback
*/
public void setConfirmCallback(IConfirmCallback confirmCallback) {
this.confirmCallback = confirmCallback;
}
/*
* (non-Javadoc)
* @see org.eclipse.tcf.te.ui.views.interfaces.handler.IDeleteHandlerDelegate#canDelete(java.lang.Object)
*/
@Override
public boolean canDelete(Object element) {
if (element instanceof FSTreeNode) {
FSTreeNode node = (FSTreeNode) element;
if (!node.isSystemRoot() && !node.isRoot()) {
return node.isWindowsNode() && !node.isReadOnly()
|| !node.isWindowsNode() && node.isWritable();
}
}
return false;
}
/*
* (non-Javadoc)
* @see org.eclipse.tcf.te.ui.views.interfaces.handler.IDeleteHandlerDelegate#delete(java.lang.Object, org.eclipse.tcf.te.runtime.interfaces.properties.IPropertiesContainer, org.eclipse.tcf.te.runtime.interfaces.callback.ICallback)
*/
@Override
public void delete(Object element, IPropertiesContainer state, ICallback callback) {
Assert.isNotNull(element);
Assert.isNotNull(state);
UUID lastProcessed = (UUID) state.getProperty(KEY_PROCESSED);
if (lastProcessed == null || !lastProcessed.equals(state.getUUID())) {
state.setProperty(KEY_PROCESSED, state.getUUID());
if(confirmCallback != null) {
IStructuredSelection selection = (IStructuredSelection) state.getProperty(KEY_SELECTION);
- if(confirmCallback.requires(selection) && confirmCallback.confirms(selection) == IConfirmCallback.YES) {
+ if(!confirmCallback.requires(selection) || confirmCallback.confirms(selection) == IConfirmCallback.YES) {
List<FSTreeNode> nodes = selection.toList();
FSDelete delete = new FSDelete(nodes);
delete.doit();
}
}
}
if (callback != null) callback.done(this, Status.OK_STATUS);
}
/*
*
*/
@Override
public boolean requires(Object object) {
return true;
}
/*
* (non-Javadoc)
* @see org.eclipse.tcf.te.tcf.filesystem.interfaces.IConfirmCallback#confirms(java.lang.Object)
*/
@Override
public int confirms(Object object) {
IStructuredSelection selection = (IStructuredSelection) object;
List<FSTreeNode> nodes = selection.toList();
String question;
if (nodes.size() == 1) {
FSTreeNode node = nodes.get(0);
question = NLS.bind(Messages.DeleteFilesHandler_DeleteOneFileConfirmation, node.name);
}
else {
question = NLS.bind(Messages.DeleteFilesHandler_DeleteMultipleFilesConfirmation, Integer.valueOf(nodes.size()));
}
Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
if (MessageDialog.openQuestion(parent, Messages.DeleteFilesHandler_ConfirmDialogTitle, question)) {
return IConfirmCallback.YES;
}
return IConfirmCallback.NO;
}
}
| true | true | public void delete(Object element, IPropertiesContainer state, ICallback callback) {
Assert.isNotNull(element);
Assert.isNotNull(state);
UUID lastProcessed = (UUID) state.getProperty(KEY_PROCESSED);
if (lastProcessed == null || !lastProcessed.equals(state.getUUID())) {
state.setProperty(KEY_PROCESSED, state.getUUID());
if(confirmCallback != null) {
IStructuredSelection selection = (IStructuredSelection) state.getProperty(KEY_SELECTION);
if(confirmCallback.requires(selection) && confirmCallback.confirms(selection) == IConfirmCallback.YES) {
List<FSTreeNode> nodes = selection.toList();
FSDelete delete = new FSDelete(nodes);
delete.doit();
}
}
}
if (callback != null) callback.done(this, Status.OK_STATUS);
}
| public void delete(Object element, IPropertiesContainer state, ICallback callback) {
Assert.isNotNull(element);
Assert.isNotNull(state);
UUID lastProcessed = (UUID) state.getProperty(KEY_PROCESSED);
if (lastProcessed == null || !lastProcessed.equals(state.getUUID())) {
state.setProperty(KEY_PROCESSED, state.getUUID());
if(confirmCallback != null) {
IStructuredSelection selection = (IStructuredSelection) state.getProperty(KEY_SELECTION);
if(!confirmCallback.requires(selection) || confirmCallback.confirms(selection) == IConfirmCallback.YES) {
List<FSTreeNode> nodes = selection.toList();
FSDelete delete = new FSDelete(nodes);
delete.doit();
}
}
}
if (callback != null) callback.done(this, Status.OK_STATUS);
}
|
diff --git a/javafx/money-fxdemo/src/main/java/net/java/javamoney/fxsample/core/CalculateAmounts.java b/javafx/money-fxdemo/src/main/java/net/java/javamoney/fxsample/core/CalculateAmounts.java
index 5f79a5e..cb7bc36 100644
--- a/javafx/money-fxdemo/src/main/java/net/java/javamoney/fxsample/core/CalculateAmounts.java
+++ b/javafx/money-fxdemo/src/main/java/net/java/javamoney/fxsample/core/CalculateAmounts.java
@@ -1,124 +1,124 @@
package net.java.javamoney.fxsample.core;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import javafx.event.ActionEvent;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javax.money.MonetaryAmount;
import net.java.javamoney.fxsample.widgets.AbstractExamplePane;
import net.java.javamoney.fxsample.widgets.AbstractSingleSamplePane;
import net.java.javamoney.fxsample.widgets.AmountEntry;
public class CalculateAmounts extends AbstractExamplePane {
public CalculateAmounts() {
super(new ExamplePane());
setExampleTitle("Monetary Amounts Arithmethics");
setExampleDescription("This example shows how to perform arithemtic operations on monmetary amounts.");
setExampleCode(loadExample("/samples/AmountArithmetics.javatxt"));
}
public final static class ExamplePane extends AbstractSingleSamplePane {
private HBox exPane = new HBox();
private AmountEntry amount1Pane = new AmountEntry("First Amount");
private AmountEntry amount2Pane = new AmountEntry("Second Amount");
private Label operationLabel = new Label("Operation to be performed:");
private ChoiceBox operationChoice = new ChoiceBox();
private CheckBox addResultToAmount1 = new CheckBox(
"Set result to Amount 1.");
public ExamplePane() {
exPane.getChildren().add(amount1Pane);
exPane.getChildren().add(amount2Pane);
VBox amountBox = new VBox();
amountBox.getChildren().addAll(amount1Pane,
amount2Pane);
VBox opBox = new VBox();
opBox.getChildren().addAll(new Label("Operation"), operationChoice,
addResultToAmount1);
exPane.getChildren().addAll(amountBox, opBox);
this.inputPane.getChildren().add(exPane);
AnchorPane.setLeftAnchor(inputPane, 10d);
AnchorPane.setTopAnchor(inputPane, 10d);
operationChoice.getItems().addAll("add", "subtract", "multiply",
"divide", "divideToIntegralValue", "max", "min",
"remainder");
Button actionButton = new Button("Perform");
actionButton
.setOnAction(new javafx.event.EventHandler<ActionEvent>() {
public void handle(ActionEvent action) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
StringBuilder builder = new StringBuilder();
try {
MonetaryAmount amount1 = amount1Pane
.getAmount();
MonetaryAmount amount2 = amount2Pane
.getAmount();
MonetaryAmount amountResult = performOperation(
amount1, amount2,
(String) operationChoice
.getSelectionModel()
.getSelectedItem());
if (addResultToAmount1.isSelected()) {
amount1Pane.setAmount(amountResult);
}
pw.println("MonetaryAmount");
pw.println("--------------");
pw.println();
printSummary(amountResult, pw);
} catch (Exception e) {
e.printStackTrace(pw);
}
pw.flush();
ExamplePane.this.outputArea.setText(sw.toString());
}
private MonetaryAmount performOperation(
MonetaryAmount amount1, MonetaryAmount amount2,
String operation) {
if ("add".equals(operation)) {
return amount1.add(amount2);
} else if ("subtract".equals(operation)) {
return amount1.subtract(amount2);
} else if ("multiply".equals(operation)) {
return amount1.multiply(amount2);
} else if ("divide".equals(operation)) {
return amount1.divide(amount2);
} else if ("divideToIntegralValue"
.equals(operation)) {
return amount1.divideToIntegralValue(amount2);
- } else if ("max".equals(operation)) {
- return amount1.max(amount2);
- } else if ("min".equals(operation)) {
- return amount1.min(amount2);
+// } else if ("max".equals(operation)) {
+// return amount1.max(amount2);
+// } else if ("min".equals(operation)) {
+// return amount1.min(amount2);
} else if ("remainder".equals(operation)) {
return amount1.remainder(amount2);
}
return null;
}
private void printSummary(MonetaryAmount amount,
PrintWriter pw) {
pw.println("Class: " + amount.getClass().getName());
pw.println("Value (BD): "
+ amount.asType(BigDecimal.class));
pw.println("Precision: " + amount.getPrecision());
pw.println("Scale: " + amount.getScale());
}
});
buttonPane.getChildren().add(actionButton);
}
}
}
| true | true | public ExamplePane() {
exPane.getChildren().add(amount1Pane);
exPane.getChildren().add(amount2Pane);
VBox amountBox = new VBox();
amountBox.getChildren().addAll(amount1Pane,
amount2Pane);
VBox opBox = new VBox();
opBox.getChildren().addAll(new Label("Operation"), operationChoice,
addResultToAmount1);
exPane.getChildren().addAll(amountBox, opBox);
this.inputPane.getChildren().add(exPane);
AnchorPane.setLeftAnchor(inputPane, 10d);
AnchorPane.setTopAnchor(inputPane, 10d);
operationChoice.getItems().addAll("add", "subtract", "multiply",
"divide", "divideToIntegralValue", "max", "min",
"remainder");
Button actionButton = new Button("Perform");
actionButton
.setOnAction(new javafx.event.EventHandler<ActionEvent>() {
public void handle(ActionEvent action) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
StringBuilder builder = new StringBuilder();
try {
MonetaryAmount amount1 = amount1Pane
.getAmount();
MonetaryAmount amount2 = amount2Pane
.getAmount();
MonetaryAmount amountResult = performOperation(
amount1, amount2,
(String) operationChoice
.getSelectionModel()
.getSelectedItem());
if (addResultToAmount1.isSelected()) {
amount1Pane.setAmount(amountResult);
}
pw.println("MonetaryAmount");
pw.println("--------------");
pw.println();
printSummary(amountResult, pw);
} catch (Exception e) {
e.printStackTrace(pw);
}
pw.flush();
ExamplePane.this.outputArea.setText(sw.toString());
}
private MonetaryAmount performOperation(
MonetaryAmount amount1, MonetaryAmount amount2,
String operation) {
if ("add".equals(operation)) {
return amount1.add(amount2);
} else if ("subtract".equals(operation)) {
return amount1.subtract(amount2);
} else if ("multiply".equals(operation)) {
return amount1.multiply(amount2);
} else if ("divide".equals(operation)) {
return amount1.divide(amount2);
} else if ("divideToIntegralValue"
.equals(operation)) {
return amount1.divideToIntegralValue(amount2);
} else if ("max".equals(operation)) {
return amount1.max(amount2);
} else if ("min".equals(operation)) {
return amount1.min(amount2);
} else if ("remainder".equals(operation)) {
return amount1.remainder(amount2);
}
return null;
}
private void printSummary(MonetaryAmount amount,
PrintWriter pw) {
pw.println("Class: " + amount.getClass().getName());
pw.println("Value (BD): "
+ amount.asType(BigDecimal.class));
pw.println("Precision: " + amount.getPrecision());
pw.println("Scale: " + amount.getScale());
}
});
buttonPane.getChildren().add(actionButton);
}
| public ExamplePane() {
exPane.getChildren().add(amount1Pane);
exPane.getChildren().add(amount2Pane);
VBox amountBox = new VBox();
amountBox.getChildren().addAll(amount1Pane,
amount2Pane);
VBox opBox = new VBox();
opBox.getChildren().addAll(new Label("Operation"), operationChoice,
addResultToAmount1);
exPane.getChildren().addAll(amountBox, opBox);
this.inputPane.getChildren().add(exPane);
AnchorPane.setLeftAnchor(inputPane, 10d);
AnchorPane.setTopAnchor(inputPane, 10d);
operationChoice.getItems().addAll("add", "subtract", "multiply",
"divide", "divideToIntegralValue", "max", "min",
"remainder");
Button actionButton = new Button("Perform");
actionButton
.setOnAction(new javafx.event.EventHandler<ActionEvent>() {
public void handle(ActionEvent action) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
StringBuilder builder = new StringBuilder();
try {
MonetaryAmount amount1 = amount1Pane
.getAmount();
MonetaryAmount amount2 = amount2Pane
.getAmount();
MonetaryAmount amountResult = performOperation(
amount1, amount2,
(String) operationChoice
.getSelectionModel()
.getSelectedItem());
if (addResultToAmount1.isSelected()) {
amount1Pane.setAmount(amountResult);
}
pw.println("MonetaryAmount");
pw.println("--------------");
pw.println();
printSummary(amountResult, pw);
} catch (Exception e) {
e.printStackTrace(pw);
}
pw.flush();
ExamplePane.this.outputArea.setText(sw.toString());
}
private MonetaryAmount performOperation(
MonetaryAmount amount1, MonetaryAmount amount2,
String operation) {
if ("add".equals(operation)) {
return amount1.add(amount2);
} else if ("subtract".equals(operation)) {
return amount1.subtract(amount2);
} else if ("multiply".equals(operation)) {
return amount1.multiply(amount2);
} else if ("divide".equals(operation)) {
return amount1.divide(amount2);
} else if ("divideToIntegralValue"
.equals(operation)) {
return amount1.divideToIntegralValue(amount2);
// } else if ("max".equals(operation)) {
// return amount1.max(amount2);
// } else if ("min".equals(operation)) {
// return amount1.min(amount2);
} else if ("remainder".equals(operation)) {
return amount1.remainder(amount2);
}
return null;
}
private void printSummary(MonetaryAmount amount,
PrintWriter pw) {
pw.println("Class: " + amount.getClass().getName());
pw.println("Value (BD): "
+ amount.asType(BigDecimal.class));
pw.println("Precision: " + amount.getPrecision());
pw.println("Scale: " + amount.getScale());
}
});
buttonPane.getChildren().add(actionButton);
}
|
diff --git a/apps/ibis/cell1d/OpenCell1D.java b/apps/ibis/cell1d/OpenCell1D.java
index ac69741f..270a9836 100644
--- a/apps/ibis/cell1d/OpenCell1D.java
+++ b/apps/ibis/cell1d/OpenCell1D.java
@@ -1,801 +1,795 @@
// File: $Id$
import ibis.ipl.*;
import java.util.Properties;
import java.util.Random;
import java.io.IOException;
interface OpenConfig {
static final boolean tracePortCreation = false;
static final boolean traceCommunication = false;
static final boolean showProgress = true;
static final boolean showBoard = false;
static final boolean traceClusterResizing = false;
static final boolean traceLoadBalancing = true;
static final int DEFAULTBOARDSIZE = 4000;
static final int GENERATIONS = 30;
static final int SHOWNBOARDWIDTH = 60;
static final int SHOWNBOARDHEIGHT = 30;
}
final class Problem implements OpenConfig {
public byte leftBorder[];
public byte board[][];
public byte rightBorder[];
public int firstColumn = -1;
public int firstNoColumn = -1;
// We need two extra column arrays to temporarily store the update
// of a column. These arrays will be circulated with our columns of
// the board.
public byte updatecol[];
public byte nextupdatecol[];
public Problem( int boardsize, int firstCol, int firstNoCol )
{
// We allocate one column extra to allow a more efficient computational
// loop. The last element will always be null, though.
board = new byte[boardsize+1][];
updatecol = new byte[boardsize+2];
nextupdatecol = new byte[boardsize+2];
firstColumn = firstCol;
firstNoColumn = firstNoCol;
// Now populate the columns that are our responsibility,
for( int col=firstCol; col<firstNoCol; col++ ){
board[col] = new byte[boardsize+2];
}
// And two border columns.
leftBorder = new byte[boardsize+2];
rightBorder = new byte[boardsize+2];
}
}
class RszHandler implements OpenConfig, ResizeHandler {
private int members = 0;
private IbisIdentifier prev = null;
public void join( IbisIdentifier id )
{
if( traceClusterResizing ){
System.out.println( "Machine " + id.name() + " joins the computation" );
}
if( id.equals( OpenCell1D.ibis.identifier() ) ){
// Hey! That's me. Now I know my member number and my left
// neighbour.
OpenCell1D.leftNeighbour = prev;
if( traceClusterResizing ){
String who = "no";
if( OpenCell1D.leftNeighbour != null ){
who = OpenCell1D.leftNeighbour.name() + " as";
}
System.out.println( "P" + members + ": that's me! I have " + who + " left neighbour" );
}
OpenCell1D.me = members;
}
else if( prev != null && prev.equals( OpenCell1D.ibis.identifier() ) ){
// The next one after me. Now I know my right neighbour.
OpenCell1D.rightNeighbour = id;
if( traceClusterResizing ){
System.out.println( "P" + OpenCell1D.me + ": that's my right neighbour" );
}
}
members++;
prev = id;
}
public void leave( IbisIdentifier id )
{
if( traceClusterResizing ){
System.out.println( "Machine " + id.name() + " leaves the computation" );
}
members--;
}
public void delete( IbisIdentifier id )
{
if( traceClusterResizing ){
System.out.println( "Machine " + id.name() + " is deleted from the computation" );
}
members--;
}
public void reconfigure()
{
if( traceClusterResizing ){
System.out.println( "Cluster is reconfigured" );
}
}
public synchronized int getMemberCount()
{
return members;
}
}
class OpenCell1D implements OpenConfig {
static Ibis ibis;
static Registry registry;
static IbisIdentifier leftNeighbour;
static IbisIdentifier rightNeighbour;
static IbisIdentifier myName;
static int me = -1;
static SendPort leftSendPort;
static SendPort rightSendPort;
static ReceivePort leftReceivePort;
static ReceivePort rightReceivePort;
static int generation = 0;
static int boardsize = DEFAULTBOARDSIZE;
private static void usage()
{
System.out.println( "Usage: OpenCell1D [-size <int>] [count]" );
System.exit( 0 );
}
/**
* Creates an update send port that connected to the specified neighbour.
* @param updatePort The type of the port to construct.
* @param dest The destination processor.
* @param prefix The prefix of the port names.
*/
private static SendPort createNeighbourSendPort( PortType updatePort, IbisIdentifier dest, String prefix )
throws java.io.IOException
{
String sendportname = prefix + "Send" + myName.name();
String receiveportname = prefix + "Receive" + dest.name();
SendPort res = updatePort.createSendPort( sendportname );
if( tracePortCreation ){
System.out.println( "P" + me + ": created send port " + res );
}
ReceivePortIdentifier id = registry.lookup( receiveportname );
res.connect( id );
if( tracePortCreation ){
System.out.println( "P" + me + ": connected " + sendportname + " to " + receiveportname );
}
return res;
}
/**
* Creates an update receive port.
* @param updatePort The type of the port to construct.
* @param prefix The prefix of the port names.
*/
private static ReceivePort createNeighbourReceivePort( PortType updatePort, String prefix )
throws java.io.IOException
{
String receiveportname = prefix + "Receive" + myName.name();
ReceivePort res = updatePort.createReceivePort( receiveportname );
if( tracePortCreation ){
System.out.println( "P" + me + ": created receive port " + res );
}
res.enableConnections();
return res;
}
private static byte horTwister[][] = {
{ 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 0 },
{ 0, 0, 0, 0, 0 },
};
private static byte vertTwister[][] = {
{ 0, 0, 0 },
{ 0, 1, 0 },
{ 0, 1, 0 },
{ 0, 1, 0 },
{ 0, 0, 0 },
};
private static byte horTril[][] = {
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0 },
{ 0, 1, 0, 0, 1, 0 },
{ 0, 0, 1, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 0 },
};
private static byte vertTril[][] = {
{ 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 1, 0, 1, 0 },
{ 0, 1, 0, 1, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0 },
};
private static byte glider[][] = {
{ 0, 0, 0, 0, 0 },
{ 0, 1, 1, 1, 0 },
{ 0, 1, 0, 0, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0 },
};
/**
* Puts the given pattern at the given coordinates.
* Since we want the pattern to be readable, we take the first
* row of the pattern to be the at the top.
*/
static protected void putPattern( Problem p, int px, int py, byte pat[][] )
{
for( int y=pat.length-1; y>=0; y-- ){
byte paty[] = pat[y];
for( int x=0; x<paty.length; x++ ){
if( p.board[px+x] != null ){
p.board[px+x][py+y] = paty[x];
}
}
}
}
/**
* Returns true iff the given pattern occurs at the given
* coordinates.
*/
static protected boolean hasPattern( Problem p, int px, int py, byte pat[][ ] )
{
for( int y=pat.length-1; y>=0; y-- ){
byte paty[] = pat[y];
for( int x=0; x<paty.length; x++ ){
if( p.board[px+x] != null && p.board[px+x][py+y] != paty[x] ){
return false;
}
}
}
return true;
}
// Put a twister (a bar of 3 cells) at the given center cell.
static protected void putTwister( Problem p, int x, int y )
{
putPattern( p, x-2, y-1, horTwister );
}
// Given a position, return true iff there is a twister in hor or
// vertical position at that point.
static protected boolean hasTwister( Problem p, int x, int y )
{
return hasPattern( p, x-2, y-1, horTwister ) ||
hasPattern( p, x-1, y-2, vertTwister );
}
/**
* Sends a new border to the lefthand neighbour. For load balancing
* purposes, perhaps also send some of the columns I own to that
* neighbour.
* @param port The port to send to.
* @param p The problem.
* @param aimFirstColomn The first column we should own.
* @param aimFirstNoColomn The first column we should not own.
*/
static void sendLeft( SendPort port, Problem p, int aimFirstColumn, int aimFirstNoColumn )
throws java.io.IOException
{
if( port == null ){
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": there is no left neighbour to send to" );
}
return;
}
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": sending to P" + (me-1) + ": " + port );
}
if( p.firstColumn == 0 ){
System.err.println( "ERROR: I have a left neighbour, but my first column is 0???" );
System.exit( 1 );
}
int sendCount;
if( p.firstColumn<boardsize ){
sendCount = aimFirstColumn-p.firstColumn;
if( sendCount<0 ){
sendCount = 0;
}
}
else {
sendCount = 0;
}
if( sendCount>0 ){
if( traceLoadBalancing ){
System.out.println( "P" + me + ":" + generation + ": sending " + sendCount + " columns to P" + (me+1) );
}
// The border has changed, but since until now we maintained it,
// we can record its current state from our own columns.
System.arraycopy( p.board[aimFirstColumn-1], 0, p.leftBorder, 0, boardsize+2 );
}
WriteMessage m = port.newMessage();
m.writeInt( generation );
m.writeInt( sendCount );
// Send the columns we want to move to the border.
while( sendCount>0 ){
int ix = p.firstColumn;
byte buf[] = p.board[ix];
if( buf == null ){
// This shouldn't happen, but make the best of it.
System.out.println( "ERROR: P" + me + ":" + generation + ": cannot send null column " + ix + " to P" + (me-1) + "; sending a dummy instead" );
buf = p.leftBorder;
}
m.writeInt( ix );
m.writeArray( buf );
p.board[ix] = null;
p.firstColumn++;
sendCount--;
}
// ... and always send our first column as border to
// the neighbour.
m.writeInt( p.firstColumn );
if( p.firstColumn<p.firstNoColumn ){
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": sending border column " + p.firstColumn + " to P" + (me-1) );
}
m.writeArray( p.board[p.firstColumn] );
}
else {
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": there is no border column to send to P" + (me-1) );
}
}
m.send();
m.finish();
}
/**
* Sends a new border to the righthand neighbour. For load balancing
* purposes, perhaps also send some of the columns I own to that
* neighbour.
* @param port The port to send to.
* @param p The problem.
* @param aimFirstColomn The first column we should own.
* @param aimFirstNoColomn The first column we should not own.
*/
static void sendRight( SendPort port, Problem p, int aimFirstColumn, int aimFirstNoColumn )
throws java.io.IOException
{
if( port == null ){
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": there is no right neighbour to send to" );
}
return;
}
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": sending to P" + (me+1) +": " + port );
}
int sendCount;
if( p.firstColumn<boardsize ){
sendCount = p.firstNoColumn-aimFirstNoColumn;
if( sendCount<0 ){
sendCount = 0;
}
}
else {
sendCount = 0;
}
if( sendCount>0 ){
if( traceLoadBalancing ){
System.out.println( "P" + me + ":" + generation + ": sending " + sendCount + " columns to P" + (me+1) );
}
// The border has changed, but since until now we
// maintained it as an ordinary column, we can easily intialize
// it.
System.arraycopy( p.board[aimFirstNoColumn], 0, p.rightBorder, 0, boardsize+2 );
}
WriteMessage m = port.newMessage();
m.writeInt( generation );
m.writeInt( sendCount );
// Send the columns we want to move from right to left.
while( sendCount>0 ){
int ix = p.firstNoColumn-1;
byte buf[] = p.board[ix];
if( buf == null ){
// This shouldn't happen, but make the best of it.
System.out.println( "ERROR: P" + me + ":" + generation + ": cannot send null column " + ix + " to P" + (me+1) + "; sending a dummy instead" );
buf = p.leftBorder;
}
m.writeInt( ix );
m.writeArray( buf );
p.board[ix] = null;
p.firstNoColumn--;
sendCount--;
}
// TODO: make sure that all this shrinking doesn't leave us with
// an empty set, unless all our right neighbours are also
// empty.
// ... and always send our first column as border to the neighbour.
if( p.firstColumn<p.firstNoColumn ){
int ix = p.firstNoColumn-1;
m.writeInt( ix );
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": sending border column " + ix + " to P" + (me+1) );
}
byte buf[] = p.board[ix];
if( buf == null ){
System.out.println( "ERROR: P" + me + ":" + generation + ": cannot send right border column " + ix + " since it is null; sending a dummy" );
buf = p.rightBorder;
}
m.writeArray( buf );
}
else {
// We don't have columns, so no border columns either. Tell
// that to the opposite side.
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": there is no border column to send to P" + (me+1) );
}
m.writeInt( boardsize );
}
m.send();
m.finish();
}
static void receiveLeft( ReceivePort port, Problem p )
throws java.io.IOException
{
int colno;
if( port == null ){
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": there is no left neighbour to receive from" );
}
return;
}
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": receiving from P" + (me-1) + ": " + port );
}
ReadMessage m = port.receive();
int gen = m.readInt();
if( gen>=0 && OpenCell1D.generation<0 ){
OpenCell1D.generation = gen;
}
int receiveCount = m.readInt();
if( receiveCount>0 ){
if( traceLoadBalancing ){
System.out.println( "P" + me + ":" + generation + ": receiving " + receiveCount + " columns from P" + (me-1) );
}
int newFirst = p.firstColumn;
int newLast = -1;
for( int i=0; i<receiveCount; i++ ){
colno = m.readInt();
if( colno>=p.firstColumn && colno<p.firstNoColumn ){
System.out.println( "ERROR: P" + me + ": left neighbour P" + (me-1) + " sent column " + colno + ", but that is in my range" );
}
else if( p.board[colno] != null ){
System.out.println( "ERROR: P" + me + ": left neighbour P" + (me-1) + " sent column " + colno + ", but I already have a column there (although it is not in my range)" );
}
byte buf[] = new byte[boardsize+2];
m.readArray( buf );
p.board[colno] = buf;
if( colno<newFirst ){
newFirst = colno;
}
if( colno>newLast ){
newLast = colno;
}
}
if( p.firstColumn>=boardsize ){
p.firstNoColumn = newLast+1;
}
else {
if( (newLast+1)<p.firstNoColumn ){
System.out.println( "ERROR: P" + me + ": left neighbour P" + (me-1) + " sent columns " + newFirst + "-" + (newLast+1) + " but that leaves a gap to my columns " + p.firstColumn + "-" + p.firstNoColumn );
}
}
p.firstColumn = newFirst;
}
colno = m.readInt();
if( colno<boardsize ){
// TODO: check that the column number is the one we expect.
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": receiving border column " + colno + " from P" + (me-1) );
}
m.readArray( p.leftBorder );
}
else {
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": P" + (me-1) + " doesn't have a border column to send" );
}
}
m.finish();
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": completed receiving from P" + (me-1) );
}
}
static void receiveRight( ReceivePort port, Problem p )
throws java.io.IOException
{
int colno;
if( port == null ){
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": there is no right neighbour to receive from" );
}
return;
}
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": receiving from P" + (me+1) + ": " + port );
}
ReadMessage m = port.receive();
int gen = m.readInt();
if( gen>=0 && OpenCell1D.generation<0 ){
OpenCell1D.generation = gen;
}
int receiveCount = m.readInt();
if( receiveCount>0 ){
if( traceLoadBalancing ){
System.out.println( "P" + me + ": receiving " + receiveCount + " columns from P" + (me+1) );
}
}
p.firstNoColumn += receiveCount;
int ix = p.firstNoColumn;
for( int i=0; i<receiveCount; i++ ){
ix--;
if( p.board[ix] == null ){
p.board[ix] = new byte[boardsize+2];
}
else {
System.out.println( "P" + me + ":" + generation + ": column " + ix + " is not in my posession, but is not null" );
}
colno = m.readInt();
if( colno != ix ){
System.out.println( "ERROR: P" + me +":" + generation + ": P" + (me+1) + " sent me column " + colno + ", but I need column " + ix );
}
m.readArray( p.board[ix] );
}
colno = m.readInt();
if( colno<boardsize ){
// TODO: check that the column number is the one we expect.
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": receiving border column " + colno + " from P" + (me+1) );
}
m.readArray( p.rightBorder );
}
else {
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": P" + (me+1) + " doesn't have a border column to send" );
}
}
m.finish();
if( traceCommunication ){
System.out.println( "P" + me + ":" + generation + ": completed receiving from P" + (me+1) );
}
}
static void computeNextGeneration( Problem p )
{
if( p.firstColumn<p.firstNoColumn ){
byte prev[];
byte curr[] = p.leftBorder;
byte next[] = p.board[p.firstColumn];
if( showBoard && leftNeighbour == null ){
System.out.println( "Generation " + generation );
for( int y=0; y<SHOWNBOARDHEIGHT; y++ ){
for( int x=1; x<SHOWNBOARDWIDTH; x++ ){
System.out.print( p.board[x][y] );
}
System.out.println();
}
}
for( int i=p.firstColumn; i<p.firstNoColumn; i++ ){
prev = curr;
curr = next;
next = p.board[i+1];
if( next == null ){
// No column there. We blindly assume that
// that means we must use the right border.
next = p.rightBorder;
}
for( int j=1; j<=boardsize; j++ ){
int neighbours =
prev[j-1] +
prev[j] +
prev[j+1] +
curr[j-1] +
curr[j+1] +
next[j-1] +
next[j] +
next[j+1];
boolean alive = (neighbours == 3) || ((neighbours == 2) && (curr[j]==1));
p.updatecol[j] = alive?(byte) 1:(byte) 0;
}
//
byte tmp[] = p.board[i];
p.board[i] = p.updatecol;
p.updatecol = p.nextupdatecol;
p.nextupdatecol = tmp;
}
}
}
public static void main( String [] args )
{
int count = GENERATIONS;
RszHandler rszHandler = new RszHandler();
int knownMembers = 0;
/** The first column that is my responsibility. */
int firstColumn = -1;
/** The first column that is no longer my responsibility. */
int firstNoColumn = -1;
/* Parse commandline parameters. */
for( int i=0; i<args.length; i++ ){
if( args[i].equals( "-size" ) ){
i++;
boardsize = Integer.parseInt( args[i] );
}
else {
- if( count == -1 ){
- count = Integer.parseInt( args[i] );
- }
- else {
- System.out.println( "Bad generation count `" + args[i] + "'" );
- usage();
- }
+ count = Integer.parseInt( args[i] );
}
}
try {
long startTime = System.currentTimeMillis();
StaticProperties s = new StaticProperties();
s.add( "serialization", "data" );
s.add( "communication", "OneToOne, Reliable, AutoUpcalls, ExplicitReceipt" );
s.add( "worldmodel", "open" );
ibis = Ibis.createIbis( s, rszHandler );
myName = ibis.identifier();
ibis.openWorld();
registry = ibis.registry();
// TODO: be more precise about the properties for the two
// port types.
PortType updatePort = ibis.createPortType( "neighbour update", s );
PortType loadbalancePort = ibis.createPortType( "loadbalance", s );
leftSendPort = null;
rightSendPort = null;
leftReceivePort = null;
rightReceivePort = null;
// Wait until I know my processor number (and also
// my left neighbour).
// TODO: use a more subtle approach than this.
while( me<0 ){
Thread.sleep( 20 );
}
if( me != 0 && leftNeighbour == null ){
System.out.println( "P" + me + ": there is no left neighbour???" );
}
if( leftNeighbour != null ){
leftReceivePort = createNeighbourReceivePort( updatePort, "upstream" );
leftSendPort = createNeighbourSendPort( updatePort, leftNeighbour, "downstream" );
}
if( leftNeighbour == null ){
// I'm the leftmost node, I start with the entire board.
// Workstealing will spread the load to other processors later
// on.
firstColumn = 0;
firstNoColumn = boardsize;
generation = 0; // I decide the generation count.
knownMembers = 1;
}
else {
firstColumn = boardsize;
firstNoColumn = boardsize;
}
if( me == 0 ){
System.out.println( "Started" );
}
// For the moment we're satisfied with the work distribution.
int aimFirstColumn = firstColumn;
int aimFirstNoColumn = firstNoColumn;
// First, create an array to hold all columns of the total
// array size, plus two empty dummy border columns. (The top and
// bottom *rows* are also empty dummies that are never updated).
Problem p = new Problem( boardsize, firstColumn, firstNoColumn );
// Put a few fixed objects on the board to do a sanity check.
putTwister( p, 100, 3 );
putPattern( p, 4, 4, glider );
while( generation<count ){
computeNextGeneration( p );
if( rightNeighbour != null ){
if( rightReceivePort == null ){
// We now have a right neightbour. Set up communication
// with it.
if( tracePortCreation ){
System.out.println( "P" + me + ": a right neighbour has appeared; creating ports" );
}
rightReceivePort = createNeighbourReceivePort( updatePort, "downstream" );
rightSendPort = createNeighbourSendPort( updatePort, rightNeighbour, "upstream" );
}
}
int members = rszHandler.getMemberCount();
if( knownMembers<members ){
// Some processors have joined the computation.
// Redistribute the load.
// For an equal division of the load, I should get...
aimFirstColumn = (me*boardsize)/members;
aimFirstNoColumn = ((me+1)*boardsize)/members;
if( traceLoadBalancing ){
System.out.println( "P" + me + ": there are now " + members + " nodes in the computation (was " + knownMembers + ")" );
System.out.println( "P" + me + ": I have columns " + p.firstColumn + "-" + p.firstNoColumn + ", I should have " + aimFirstColumn + "-" + aimFirstNoColumn );
}
knownMembers = members;
}
if( (me % 2) == 0 ){
sendLeft( leftSendPort, p, aimFirstColumn, aimFirstNoColumn );
sendRight( rightSendPort, p, aimFirstColumn, aimFirstNoColumn );
receiveLeft( leftReceivePort, p );
receiveRight( rightReceivePort, p );
}
else {
receiveRight( rightReceivePort, p );
receiveLeft( leftReceivePort, p );
sendRight( rightSendPort, p, aimFirstColumn, aimFirstNoColumn );
sendLeft( leftSendPort, p, aimFirstColumn, aimFirstNoColumn );
}
if( showProgress && me == 0 ){
System.out.print( '.' );
}
generation++;
}
if( showProgress && me == 0 ){
System.out.println();
}
// Do a sanity check.
if( !hasTwister( p, 100, 3 ) ){
System.out.println( "Twister has gone missing" );
}
// TODO: also do a sanity check on the other pattern we
// put on the board.
if( me == 0 ){
long endTime = System.currentTimeMillis();
double time = ((double) (endTime - startTime))/1000.0;
long updates = boardsize*boardsize*(long) count;
System.out.println( "ExecutionTime: " + time );
System.out.println( "Did " + updates + " updates" );
}
ibis.end();
}
catch( Exception e ) {
System.out.println( "Got exception " + e );
System.out.println( "StackTrace:" );
e.printStackTrace();
}
}
}
| true | true | public static void main( String [] args )
{
int count = GENERATIONS;
RszHandler rszHandler = new RszHandler();
int knownMembers = 0;
/** The first column that is my responsibility. */
int firstColumn = -1;
/** The first column that is no longer my responsibility. */
int firstNoColumn = -1;
/* Parse commandline parameters. */
for( int i=0; i<args.length; i++ ){
if( args[i].equals( "-size" ) ){
i++;
boardsize = Integer.parseInt( args[i] );
}
else {
if( count == -1 ){
count = Integer.parseInt( args[i] );
}
else {
System.out.println( "Bad generation count `" + args[i] + "'" );
usage();
}
}
}
try {
long startTime = System.currentTimeMillis();
StaticProperties s = new StaticProperties();
s.add( "serialization", "data" );
s.add( "communication", "OneToOne, Reliable, AutoUpcalls, ExplicitReceipt" );
s.add( "worldmodel", "open" );
ibis = Ibis.createIbis( s, rszHandler );
myName = ibis.identifier();
ibis.openWorld();
registry = ibis.registry();
// TODO: be more precise about the properties for the two
// port types.
PortType updatePort = ibis.createPortType( "neighbour update", s );
PortType loadbalancePort = ibis.createPortType( "loadbalance", s );
leftSendPort = null;
rightSendPort = null;
leftReceivePort = null;
rightReceivePort = null;
// Wait until I know my processor number (and also
// my left neighbour).
// TODO: use a more subtle approach than this.
while( me<0 ){
Thread.sleep( 20 );
}
if( me != 0 && leftNeighbour == null ){
System.out.println( "P" + me + ": there is no left neighbour???" );
}
if( leftNeighbour != null ){
leftReceivePort = createNeighbourReceivePort( updatePort, "upstream" );
leftSendPort = createNeighbourSendPort( updatePort, leftNeighbour, "downstream" );
}
if( leftNeighbour == null ){
// I'm the leftmost node, I start with the entire board.
// Workstealing will spread the load to other processors later
// on.
firstColumn = 0;
firstNoColumn = boardsize;
generation = 0; // I decide the generation count.
knownMembers = 1;
}
else {
firstColumn = boardsize;
firstNoColumn = boardsize;
}
if( me == 0 ){
System.out.println( "Started" );
}
// For the moment we're satisfied with the work distribution.
int aimFirstColumn = firstColumn;
int aimFirstNoColumn = firstNoColumn;
// First, create an array to hold all columns of the total
// array size, plus two empty dummy border columns. (The top and
// bottom *rows* are also empty dummies that are never updated).
Problem p = new Problem( boardsize, firstColumn, firstNoColumn );
// Put a few fixed objects on the board to do a sanity check.
putTwister( p, 100, 3 );
putPattern( p, 4, 4, glider );
while( generation<count ){
computeNextGeneration( p );
if( rightNeighbour != null ){
if( rightReceivePort == null ){
// We now have a right neightbour. Set up communication
// with it.
if( tracePortCreation ){
System.out.println( "P" + me + ": a right neighbour has appeared; creating ports" );
}
rightReceivePort = createNeighbourReceivePort( updatePort, "downstream" );
rightSendPort = createNeighbourSendPort( updatePort, rightNeighbour, "upstream" );
}
}
int members = rszHandler.getMemberCount();
if( knownMembers<members ){
// Some processors have joined the computation.
// Redistribute the load.
// For an equal division of the load, I should get...
aimFirstColumn = (me*boardsize)/members;
aimFirstNoColumn = ((me+1)*boardsize)/members;
if( traceLoadBalancing ){
System.out.println( "P" + me + ": there are now " + members + " nodes in the computation (was " + knownMembers + ")" );
System.out.println( "P" + me + ": I have columns " + p.firstColumn + "-" + p.firstNoColumn + ", I should have " + aimFirstColumn + "-" + aimFirstNoColumn );
}
knownMembers = members;
}
if( (me % 2) == 0 ){
sendLeft( leftSendPort, p, aimFirstColumn, aimFirstNoColumn );
sendRight( rightSendPort, p, aimFirstColumn, aimFirstNoColumn );
receiveLeft( leftReceivePort, p );
receiveRight( rightReceivePort, p );
}
else {
receiveRight( rightReceivePort, p );
receiveLeft( leftReceivePort, p );
sendRight( rightSendPort, p, aimFirstColumn, aimFirstNoColumn );
sendLeft( leftSendPort, p, aimFirstColumn, aimFirstNoColumn );
}
if( showProgress && me == 0 ){
System.out.print( '.' );
}
generation++;
}
if( showProgress && me == 0 ){
System.out.println();
}
// Do a sanity check.
if( !hasTwister( p, 100, 3 ) ){
System.out.println( "Twister has gone missing" );
}
// TODO: also do a sanity check on the other pattern we
// put on the board.
if( me == 0 ){
long endTime = System.currentTimeMillis();
double time = ((double) (endTime - startTime))/1000.0;
long updates = boardsize*boardsize*(long) count;
System.out.println( "ExecutionTime: " + time );
System.out.println( "Did " + updates + " updates" );
}
ibis.end();
}
catch( Exception e ) {
System.out.println( "Got exception " + e );
System.out.println( "StackTrace:" );
e.printStackTrace();
}
}
| public static void main( String [] args )
{
int count = GENERATIONS;
RszHandler rszHandler = new RszHandler();
int knownMembers = 0;
/** The first column that is my responsibility. */
int firstColumn = -1;
/** The first column that is no longer my responsibility. */
int firstNoColumn = -1;
/* Parse commandline parameters. */
for( int i=0; i<args.length; i++ ){
if( args[i].equals( "-size" ) ){
i++;
boardsize = Integer.parseInt( args[i] );
}
else {
count = Integer.parseInt( args[i] );
}
}
try {
long startTime = System.currentTimeMillis();
StaticProperties s = new StaticProperties();
s.add( "serialization", "data" );
s.add( "communication", "OneToOne, Reliable, AutoUpcalls, ExplicitReceipt" );
s.add( "worldmodel", "open" );
ibis = Ibis.createIbis( s, rszHandler );
myName = ibis.identifier();
ibis.openWorld();
registry = ibis.registry();
// TODO: be more precise about the properties for the two
// port types.
PortType updatePort = ibis.createPortType( "neighbour update", s );
PortType loadbalancePort = ibis.createPortType( "loadbalance", s );
leftSendPort = null;
rightSendPort = null;
leftReceivePort = null;
rightReceivePort = null;
// Wait until I know my processor number (and also
// my left neighbour).
// TODO: use a more subtle approach than this.
while( me<0 ){
Thread.sleep( 20 );
}
if( me != 0 && leftNeighbour == null ){
System.out.println( "P" + me + ": there is no left neighbour???" );
}
if( leftNeighbour != null ){
leftReceivePort = createNeighbourReceivePort( updatePort, "upstream" );
leftSendPort = createNeighbourSendPort( updatePort, leftNeighbour, "downstream" );
}
if( leftNeighbour == null ){
// I'm the leftmost node, I start with the entire board.
// Workstealing will spread the load to other processors later
// on.
firstColumn = 0;
firstNoColumn = boardsize;
generation = 0; // I decide the generation count.
knownMembers = 1;
}
else {
firstColumn = boardsize;
firstNoColumn = boardsize;
}
if( me == 0 ){
System.out.println( "Started" );
}
// For the moment we're satisfied with the work distribution.
int aimFirstColumn = firstColumn;
int aimFirstNoColumn = firstNoColumn;
// First, create an array to hold all columns of the total
// array size, plus two empty dummy border columns. (The top and
// bottom *rows* are also empty dummies that are never updated).
Problem p = new Problem( boardsize, firstColumn, firstNoColumn );
// Put a few fixed objects on the board to do a sanity check.
putTwister( p, 100, 3 );
putPattern( p, 4, 4, glider );
while( generation<count ){
computeNextGeneration( p );
if( rightNeighbour != null ){
if( rightReceivePort == null ){
// We now have a right neightbour. Set up communication
// with it.
if( tracePortCreation ){
System.out.println( "P" + me + ": a right neighbour has appeared; creating ports" );
}
rightReceivePort = createNeighbourReceivePort( updatePort, "downstream" );
rightSendPort = createNeighbourSendPort( updatePort, rightNeighbour, "upstream" );
}
}
int members = rszHandler.getMemberCount();
if( knownMembers<members ){
// Some processors have joined the computation.
// Redistribute the load.
// For an equal division of the load, I should get...
aimFirstColumn = (me*boardsize)/members;
aimFirstNoColumn = ((me+1)*boardsize)/members;
if( traceLoadBalancing ){
System.out.println( "P" + me + ": there are now " + members + " nodes in the computation (was " + knownMembers + ")" );
System.out.println( "P" + me + ": I have columns " + p.firstColumn + "-" + p.firstNoColumn + ", I should have " + aimFirstColumn + "-" + aimFirstNoColumn );
}
knownMembers = members;
}
if( (me % 2) == 0 ){
sendLeft( leftSendPort, p, aimFirstColumn, aimFirstNoColumn );
sendRight( rightSendPort, p, aimFirstColumn, aimFirstNoColumn );
receiveLeft( leftReceivePort, p );
receiveRight( rightReceivePort, p );
}
else {
receiveRight( rightReceivePort, p );
receiveLeft( leftReceivePort, p );
sendRight( rightSendPort, p, aimFirstColumn, aimFirstNoColumn );
sendLeft( leftSendPort, p, aimFirstColumn, aimFirstNoColumn );
}
if( showProgress && me == 0 ){
System.out.print( '.' );
}
generation++;
}
if( showProgress && me == 0 ){
System.out.println();
}
// Do a sanity check.
if( !hasTwister( p, 100, 3 ) ){
System.out.println( "Twister has gone missing" );
}
// TODO: also do a sanity check on the other pattern we
// put on the board.
if( me == 0 ){
long endTime = System.currentTimeMillis();
double time = ((double) (endTime - startTime))/1000.0;
long updates = boardsize*boardsize*(long) count;
System.out.println( "ExecutionTime: " + time );
System.out.println( "Did " + updates + " updates" );
}
ibis.end();
}
catch( Exception e ) {
System.out.println( "Got exception " + e );
System.out.println( "StackTrace:" );
e.printStackTrace();
}
}
|
diff --git a/src/web/org/openmrs/web/taglib/ObsTableWidget.java b/src/web/org/openmrs/web/taglib/ObsTableWidget.java
index 843a3d15..999e2d15 100644
--- a/src/web/org/openmrs/web/taglib/ObsTableWidget.java
+++ b/src/web/org/openmrs/web/taglib/ObsTableWidget.java
@@ -1,435 +1,441 @@
/**
* The contents of this file are subject to the OpenMRS Public 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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.taglib;
import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.ConceptName;
import org.openmrs.Obs;
import org.openmrs.api.ConceptService;
import org.openmrs.api.context.Context;
public class ObsTableWidget extends TagSupport {
private static final long serialVersionUID = 14352344444L;
private final Log log = LogFactory.getLog(getClass());
/*
* pipe-separated list that could be:
* a concept id (e.g. "5089")
* a concept name (e.g. "name:CD4 COUNT")
* a concept set, by id or name (e.g. "set:5089" or "set.en:LAB TESTS")
*/
private String concepts;
private Collection<Obs> observations;
private boolean sortDescending = true;
private boolean orientVertical = true;
private Boolean showEmptyConcepts = true;
private Boolean showConceptHeader = true;
private Boolean showDateHeader = true;
private Boolean combineEqualResults = true;
private String id;
private String cssClass;
private Date fromDate;
private Date toDate;
private Integer limit = 0;
private String conceptLink = null;
//private String combineBy = "day";
public ObsTableWidget() {
}
public String getConcepts() {
return concepts;
}
public void setConcepts(String concepts) {
if (concepts == null || concepts.length() == 0)
return;
this.concepts = concepts;
}
public String getConceptLink() {
return conceptLink;
}
public void setConceptLink(String conceptLink) {
this.conceptLink = conceptLink;
}
public String getCssClass() {
return cssClass;
}
public void setCssClass(String cssClass) {
if (cssClass == null || cssClass.length() == 0)
return;
this.cssClass = cssClass;
}
public String getId() {
return id;
}
public void setId(String id) {
if (id == null || id.length() == 0)
return;
this.id = id;
}
public Boolean getShowEmptyConcepts() {
return showEmptyConcepts;
}
public void setShowEmptyConcepts(Boolean showEmptyConcepts) {
if (showEmptyConcepts == null)
return;
this.showEmptyConcepts = showEmptyConcepts;
}
public Boolean getShowConceptHeader() {
return showConceptHeader;
}
public void setShowConceptHeader(Boolean showHeader) {
if (showHeader == null)
return;
this.showConceptHeader = showHeader;
}
public Boolean getShowDateHeader() {
return showDateHeader;
}
public void setShowDateHeader(Boolean showDateHeader) {
if (showDateHeader == null)
return;
this.showDateHeader = showDateHeader;
}
public String getSort() {
return sortDescending ? "desc" : "asc";
}
public void setSort(String sort) {
if (sort == null || sort.length() == 0)
return;
sortDescending = !sort.equals("asc");
}
public String getOrientation() {
return orientVertical ? "vertical" : "horizontal";
}
public void setOrientation(String orientation) {
if (orientation == null || orientation.length() == 0)
return;
orientVertical = !orientation.equals("horizontal");
}
public Collection<Obs> getObservations() {
return observations;
}
public void setObservations(Collection<Obs> observations) {
this.observations = observations;
}
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
if (fromDate == null)
return;
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
if (toDate == null)
return;
this.toDate = toDate;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
if (limit == null)
return;
this.limit = limit;
}
public Boolean getCombineEqualResults() {
return combineEqualResults;
}
public void setCombineEqualResults(Boolean combineEqualResults) {
this.combineEqualResults = combineEqualResults;
}
public int doStartTag() {
Locale loc = Context.getLocale();
- DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, loc);
+ DateFormat df = Context.getDateFormat();
+ //DateFormat.getDateInstance(DateFormat.SHORT, loc);
// determine which concepts we care about
List<Concept> conceptList = new ArrayList<Concept>();
Set<Integer> conceptIds = new HashSet<Integer>();
ConceptService cs = Context.getConceptService();
for (StringTokenizer st = new StringTokenizer(concepts, "|"); st.hasMoreTokens();) {
String s = st.nextToken().trim();
log.debug("looking at " + s);
boolean isSet = s.startsWith("set:");
if (isSet)
s = s.substring(4).trim();
Concept c = null;
if (s.startsWith("name:")) {
String name = s.substring(5).trim();
c = cs.getConceptByName(name);
} else {
try {
c = cs.getConcept(Integer.valueOf(s.trim()));
}
catch (Exception ex) {}
}
if (c != null) {
if (isSet) {
List<Concept> inSet = cs.getConceptsByConceptSet(c);
for (Concept con : inSet) {
if (!conceptIds.contains(con.getConceptId())) {
conceptList.add(con);
conceptIds.add(con.getConceptId());
}
}
} else {
if (!conceptIds.contains(c.getConceptId())) {
conceptList.add(c);
conceptIds.add(c.getConceptId());
}
}
}
log.debug("conceptList == " + conceptList);
}
// organize obs of those concepts by Date and Concept
Set<Integer> conceptsWithObs = new HashSet<Integer>();
SortedSet<Date> dates = new TreeSet<Date>();
Map<String, List<Obs>> groupedObs = new HashMap<String, List<Obs>>(); // key is conceptId + "." + date
for (Obs o : observations) {
Integer conceptId = o.getConcept().getConceptId();
if (conceptIds.contains(conceptId)) {
Date thisDate = o.getObsDatetime();
// TODO: allow grouping by day/week/month/etc
if ((fromDate != null && thisDate.compareTo(fromDate) < 0)
|| (toDate != null && thisDate.compareTo(toDate) > 0)) {
continue;
}
dates.add(thisDate);
String key = conceptId + "." + thisDate;
List<Obs> group = groupedObs.get(key);
if (group == null) {
group = new ArrayList<Obs>();
groupedObs.put(key, group);
}
group.add(o);
conceptsWithObs.add(conceptId);
}
}
if (!showEmptyConcepts) {
for (Iterator<Concept> i = conceptList.iterator(); i.hasNext();) {
if (!conceptsWithObs.contains(i.next().getConceptId()))
i.remove();
}
}
List<Date> dateOrder = new ArrayList<Date>(dates);
if (sortDescending)
Collections.reverse(dateOrder);
if (limit > 0 && limit < dateOrder.size()) {
+ if (!sortDescending) {
+ dateOrder = dateOrder.subList(dateOrder.size() - limit, dateOrder.size());
+ }
+ else {
dateOrder = dateOrder.subList(0, limit);
}
+ }
StringBuilder ret = new StringBuilder();
ret.append("<table");
if (id != null)
ret.append(" id=\"" + id + "\"");
if (cssClass != null)
ret.append(" class=\"" + cssClass + "\"");
ret.append(">");
if (orientVertical) {
if (showConceptHeader) {
ret.append("<tr>");
ret.append("<th></th>");
for (Concept c : conceptList) {
ConceptName cn = c.getShortestName(loc, false);
String name = cn.getName();
ret.append("<th>");
if (conceptLink != null) {
ret.append("<a href=\"" + conceptLink + "conceptId=" + c.getConceptId() + "\">");
}
ret.append(name);
if (conceptLink != null) {
ret.append("</a>");
}
ret.append("</th>");
}
ret.append("</tr>");
}
for (Date date : dateOrder) {
ret.append("<tr>");
if (showDateHeader)
ret.append("<th>" + df.format(date) + "</th>");
for (Concept c : conceptList) {
- ret.append("<td>");
+ ret.append("<td align=\"center\">");
String key = c.getConceptId() + "." + date;
List<Obs> list = groupedObs.get(key);
if (list != null) {
if (combineEqualResults) {
Collection<String> unique = new LinkedHashSet<String>();
for (Obs obs : list)
unique.add(obs.getValueAsString(loc));
for (String s : unique)
ret.append(s).append("<br/>");
} else {
for (Obs obs : list)
ret.append(obs.getValueAsString(loc)).append("<br/>");
}
}
ret.append("</td>");
}
ret.append("</tr>");
}
} else { // horizontal
if (showDateHeader) {
ret.append("<tr>");
ret.append("<th></th>");
for (Date date : dateOrder) {
ret.append("<th>" + df.format(date) + "</th>");
}
}
for (Concept c : conceptList) {
ret.append("<tr>");
if (showConceptHeader) {
ConceptName cn = c.getShortestName(loc, false);
String name = cn.getName();
ret.append("<th>");
if (conceptLink != null) {
ret.append("<a href=\"" + conceptLink + "conceptId=" + c.getConceptId() + "\">");
}
ret.append(name);
if (conceptLink != null) {
ret.append("</a>");
}
ret.append("</th>");
}
for (Date date : dateOrder) {
- ret.append("<td>");
+ ret.append("<td align=\"center\">");
String key = c.getConceptId() + "." + date;
List<Obs> list = groupedObs.get(key);
if (list != null) {
if (combineEqualResults) {
Collection<String> unique = new LinkedHashSet<String>();
for (Obs obs : list)
unique.add(obs.getValueAsString(loc));
for (String s : unique)
ret.append(s).append("<br/>");
} else {
for (Obs obs : list)
ret.append(obs.getValueAsString(loc)).append("<br/>");
}
}
ret.append("</td>");
}
ret.append("</tr>");
}
}
ret.append("</table>");
try {
JspWriter w = pageContext.getOut();
w.println(ret);
}
catch (IOException ex) {
log.error("Error while starting ObsTableWidget tag", ex);
}
return SKIP_BODY;
}
public int doEndTag() {
concepts = null;
observations = null;
sortDescending = true;
orientVertical = true;
showEmptyConcepts = true;
showConceptHeader = true;
showDateHeader = true;
combineEqualResults = true;
id = null;
cssClass = null;
showEmptyConcepts = true;
showConceptHeader = true;
fromDate = null;
toDate = null;
limit = 0;
conceptLink = null;
return EVAL_PAGE;
}
}
| false | true | public int doStartTag() {
Locale loc = Context.getLocale();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, loc);
// determine which concepts we care about
List<Concept> conceptList = new ArrayList<Concept>();
Set<Integer> conceptIds = new HashSet<Integer>();
ConceptService cs = Context.getConceptService();
for (StringTokenizer st = new StringTokenizer(concepts, "|"); st.hasMoreTokens();) {
String s = st.nextToken().trim();
log.debug("looking at " + s);
boolean isSet = s.startsWith("set:");
if (isSet)
s = s.substring(4).trim();
Concept c = null;
if (s.startsWith("name:")) {
String name = s.substring(5).trim();
c = cs.getConceptByName(name);
} else {
try {
c = cs.getConcept(Integer.valueOf(s.trim()));
}
catch (Exception ex) {}
}
if (c != null) {
if (isSet) {
List<Concept> inSet = cs.getConceptsByConceptSet(c);
for (Concept con : inSet) {
if (!conceptIds.contains(con.getConceptId())) {
conceptList.add(con);
conceptIds.add(con.getConceptId());
}
}
} else {
if (!conceptIds.contains(c.getConceptId())) {
conceptList.add(c);
conceptIds.add(c.getConceptId());
}
}
}
log.debug("conceptList == " + conceptList);
}
// organize obs of those concepts by Date and Concept
Set<Integer> conceptsWithObs = new HashSet<Integer>();
SortedSet<Date> dates = new TreeSet<Date>();
Map<String, List<Obs>> groupedObs = new HashMap<String, List<Obs>>(); // key is conceptId + "." + date
for (Obs o : observations) {
Integer conceptId = o.getConcept().getConceptId();
if (conceptIds.contains(conceptId)) {
Date thisDate = o.getObsDatetime();
// TODO: allow grouping by day/week/month/etc
if ((fromDate != null && thisDate.compareTo(fromDate) < 0)
|| (toDate != null && thisDate.compareTo(toDate) > 0)) {
continue;
}
dates.add(thisDate);
String key = conceptId + "." + thisDate;
List<Obs> group = groupedObs.get(key);
if (group == null) {
group = new ArrayList<Obs>();
groupedObs.put(key, group);
}
group.add(o);
conceptsWithObs.add(conceptId);
}
}
if (!showEmptyConcepts) {
for (Iterator<Concept> i = conceptList.iterator(); i.hasNext();) {
if (!conceptsWithObs.contains(i.next().getConceptId()))
i.remove();
}
}
List<Date> dateOrder = new ArrayList<Date>(dates);
if (sortDescending)
Collections.reverse(dateOrder);
if (limit > 0 && limit < dateOrder.size()) {
dateOrder = dateOrder.subList(0, limit);
}
StringBuilder ret = new StringBuilder();
ret.append("<table");
if (id != null)
ret.append(" id=\"" + id + "\"");
if (cssClass != null)
ret.append(" class=\"" + cssClass + "\"");
ret.append(">");
if (orientVertical) {
if (showConceptHeader) {
ret.append("<tr>");
ret.append("<th></th>");
for (Concept c : conceptList) {
ConceptName cn = c.getShortestName(loc, false);
String name = cn.getName();
ret.append("<th>");
if (conceptLink != null) {
ret.append("<a href=\"" + conceptLink + "conceptId=" + c.getConceptId() + "\">");
}
ret.append(name);
if (conceptLink != null) {
ret.append("</a>");
}
ret.append("</th>");
}
ret.append("</tr>");
}
for (Date date : dateOrder) {
ret.append("<tr>");
if (showDateHeader)
ret.append("<th>" + df.format(date) + "</th>");
for (Concept c : conceptList) {
ret.append("<td>");
String key = c.getConceptId() + "." + date;
List<Obs> list = groupedObs.get(key);
if (list != null) {
if (combineEqualResults) {
Collection<String> unique = new LinkedHashSet<String>();
for (Obs obs : list)
unique.add(obs.getValueAsString(loc));
for (String s : unique)
ret.append(s).append("<br/>");
} else {
for (Obs obs : list)
ret.append(obs.getValueAsString(loc)).append("<br/>");
}
}
ret.append("</td>");
}
ret.append("</tr>");
}
} else { // horizontal
if (showDateHeader) {
ret.append("<tr>");
ret.append("<th></th>");
for (Date date : dateOrder) {
ret.append("<th>" + df.format(date) + "</th>");
}
}
for (Concept c : conceptList) {
ret.append("<tr>");
if (showConceptHeader) {
ConceptName cn = c.getShortestName(loc, false);
String name = cn.getName();
ret.append("<th>");
if (conceptLink != null) {
ret.append("<a href=\"" + conceptLink + "conceptId=" + c.getConceptId() + "\">");
}
ret.append(name);
if (conceptLink != null) {
ret.append("</a>");
}
ret.append("</th>");
}
for (Date date : dateOrder) {
ret.append("<td>");
String key = c.getConceptId() + "." + date;
List<Obs> list = groupedObs.get(key);
if (list != null) {
if (combineEqualResults) {
Collection<String> unique = new LinkedHashSet<String>();
for (Obs obs : list)
unique.add(obs.getValueAsString(loc));
for (String s : unique)
ret.append(s).append("<br/>");
} else {
for (Obs obs : list)
ret.append(obs.getValueAsString(loc)).append("<br/>");
}
}
ret.append("</td>");
}
ret.append("</tr>");
}
}
ret.append("</table>");
try {
JspWriter w = pageContext.getOut();
w.println(ret);
}
catch (IOException ex) {
log.error("Error while starting ObsTableWidget tag", ex);
}
return SKIP_BODY;
}
| public int doStartTag() {
Locale loc = Context.getLocale();
DateFormat df = Context.getDateFormat();
//DateFormat.getDateInstance(DateFormat.SHORT, loc);
// determine which concepts we care about
List<Concept> conceptList = new ArrayList<Concept>();
Set<Integer> conceptIds = new HashSet<Integer>();
ConceptService cs = Context.getConceptService();
for (StringTokenizer st = new StringTokenizer(concepts, "|"); st.hasMoreTokens();) {
String s = st.nextToken().trim();
log.debug("looking at " + s);
boolean isSet = s.startsWith("set:");
if (isSet)
s = s.substring(4).trim();
Concept c = null;
if (s.startsWith("name:")) {
String name = s.substring(5).trim();
c = cs.getConceptByName(name);
} else {
try {
c = cs.getConcept(Integer.valueOf(s.trim()));
}
catch (Exception ex) {}
}
if (c != null) {
if (isSet) {
List<Concept> inSet = cs.getConceptsByConceptSet(c);
for (Concept con : inSet) {
if (!conceptIds.contains(con.getConceptId())) {
conceptList.add(con);
conceptIds.add(con.getConceptId());
}
}
} else {
if (!conceptIds.contains(c.getConceptId())) {
conceptList.add(c);
conceptIds.add(c.getConceptId());
}
}
}
log.debug("conceptList == " + conceptList);
}
// organize obs of those concepts by Date and Concept
Set<Integer> conceptsWithObs = new HashSet<Integer>();
SortedSet<Date> dates = new TreeSet<Date>();
Map<String, List<Obs>> groupedObs = new HashMap<String, List<Obs>>(); // key is conceptId + "." + date
for (Obs o : observations) {
Integer conceptId = o.getConcept().getConceptId();
if (conceptIds.contains(conceptId)) {
Date thisDate = o.getObsDatetime();
// TODO: allow grouping by day/week/month/etc
if ((fromDate != null && thisDate.compareTo(fromDate) < 0)
|| (toDate != null && thisDate.compareTo(toDate) > 0)) {
continue;
}
dates.add(thisDate);
String key = conceptId + "." + thisDate;
List<Obs> group = groupedObs.get(key);
if (group == null) {
group = new ArrayList<Obs>();
groupedObs.put(key, group);
}
group.add(o);
conceptsWithObs.add(conceptId);
}
}
if (!showEmptyConcepts) {
for (Iterator<Concept> i = conceptList.iterator(); i.hasNext();) {
if (!conceptsWithObs.contains(i.next().getConceptId()))
i.remove();
}
}
List<Date> dateOrder = new ArrayList<Date>(dates);
if (sortDescending)
Collections.reverse(dateOrder);
if (limit > 0 && limit < dateOrder.size()) {
if (!sortDescending) {
dateOrder = dateOrder.subList(dateOrder.size() - limit, dateOrder.size());
}
else {
dateOrder = dateOrder.subList(0, limit);
}
}
StringBuilder ret = new StringBuilder();
ret.append("<table");
if (id != null)
ret.append(" id=\"" + id + "\"");
if (cssClass != null)
ret.append(" class=\"" + cssClass + "\"");
ret.append(">");
if (orientVertical) {
if (showConceptHeader) {
ret.append("<tr>");
ret.append("<th></th>");
for (Concept c : conceptList) {
ConceptName cn = c.getShortestName(loc, false);
String name = cn.getName();
ret.append("<th>");
if (conceptLink != null) {
ret.append("<a href=\"" + conceptLink + "conceptId=" + c.getConceptId() + "\">");
}
ret.append(name);
if (conceptLink != null) {
ret.append("</a>");
}
ret.append("</th>");
}
ret.append("</tr>");
}
for (Date date : dateOrder) {
ret.append("<tr>");
if (showDateHeader)
ret.append("<th>" + df.format(date) + "</th>");
for (Concept c : conceptList) {
ret.append("<td align=\"center\">");
String key = c.getConceptId() + "." + date;
List<Obs> list = groupedObs.get(key);
if (list != null) {
if (combineEqualResults) {
Collection<String> unique = new LinkedHashSet<String>();
for (Obs obs : list)
unique.add(obs.getValueAsString(loc));
for (String s : unique)
ret.append(s).append("<br/>");
} else {
for (Obs obs : list)
ret.append(obs.getValueAsString(loc)).append("<br/>");
}
}
ret.append("</td>");
}
ret.append("</tr>");
}
} else { // horizontal
if (showDateHeader) {
ret.append("<tr>");
ret.append("<th></th>");
for (Date date : dateOrder) {
ret.append("<th>" + df.format(date) + "</th>");
}
}
for (Concept c : conceptList) {
ret.append("<tr>");
if (showConceptHeader) {
ConceptName cn = c.getShortestName(loc, false);
String name = cn.getName();
ret.append("<th>");
if (conceptLink != null) {
ret.append("<a href=\"" + conceptLink + "conceptId=" + c.getConceptId() + "\">");
}
ret.append(name);
if (conceptLink != null) {
ret.append("</a>");
}
ret.append("</th>");
}
for (Date date : dateOrder) {
ret.append("<td align=\"center\">");
String key = c.getConceptId() + "." + date;
List<Obs> list = groupedObs.get(key);
if (list != null) {
if (combineEqualResults) {
Collection<String> unique = new LinkedHashSet<String>();
for (Obs obs : list)
unique.add(obs.getValueAsString(loc));
for (String s : unique)
ret.append(s).append("<br/>");
} else {
for (Obs obs : list)
ret.append(obs.getValueAsString(loc)).append("<br/>");
}
}
ret.append("</td>");
}
ret.append("</tr>");
}
}
ret.append("</table>");
try {
JspWriter w = pageContext.getOut();
w.println(ret);
}
catch (IOException ex) {
log.error("Error while starting ObsTableWidget tag", ex);
}
return SKIP_BODY;
}
|
diff --git a/src/ca/slashdev/bb/tasks/JadtoolTask.java b/src/ca/slashdev/bb/tasks/JadtoolTask.java
index e40007b..e918b5c 100644
--- a/src/ca/slashdev/bb/tasks/JadtoolTask.java
+++ b/src/ca/slashdev/bb/tasks/JadtoolTask.java
@@ -1,198 +1,198 @@
/*
* Copyright 2008 Josh Kropf
*
* This file is part of bb-ant-tools.
*
* bb-ant-tools 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.
*
* bb-ant-tools 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 bb-ant-tools; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package ca.slashdev.bb.tasks;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.ResourceCollection;
import org.apache.tools.ant.types.resources.FileResource;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.ant.util.ResourceUtils;
import ca.slashdev.bb.types.OverrideType;
import ca.slashdev.bb.util.Utils;
/**
* @author josh
*/
public class JadtoolTask extends BaseTask {
private File input;
private File destDir;
private Vector<ResourceCollection> resources = new Vector<ResourceCollection>();
private Vector<OverrideType> overrides = new Vector<OverrideType>();
private Map<String, OverrideType> overrideMap = new HashMap<String, OverrideType>();
public void setInput(File input) {
this.input = input;
}
public void setDestDir(File destDir) {
this.destDir = destDir;
}
public void add(ResourceCollection res) {
resources.add(res);
}
public void add(OverrideType override) {
overrides.add(override);
}
@Override
public void execute() throws BuildException {
super.execute();
if (input == null)
throw new BuildException("input is a required attribute");
if (!input.exists())
throw new BuildException("input file is missing");
if (resources.size() == 0)
throw new BuildException("specify at least one cod file");
if (destDir == null)
throw new BuildException("destdir is a required attribute");
if (!destDir.exists())
if (!destDir.mkdirs())
throw new BuildException("unable to create destination directory");
for (OverrideType o : overrides) {
o.validate();
overrideMap.put(o.getKey().toLowerCase(), o);
}
executeRewrite();
}
@SuppressWarnings("unchecked")
private void executeRewrite() {
BufferedReader reader = null;
PrintStream output = null;
try {
try {
reader = new BufferedReader(new FileReader(input));
output = new PrintStream(new File(destDir, input.getName()));
int i, num = 0;
String line, key, value;
OverrideType override;
while ((line = reader.readLine()) != null) {
num ++;
i = line.indexOf(':');
if (i == -1)
throw new BuildException("unexpected line in jad file: "+num);
key = line.substring(0, i);
value = line.substring(i+1);
if (key.startsWith("RIM-COD-URL")
|| key.startsWith("RIM-COD-SHA1")
|| key.startsWith("RIM-COD-Size")) {
continue; // ignore line
}
// check for .jad element override, remove from map if found
override = overrideMap.get(key.toLowerCase());
if (override != null) {
value = override.getValue();
overrideMap.remove(key.toLowerCase());
}
output.printf("%s: %s\n", key, value);
}
} catch (IOException e) {
throw new BuildException("error creating jad file", e);
}
try {
int num = 0;
File destFile;
Resource r;
for (ResourceCollection rc : resources) {
Iterator<Resource> i = rc.iterator();
while (i.hasNext()) {
r = i.next();
destFile = new File(destDir, Utils.getFilePart(r));
if (Utils.isZip(r)) {
String[] zipEntries = Utils.extract(r, destDir);
for (String entry : zipEntries) {
destFile = new File(destDir, entry);
if (num == 0) {
output.printf("RIM-COD-URL: %s\n", destFile.getName());
output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile));
output.printf("RIM-COD-Size: %d\n", destFile.length());
} else {
output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName());
output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile));
output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length());
}
num++;
}
} else {
ResourceUtils.copyResource(r, new FileResource(destFile));
if (num == 0) {
output.printf("RIM-COD-URL: %s\n", destFile.getName());
output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile));
output.printf("RIM-COD-Size: %d\n", destFile.length());
} else {
output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName());
output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile));
output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length());
}
+ num ++;
}
- num ++;
}
}
} catch (IOException e) {
throw new BuildException("error copying cod file", e);
}
// flush remaining overrides into target .jad
for (OverrideType override : overrideMap.values()) {
output.printf("%s: %s\n", override.getKey(), override.getValue());
}
} finally {
FileUtils.close(reader);
FileUtils.close(output);
}
}
}
| false | true | private void executeRewrite() {
BufferedReader reader = null;
PrintStream output = null;
try {
try {
reader = new BufferedReader(new FileReader(input));
output = new PrintStream(new File(destDir, input.getName()));
int i, num = 0;
String line, key, value;
OverrideType override;
while ((line = reader.readLine()) != null) {
num ++;
i = line.indexOf(':');
if (i == -1)
throw new BuildException("unexpected line in jad file: "+num);
key = line.substring(0, i);
value = line.substring(i+1);
if (key.startsWith("RIM-COD-URL")
|| key.startsWith("RIM-COD-SHA1")
|| key.startsWith("RIM-COD-Size")) {
continue; // ignore line
}
// check for .jad element override, remove from map if found
override = overrideMap.get(key.toLowerCase());
if (override != null) {
value = override.getValue();
overrideMap.remove(key.toLowerCase());
}
output.printf("%s: %s\n", key, value);
}
} catch (IOException e) {
throw new BuildException("error creating jad file", e);
}
try {
int num = 0;
File destFile;
Resource r;
for (ResourceCollection rc : resources) {
Iterator<Resource> i = rc.iterator();
while (i.hasNext()) {
r = i.next();
destFile = new File(destDir, Utils.getFilePart(r));
if (Utils.isZip(r)) {
String[] zipEntries = Utils.extract(r, destDir);
for (String entry : zipEntries) {
destFile = new File(destDir, entry);
if (num == 0) {
output.printf("RIM-COD-URL: %s\n", destFile.getName());
output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile));
output.printf("RIM-COD-Size: %d\n", destFile.length());
} else {
output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName());
output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile));
output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length());
}
num++;
}
} else {
ResourceUtils.copyResource(r, new FileResource(destFile));
if (num == 0) {
output.printf("RIM-COD-URL: %s\n", destFile.getName());
output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile));
output.printf("RIM-COD-Size: %d\n", destFile.length());
} else {
output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName());
output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile));
output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length());
}
}
num ++;
}
}
} catch (IOException e) {
throw new BuildException("error copying cod file", e);
}
// flush remaining overrides into target .jad
for (OverrideType override : overrideMap.values()) {
output.printf("%s: %s\n", override.getKey(), override.getValue());
}
} finally {
FileUtils.close(reader);
FileUtils.close(output);
}
}
| private void executeRewrite() {
BufferedReader reader = null;
PrintStream output = null;
try {
try {
reader = new BufferedReader(new FileReader(input));
output = new PrintStream(new File(destDir, input.getName()));
int i, num = 0;
String line, key, value;
OverrideType override;
while ((line = reader.readLine()) != null) {
num ++;
i = line.indexOf(':');
if (i == -1)
throw new BuildException("unexpected line in jad file: "+num);
key = line.substring(0, i);
value = line.substring(i+1);
if (key.startsWith("RIM-COD-URL")
|| key.startsWith("RIM-COD-SHA1")
|| key.startsWith("RIM-COD-Size")) {
continue; // ignore line
}
// check for .jad element override, remove from map if found
override = overrideMap.get(key.toLowerCase());
if (override != null) {
value = override.getValue();
overrideMap.remove(key.toLowerCase());
}
output.printf("%s: %s\n", key, value);
}
} catch (IOException e) {
throw new BuildException("error creating jad file", e);
}
try {
int num = 0;
File destFile;
Resource r;
for (ResourceCollection rc : resources) {
Iterator<Resource> i = rc.iterator();
while (i.hasNext()) {
r = i.next();
destFile = new File(destDir, Utils.getFilePart(r));
if (Utils.isZip(r)) {
String[] zipEntries = Utils.extract(r, destDir);
for (String entry : zipEntries) {
destFile = new File(destDir, entry);
if (num == 0) {
output.printf("RIM-COD-URL: %s\n", destFile.getName());
output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile));
output.printf("RIM-COD-Size: %d\n", destFile.length());
} else {
output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName());
output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile));
output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length());
}
num++;
}
} else {
ResourceUtils.copyResource(r, new FileResource(destFile));
if (num == 0) {
output.printf("RIM-COD-URL: %s\n", destFile.getName());
output.printf("RIM-COD-SHA1: %s\n", Utils.getSHA1(destFile));
output.printf("RIM-COD-Size: %d\n", destFile.length());
} else {
output.printf("RIM-COD-URL-%d: %s\n", num, destFile.getName());
output.printf("RIM-COD-SHA1-%d: %s\n", num, Utils.getSHA1(destFile));
output.printf("RIM-COD-Size-%d: %d\n", num, destFile.length());
}
num ++;
}
}
}
} catch (IOException e) {
throw new BuildException("error copying cod file", e);
}
// flush remaining overrides into target .jad
for (OverrideType override : overrideMap.values()) {
output.printf("%s: %s\n", override.getKey(), override.getValue());
}
} finally {
FileUtils.close(reader);
FileUtils.close(output);
}
}
|
diff --git a/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java b/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java
index dc6c5ce0..67e8af14 100644
--- a/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java
+++ b/commons/src/main/java/org/archive/io/InMemoryReplayCharSequence.java
@@ -1,148 +1,150 @@
/*
* This file is part of the Heritrix web crawler (crawler.archive.org).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA 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.archive.io;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CodingErrorAction;
import java.util.logging.Level;
import java.util.logging.Logger;
public class InMemoryReplayCharSequence implements ReplayCharSequence {
protected static Logger logger =
Logger.getLogger(InMemoryReplayCharSequence.class.getName());
/**
* CharBuffer of decoded content.
*
* Content of this buffer is unicode.
*/
private CharBuffer charBuffer = null;
protected long decodingExceptionsCount = 0;
/**
* Constructor for all in-memory operation.
*
* @param buffer
* @param size Total size of stream to replay in bytes. Used to find
* EOS. This is total length of content including HTTP headers if
* present.
* @param responseBodyStart Where the response body starts in bytes.
* Used to skip over the HTTP headers if present.
* @param encoding Encoding to use reading the passed prefix buffer and
* backing file. For now, should be java canonical name for the
* encoding. Must not be null.
*
* @throws IOException
*/
public InMemoryReplayCharSequence(byte[] buffer, long size,
long responseBodyStart, String encoding) throws IOException {
super();
this.charBuffer = decodeInMemory(buffer, size, responseBodyStart,
encoding);
}
/**
* Decode passed buffer into a CharBuffer.
*
* This method decodes a memory buffer returning a memory buffer.
*
* @param buffer
* @param size Total size of stream to replay in bytes. Used to find
* EOS. This is total length of content including HTTP headers if
* present.
* @param responseBodyStart Where the response body starts in bytes.
* Used to skip over the HTTP headers if present.
* @param encoding Encoding to use reading the passed prefix buffer and
* backing file. For now, should be java canonical name for the
* encoding. Must not be null.
*
* @return A CharBuffer view on decodings of the contents of passed
* buffer.
*/
private CharBuffer decodeInMemory(byte[] buffer, long size,
long responseBodyStart, String encoding) {
ByteBuffer bb = ByteBuffer.wrap(buffer);
// Move past the HTTP header if present.
bb.position((int) responseBodyStart);
+ bb.mark();
// Set the end-of-buffer to be end-of-content.
bb.limit((int) size);
Charset charset;
try {
charset = Charset.forName(encoding);
} catch (IllegalArgumentException e) {
logger.log(Level.WARNING,"charset problem: "+encoding,e);
// TODO: better detection or default
charset = Charset.forName(FALLBACK_CHARSET_NAME);
}
try {
return charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(bb).asReadOnlyBuffer();
} catch (CharacterCodingException cce) {
+ bb.reset();
decodingExceptionsCount++;
return charset.decode(bb).asReadOnlyBuffer();
}
}
public void close() {
this.charBuffer = null;
}
protected void finalize() throws Throwable {
super.finalize();
// Maybe TODO: eliminate close here, requiring explicit close instead
close();
}
public int length() {
return this.charBuffer.limit();
}
public char charAt(int index) {
return this.charBuffer.get(index);
}
public CharSequence subSequence(int start, int end) {
return new CharSubSequence(this, start, end);
}
public String toString() {
StringBuffer sb = new StringBuffer(length());
sb.append(this);
return sb.toString();
}
/**
* Return 1 if there were decoding problems (a full count isn't possible).
*
* @see org.archive.io.ReplayCharSequence#getDecodeExceptionCount()
*/
@Override
public long getDecodeExceptionCount() {
return decodingExceptionsCount;
}
}
| false | true | private CharBuffer decodeInMemory(byte[] buffer, long size,
long responseBodyStart, String encoding) {
ByteBuffer bb = ByteBuffer.wrap(buffer);
// Move past the HTTP header if present.
bb.position((int) responseBodyStart);
// Set the end-of-buffer to be end-of-content.
bb.limit((int) size);
Charset charset;
try {
charset = Charset.forName(encoding);
} catch (IllegalArgumentException e) {
logger.log(Level.WARNING,"charset problem: "+encoding,e);
// TODO: better detection or default
charset = Charset.forName(FALLBACK_CHARSET_NAME);
}
try {
return charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(bb).asReadOnlyBuffer();
} catch (CharacterCodingException cce) {
decodingExceptionsCount++;
return charset.decode(bb).asReadOnlyBuffer();
}
}
| private CharBuffer decodeInMemory(byte[] buffer, long size,
long responseBodyStart, String encoding) {
ByteBuffer bb = ByteBuffer.wrap(buffer);
// Move past the HTTP header if present.
bb.position((int) responseBodyStart);
bb.mark();
// Set the end-of-buffer to be end-of-content.
bb.limit((int) size);
Charset charset;
try {
charset = Charset.forName(encoding);
} catch (IllegalArgumentException e) {
logger.log(Level.WARNING,"charset problem: "+encoding,e);
// TODO: better detection or default
charset = Charset.forName(FALLBACK_CHARSET_NAME);
}
try {
return charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(bb).asReadOnlyBuffer();
} catch (CharacterCodingException cce) {
bb.reset();
decodingExceptionsCount++;
return charset.decode(bb).asReadOnlyBuffer();
}
}
|
diff --git a/src/com/bot42/Bot42.java b/src/com/bot42/Bot42.java
index 4e07fa2..806e2e9 100644
--- a/src/com/bot42/Bot42.java
+++ b/src/com/bot42/Bot42.java
@@ -1,176 +1,175 @@
package com.bot42;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public class Bot42 {
private String nick = "Bot42";
private String host = "irc.kottnet.net";
private int port = 6667;
private Socket ircSocket;
private PrintWriter ircWriter = null;
private BufferedReader ircReader = null;
private List<String> joinedChannels = new LinkedList<String>();
private List<String> globalOps = new LinkedList<String>();
private HashMap<String, List<String>> channelOps = new HashMap<String, List<String>>();
private static Bot42 bot42 = new Bot42();
public static void main(String[] args) {
System.out.println("Bot42 IRC Bot by Vijfhoek and F16Gaming.");
System.out.println("TODO: Add copyright information if we're going to use a license.");
System.out.println("TODO: Add more TODO statements.");
System.out.println();
boolean connected = false;
// TODO Add a config file for this
bot42.globalOps.add("Vijfhoek");
bot42.globalOps.add("F16Gaming");
try {
bot42.ircSocket = new Socket(bot42.host, bot42.port);
bot42.ircWriter = new PrintWriter(bot42.ircSocket.getOutputStream());
bot42.ircReader = new BufferedReader(new InputStreamReader(bot42.ircSocket.getInputStream()));
bot42.write("NICK " + bot42.nick);
bot42.write("USER " + bot42.nick.toLowerCase() + " 0 * :" + bot42.nick);
while (true) {
String message = bot42.read();
String[] splitMessage = message.split(" ");
if (splitMessage[0].equals("PING")) {
bot42.write("PONG " + splitMessage[1]);
}
if (!connected) {
if (splitMessage[1].equals("376")) {
connected = true;
bot42.write("JOIN #Bot42");
} else if (splitMessage[1].equals("433")) {
bot42.nick += "|2";
bot42.write("NICK " + bot42.nick);
}
}
if (splitMessage[1].equals("366")) {
bot42.joinedChannels.add(splitMessage[3]);
} else if (splitMessage[1].equals("353")) {
List<String> ops = new LinkedList<String>();
for (int i = 5; i < splitMessage.length; i++) {
String targetNick = splitMessage[i].replace(":", "");
if (targetNick.substring(0, 1).equals("@")) {
ops.add(targetNick.substring(1));
}
}
bot42.channelOps.put(splitMessage[4], ops);
}
if (splitMessage[1].equals("KICK") && splitMessage[3].equals(bot42.nick)) {
bot42.joinedChannels.remove(splitMessage[2]);
} else if (splitMessage[1].equals("PRIVMSG")) {
if (bot42.isOp(bot42.hostToNick(splitMessage[0]), splitMessage[2])) {
if (splitMessage[3].equals(":.print")) {
String buffer = "";
for (int i = 4; i < splitMessage.length; i++) {
buffer += splitMessage[i] + " ";
}
buffer = buffer.trim();
bot42.write("PRIVMSG " + splitMessage[2] + " :" + buffer);
} else if (splitMessage[3].equals(":.raw")) {
String buffer = "";
for (int i = 4; i < splitMessage.length; i++) {
buffer += splitMessage[i] + " ";
}
buffer = buffer.trim();
bot42.write(buffer);
} else if (splitMessage[3].equals(":.kick")) {
String channel;
String target;
if (bot42.isChannel(splitMessage[2])) {
channel = splitMessage[2];
target = splitMessage[4];
} else {
channel = splitMessage[4];
target = splitMessage[5];
}
bot42.write("KICK " + channel + " " + target + " :(" + bot42.hostToNick(splitMessage[0]) + ")");
} else if (splitMessage[3].equals(":.quit")) {
String buffer = "";
if (splitMessage.length > 4) {
buffer = " :";
for (int i = 4; i < splitMessage.length; i++) {
buffer += splitMessage[i];
}
}
- buffer = buffer.trim();
bot42.write("QUIT" + buffer);
}
}
}
}
} catch (UnknownHostException e) {
System.out.println("[ERR] Can't connect to host " + bot42.host + ":" + bot42.port);
return;
} catch (IOException e) {
System.out.println("[ERR] IO Exception " + e + " occured");
return;
}
}
public void write(String line) {
ircWriter.print(line + "\r\n");
ircWriter.flush();
System.out.println("[OUT] " + line);
}
public String read() throws IOException {
String line = "";
line = ircReader.readLine();
System.out.println(" [IN] " + line);
return line;
}
public boolean isOp(String nick, String channel) {
if (channel.startsWith("#"))
{
if (!channelOps.containsKey(channel))
return false;
List<String> ops = channelOps.get(channel);
if (!ops.contains(nick))
return false;
else
return true;
} else if (channel.equals(bot42.nick)) {
if (!globalOps.contains(nick))
return false;
return true;
}
return false;
}
public boolean isChannel(String target) {
return target.startsWith("#");
}
public String hostToNick(String host) {
host = host.replaceFirst(":", "");
if (!host.contains("!"))
return null;
String nick = host.split("!")[0];
return nick;
}
}
| true | true | public static void main(String[] args) {
System.out.println("Bot42 IRC Bot by Vijfhoek and F16Gaming.");
System.out.println("TODO: Add copyright information if we're going to use a license.");
System.out.println("TODO: Add more TODO statements.");
System.out.println();
boolean connected = false;
// TODO Add a config file for this
bot42.globalOps.add("Vijfhoek");
bot42.globalOps.add("F16Gaming");
try {
bot42.ircSocket = new Socket(bot42.host, bot42.port);
bot42.ircWriter = new PrintWriter(bot42.ircSocket.getOutputStream());
bot42.ircReader = new BufferedReader(new InputStreamReader(bot42.ircSocket.getInputStream()));
bot42.write("NICK " + bot42.nick);
bot42.write("USER " + bot42.nick.toLowerCase() + " 0 * :" + bot42.nick);
while (true) {
String message = bot42.read();
String[] splitMessage = message.split(" ");
if (splitMessage[0].equals("PING")) {
bot42.write("PONG " + splitMessage[1]);
}
if (!connected) {
if (splitMessage[1].equals("376")) {
connected = true;
bot42.write("JOIN #Bot42");
} else if (splitMessage[1].equals("433")) {
bot42.nick += "|2";
bot42.write("NICK " + bot42.nick);
}
}
if (splitMessage[1].equals("366")) {
bot42.joinedChannels.add(splitMessage[3]);
} else if (splitMessage[1].equals("353")) {
List<String> ops = new LinkedList<String>();
for (int i = 5; i < splitMessage.length; i++) {
String targetNick = splitMessage[i].replace(":", "");
if (targetNick.substring(0, 1).equals("@")) {
ops.add(targetNick.substring(1));
}
}
bot42.channelOps.put(splitMessage[4], ops);
}
if (splitMessage[1].equals("KICK") && splitMessage[3].equals(bot42.nick)) {
bot42.joinedChannels.remove(splitMessage[2]);
} else if (splitMessage[1].equals("PRIVMSG")) {
if (bot42.isOp(bot42.hostToNick(splitMessage[0]), splitMessage[2])) {
if (splitMessage[3].equals(":.print")) {
String buffer = "";
for (int i = 4; i < splitMessage.length; i++) {
buffer += splitMessage[i] + " ";
}
buffer = buffer.trim();
bot42.write("PRIVMSG " + splitMessage[2] + " :" + buffer);
} else if (splitMessage[3].equals(":.raw")) {
String buffer = "";
for (int i = 4; i < splitMessage.length; i++) {
buffer += splitMessage[i] + " ";
}
buffer = buffer.trim();
bot42.write(buffer);
} else if (splitMessage[3].equals(":.kick")) {
String channel;
String target;
if (bot42.isChannel(splitMessage[2])) {
channel = splitMessage[2];
target = splitMessage[4];
} else {
channel = splitMessage[4];
target = splitMessage[5];
}
bot42.write("KICK " + channel + " " + target + " :(" + bot42.hostToNick(splitMessage[0]) + ")");
} else if (splitMessage[3].equals(":.quit")) {
String buffer = "";
if (splitMessage.length > 4) {
buffer = " :";
for (int i = 4; i < splitMessage.length; i++) {
buffer += splitMessage[i];
}
}
buffer = buffer.trim();
bot42.write("QUIT" + buffer);
}
}
}
}
} catch (UnknownHostException e) {
System.out.println("[ERR] Can't connect to host " + bot42.host + ":" + bot42.port);
return;
} catch (IOException e) {
System.out.println("[ERR] IO Exception " + e + " occured");
return;
}
}
| public static void main(String[] args) {
System.out.println("Bot42 IRC Bot by Vijfhoek and F16Gaming.");
System.out.println("TODO: Add copyright information if we're going to use a license.");
System.out.println("TODO: Add more TODO statements.");
System.out.println();
boolean connected = false;
// TODO Add a config file for this
bot42.globalOps.add("Vijfhoek");
bot42.globalOps.add("F16Gaming");
try {
bot42.ircSocket = new Socket(bot42.host, bot42.port);
bot42.ircWriter = new PrintWriter(bot42.ircSocket.getOutputStream());
bot42.ircReader = new BufferedReader(new InputStreamReader(bot42.ircSocket.getInputStream()));
bot42.write("NICK " + bot42.nick);
bot42.write("USER " + bot42.nick.toLowerCase() + " 0 * :" + bot42.nick);
while (true) {
String message = bot42.read();
String[] splitMessage = message.split(" ");
if (splitMessage[0].equals("PING")) {
bot42.write("PONG " + splitMessage[1]);
}
if (!connected) {
if (splitMessage[1].equals("376")) {
connected = true;
bot42.write("JOIN #Bot42");
} else if (splitMessage[1].equals("433")) {
bot42.nick += "|2";
bot42.write("NICK " + bot42.nick);
}
}
if (splitMessage[1].equals("366")) {
bot42.joinedChannels.add(splitMessage[3]);
} else if (splitMessage[1].equals("353")) {
List<String> ops = new LinkedList<String>();
for (int i = 5; i < splitMessage.length; i++) {
String targetNick = splitMessage[i].replace(":", "");
if (targetNick.substring(0, 1).equals("@")) {
ops.add(targetNick.substring(1));
}
}
bot42.channelOps.put(splitMessage[4], ops);
}
if (splitMessage[1].equals("KICK") && splitMessage[3].equals(bot42.nick)) {
bot42.joinedChannels.remove(splitMessage[2]);
} else if (splitMessage[1].equals("PRIVMSG")) {
if (bot42.isOp(bot42.hostToNick(splitMessage[0]), splitMessage[2])) {
if (splitMessage[3].equals(":.print")) {
String buffer = "";
for (int i = 4; i < splitMessage.length; i++) {
buffer += splitMessage[i] + " ";
}
buffer = buffer.trim();
bot42.write("PRIVMSG " + splitMessage[2] + " :" + buffer);
} else if (splitMessage[3].equals(":.raw")) {
String buffer = "";
for (int i = 4; i < splitMessage.length; i++) {
buffer += splitMessage[i] + " ";
}
buffer = buffer.trim();
bot42.write(buffer);
} else if (splitMessage[3].equals(":.kick")) {
String channel;
String target;
if (bot42.isChannel(splitMessage[2])) {
channel = splitMessage[2];
target = splitMessage[4];
} else {
channel = splitMessage[4];
target = splitMessage[5];
}
bot42.write("KICK " + channel + " " + target + " :(" + bot42.hostToNick(splitMessage[0]) + ")");
} else if (splitMessage[3].equals(":.quit")) {
String buffer = "";
if (splitMessage.length > 4) {
buffer = " :";
for (int i = 4; i < splitMessage.length; i++) {
buffer += splitMessage[i];
}
}
bot42.write("QUIT" + buffer);
}
}
}
}
} catch (UnknownHostException e) {
System.out.println("[ERR] Can't connect to host " + bot42.host + ":" + bot42.port);
return;
} catch (IOException e) {
System.out.println("[ERR] IO Exception " + e + " occured");
return;
}
}
|
diff --git a/mtp/src/main/java/org/mobicents/protocols/ss7/stream/tlv/TLVOutputStream.java b/mtp/src/main/java/org/mobicents/protocols/ss7/stream/tlv/TLVOutputStream.java
index c3004a1a5..f73f713b3 100644
--- a/mtp/src/main/java/org/mobicents/protocols/ss7/stream/tlv/TLVOutputStream.java
+++ b/mtp/src/main/java/org/mobicents/protocols/ss7/stream/tlv/TLVOutputStream.java
@@ -1,110 +1,115 @@
/**
*
*/
package org.mobicents.protocols.ss7.stream.tlv;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Simple stream to encode data
* @author baranowb
*
*/
public class TLVOutputStream extends ByteArrayOutputStream {
public void writeTag(int tagClass, boolean primitive, long tag) {
//FIXME: add this
}
/**
* Method used to write tags for common types - be it complex or primitive.
*
* @param tagClass
* @param primitive
* @param value -
* less significant bits(4) are encoded as tag code
*/
public void writeTag(int tagClass, boolean primitive, int value) {
int toEncode = (tagClass & 0x03) << 6;
toEncode |= (primitive ? 0 : 1) << 5;
toEncode |= value & 0x1F;
this.write(toEncode);
}
/**
* Method used to write tags for common types - be it complex or primitive.
*
* @param tagClass
* @param primitive
* @param value -
* less significant bits(4) are encoded as tag code
*/
public void writeTag(int tagClass, boolean primitive, byte[] value) {
int toEncode = (tagClass & 0x03) << 6;
toEncode |= (primitive ? 0 : 1) << 5;
// toEncode |= value & 0x0F;
// FIXME: add hack here
this.write(toEncode);
}
/**
* Writes length in simple or indefinite form
*
* @param l
* @throws IOException
*/
public void writeLength(int v) throws IOException {
- if(v>0x7F)
+ if(v == 0x80)
+ {
+ this.write(0x80);
+ return;
+ }
+ else if(v>0x7F)
{
//XXX: note there is super.count!!!!!!!
int count;
//long form
if ((v & 0xFF000000) > 0) {
count = 4;
} else if ((v & 0x00FF0000) > 0) {
count = 3;
} else if ((v & 0x0000FF00) > 0) {
count = 2;
} else {
count = 1;
}
this.write(count | 0x80);
// now we know how much bytes we need from V, for positive with MSB set
// on MSB-like octet, we need trailing 0x00, this L+1;
// FIXME: change this, tmp hack.
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(v);
bb.flip();
for (int c = 4 - count; c > 0; c--) {
bb.get();
}
byte[] dataToWrite = new byte[count];
bb.get(dataToWrite);
this.write(dataToWrite);
}else
{ //short
this.write(v & 0xFF);
}
}
public void writeLinkStatus(LinkStatus ls) throws IOException
{
this.writeTag(Tag.CLASS_APPLICATION, true, Tag._TAG_LINK_STATUS);
this.writeLength(1);
this.write(ls.getStatus());
}
public void writeData(byte[] b) throws IOException
{
//74, -127, 0, 0, 0, -75,
this.writeTag(Tag.CLASS_APPLICATION, true, Tag._TAG_LINK_DATA);
this.writeLength(b.length);
this.write(b);
}
}
| true | true | public void writeLength(int v) throws IOException {
if(v>0x7F)
{
//XXX: note there is super.count!!!!!!!
int count;
//long form
if ((v & 0xFF000000) > 0) {
count = 4;
} else if ((v & 0x00FF0000) > 0) {
count = 3;
} else if ((v & 0x0000FF00) > 0) {
count = 2;
} else {
count = 1;
}
this.write(count | 0x80);
// now we know how much bytes we need from V, for positive with MSB set
// on MSB-like octet, we need trailing 0x00, this L+1;
// FIXME: change this, tmp hack.
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(v);
bb.flip();
for (int c = 4 - count; c > 0; c--) {
bb.get();
}
byte[] dataToWrite = new byte[count];
bb.get(dataToWrite);
this.write(dataToWrite);
}else
{ //short
this.write(v & 0xFF);
}
}
| public void writeLength(int v) throws IOException {
if(v == 0x80)
{
this.write(0x80);
return;
}
else if(v>0x7F)
{
//XXX: note there is super.count!!!!!!!
int count;
//long form
if ((v & 0xFF000000) > 0) {
count = 4;
} else if ((v & 0x00FF0000) > 0) {
count = 3;
} else if ((v & 0x0000FF00) > 0) {
count = 2;
} else {
count = 1;
}
this.write(count | 0x80);
// now we know how much bytes we need from V, for positive with MSB set
// on MSB-like octet, we need trailing 0x00, this L+1;
// FIXME: change this, tmp hack.
ByteBuffer bb = ByteBuffer.allocate(4);
bb.putInt(v);
bb.flip();
for (int c = 4 - count; c > 0; c--) {
bb.get();
}
byte[] dataToWrite = new byte[count];
bb.get(dataToWrite);
this.write(dataToWrite);
}else
{ //short
this.write(v & 0xFF);
}
}
|
diff --git a/src/main/java/net/recommenders/evaluation/splitter/CrossValidationSplitter.java b/src/main/java/net/recommenders/evaluation/splitter/CrossValidationSplitter.java
index fcdaf4a..d567bf3 100644
--- a/src/main/java/net/recommenders/evaluation/splitter/CrossValidationSplitter.java
+++ b/src/main/java/net/recommenders/evaluation/splitter/CrossValidationSplitter.java
@@ -1,100 +1,100 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.recommenders.evaluation.splitter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Set;
import net.recommenders.evaluation.core.DataModel;
/**
*
* @author alejandr
*/
public class CrossValidationSplitter implements Splitter<Long, Long> {
private int nFolds;
private boolean perUser;
private Random rnd;
public CrossValidationSplitter(int nFolds, boolean perUser, long seed) {
this.nFolds = nFolds;
this.perUser = perUser;
rnd = new Random(seed);
}
public DataModel<Long, Long>[] split(DataModel<Long, Long> data) {
final DataModel<Long, Long>[] splits = new DataModel[nFolds * 2];
for (int i = 0; i < nFolds; i++) {
splits[i] = new DataModel<Long, Long>(); // training
splits[i + 1] = new DataModel<Long, Long>(); // test
}
if (perUser) {
int n = 0;
for (Long user : data.getUsers()) {
List<Long> items = new ArrayList<Long>(data.getUserItemPreferences().get(user).keySet());
Collections.shuffle(items, rnd);
for (Long item : items) {
Double pref = data.getUserItemPreferences().get(user).get(item);
Set<Long> time = null;
if (data.getUserItemTimestamps().containsKey(user) && data.getUserItemTimestamps().get(user).containsKey(item)) {
time = data.getUserItemTimestamps().get(user).get(item);
}
int curFold = n % nFolds;
for (int i = 0; i < nFolds; i++) {
DataModel<Long, Long> datamodel = splits[2 * i]; // training
if (i == curFold) {
datamodel = splits[2 * i + 1]; // test
}
if (pref != null) {
datamodel.addPreference(user, item, pref);
}
if (time != null) {
for (Long t : time) {
datamodel.addTimestamp(user, item, t);
}
}
}
n++;
}
}
} else {
List<Long> users = new ArrayList<Long>(data.getUsers());
Collections.shuffle(users, rnd);
int n = 0;
for (Long user : users) {
List<Long> items = new ArrayList<Long>(data.getUserItemPreferences().get(user).keySet());
Collections.shuffle(items, rnd);
for (Long item : items) {
Double pref = data.getUserItemPreferences().get(user).get(item);
Set<Long> time = null;
if (data.getUserItemTimestamps().containsKey(user) && data.getUserItemTimestamps().get(user).containsKey(item)) {
time = data.getUserItemTimestamps().get(user).get(item);
}
int curFold = n % nFolds;
for (int i = 0; i < nFolds; i++) {
- DataModel<Long, Long> datamodel = splits[2 * i]; // training
+ DataModel<Long, Long> datamodel = splits[i]; // training
if (i == curFold) {
- datamodel = splits[2 * i + 1]; // test
+ datamodel = splits[i + 1]; // test
}
if (pref != null) {
datamodel.addPreference(user, item, pref);
}
if (time != null) {
for (Long t : time) {
datamodel.addTimestamp(user, item, t);
}
}
}
n++;
}
}
}
return splits;
}
}
| false | true | public DataModel<Long, Long>[] split(DataModel<Long, Long> data) {
final DataModel<Long, Long>[] splits = new DataModel[nFolds * 2];
for (int i = 0; i < nFolds; i++) {
splits[i] = new DataModel<Long, Long>(); // training
splits[i + 1] = new DataModel<Long, Long>(); // test
}
if (perUser) {
int n = 0;
for (Long user : data.getUsers()) {
List<Long> items = new ArrayList<Long>(data.getUserItemPreferences().get(user).keySet());
Collections.shuffle(items, rnd);
for (Long item : items) {
Double pref = data.getUserItemPreferences().get(user).get(item);
Set<Long> time = null;
if (data.getUserItemTimestamps().containsKey(user) && data.getUserItemTimestamps().get(user).containsKey(item)) {
time = data.getUserItemTimestamps().get(user).get(item);
}
int curFold = n % nFolds;
for (int i = 0; i < nFolds; i++) {
DataModel<Long, Long> datamodel = splits[2 * i]; // training
if (i == curFold) {
datamodel = splits[2 * i + 1]; // test
}
if (pref != null) {
datamodel.addPreference(user, item, pref);
}
if (time != null) {
for (Long t : time) {
datamodel.addTimestamp(user, item, t);
}
}
}
n++;
}
}
} else {
List<Long> users = new ArrayList<Long>(data.getUsers());
Collections.shuffle(users, rnd);
int n = 0;
for (Long user : users) {
List<Long> items = new ArrayList<Long>(data.getUserItemPreferences().get(user).keySet());
Collections.shuffle(items, rnd);
for (Long item : items) {
Double pref = data.getUserItemPreferences().get(user).get(item);
Set<Long> time = null;
if (data.getUserItemTimestamps().containsKey(user) && data.getUserItemTimestamps().get(user).containsKey(item)) {
time = data.getUserItemTimestamps().get(user).get(item);
}
int curFold = n % nFolds;
for (int i = 0; i < nFolds; i++) {
DataModel<Long, Long> datamodel = splits[2 * i]; // training
if (i == curFold) {
datamodel = splits[2 * i + 1]; // test
}
if (pref != null) {
datamodel.addPreference(user, item, pref);
}
if (time != null) {
for (Long t : time) {
datamodel.addTimestamp(user, item, t);
}
}
}
n++;
}
}
}
return splits;
}
| public DataModel<Long, Long>[] split(DataModel<Long, Long> data) {
final DataModel<Long, Long>[] splits = new DataModel[nFolds * 2];
for (int i = 0; i < nFolds; i++) {
splits[i] = new DataModel<Long, Long>(); // training
splits[i + 1] = new DataModel<Long, Long>(); // test
}
if (perUser) {
int n = 0;
for (Long user : data.getUsers()) {
List<Long> items = new ArrayList<Long>(data.getUserItemPreferences().get(user).keySet());
Collections.shuffle(items, rnd);
for (Long item : items) {
Double pref = data.getUserItemPreferences().get(user).get(item);
Set<Long> time = null;
if (data.getUserItemTimestamps().containsKey(user) && data.getUserItemTimestamps().get(user).containsKey(item)) {
time = data.getUserItemTimestamps().get(user).get(item);
}
int curFold = n % nFolds;
for (int i = 0; i < nFolds; i++) {
DataModel<Long, Long> datamodel = splits[2 * i]; // training
if (i == curFold) {
datamodel = splits[2 * i + 1]; // test
}
if (pref != null) {
datamodel.addPreference(user, item, pref);
}
if (time != null) {
for (Long t : time) {
datamodel.addTimestamp(user, item, t);
}
}
}
n++;
}
}
} else {
List<Long> users = new ArrayList<Long>(data.getUsers());
Collections.shuffle(users, rnd);
int n = 0;
for (Long user : users) {
List<Long> items = new ArrayList<Long>(data.getUserItemPreferences().get(user).keySet());
Collections.shuffle(items, rnd);
for (Long item : items) {
Double pref = data.getUserItemPreferences().get(user).get(item);
Set<Long> time = null;
if (data.getUserItemTimestamps().containsKey(user) && data.getUserItemTimestamps().get(user).containsKey(item)) {
time = data.getUserItemTimestamps().get(user).get(item);
}
int curFold = n % nFolds;
for (int i = 0; i < nFolds; i++) {
DataModel<Long, Long> datamodel = splits[i]; // training
if (i == curFold) {
datamodel = splits[i + 1]; // test
}
if (pref != null) {
datamodel.addPreference(user, item, pref);
}
if (time != null) {
for (Long t : time) {
datamodel.addTimestamp(user, item, t);
}
}
}
n++;
}
}
}
return splits;
}
|
diff --git a/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/PrivateMessageManagerImpl.java b/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/PrivateMessageManagerImpl.java
index 4d4ced78..8e229719 100644
--- a/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/PrivateMessageManagerImpl.java
+++ b/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/PrivateMessageManagerImpl.java
@@ -1,1216 +1,1216 @@
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/msgcntr/trunk/messageforums-component-impl/src/java/org/sakaiproject/component/app/messageforums/ui/PrivateMessageManagerImpl.java $
* $Id: PrivateMessageManagerImpl.java 9227 2006-05-15 15:02:42Z [email protected] $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 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.component.app.messageforums.ui;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.api.app.messageforums.Area;
import org.sakaiproject.api.app.messageforums.AreaManager;
import org.sakaiproject.api.app.messageforums.Attachment;
import org.sakaiproject.api.app.messageforums.Message;
import org.sakaiproject.api.app.messageforums.MessageForumsForumManager;
import org.sakaiproject.api.app.messageforums.MessageForumsMessageManager;
import org.sakaiproject.api.app.messageforums.MessageForumsTypeManager;
import org.sakaiproject.api.app.messageforums.PrivateForum;
import org.sakaiproject.api.app.messageforums.PrivateMessage;
import org.sakaiproject.api.app.messageforums.PrivateMessageRecipient;
import org.sakaiproject.api.app.messageforums.PrivateTopic;
import org.sakaiproject.api.app.messageforums.Topic;
import org.sakaiproject.api.app.messageforums.UniqueArrayList;
import org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager;
import org.sakaiproject.id.api.IdManager;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.site.api.ToolConfiguration;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.component.app.messageforums.TestUtil;
import org.sakaiproject.component.app.messageforums.dao.hibernate.PrivateMessageImpl;
import org.sakaiproject.component.app.messageforums.dao.hibernate.PrivateMessageRecipientImpl;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.email.api.EmailService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.cover.ContentHostingService;
import org.sakaiproject.authz.cover.SecurityService;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.cover.UserDirectoryService;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class PrivateMessageManagerImpl extends HibernateDaoSupport implements
PrivateMessageManager
{
private static final Log LOG = LogFactory
.getLog(PrivateMessageManagerImpl.class);
private static final String QUERY_AGGREGATE_COUNT = "findAggregatePvtMsgCntForUserInContext";
private static final String QUERY_MESSAGES_BY_USER_TYPE_AND_CONTEXT = "findPrvtMsgsByUserTypeContext";
private static final String QUERY_MESSAGES_BY_ID_WITH_RECIPIENTS = "findPrivateMessageByIdWithRecipients";
private static List aggregateList;
private AreaManager areaManager;
private MessageForumsMessageManager messageManager;
private MessageForumsForumManager forumManager;
private MessageForumsTypeManager typeManager;
private IdManager idManager;
private SessionManager sessionManager;
private EmailService emailService;
public void init()
{
;
}
public boolean getPrivateAreaEnabled()
{
if (LOG.isDebugEnabled())
{
LOG.debug("getPrivateAreaEnabled()");
}
return areaManager.isPrivateAreaEnabled();
}
public void setPrivateAreaEnabled(boolean value)
{
if (LOG.isDebugEnabled())
{
LOG.debug("setPrivateAreaEnabled(value: " + value + ")");
}
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#isPrivateAreaEnabled()
*/
public boolean isPrivateAreaEnabled()
{
return areaManager.isPrivateAreaEnabled();
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#getPrivateMessageArea()
*/
public Area getPrivateMessageArea()
{
return areaManager.getPrivateArea();
}
public void savePrivateMessageArea(Area area)
{
areaManager.saveArea(area);
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#initializePrivateMessageArea(org.sakaiproject.api.app.messageforums.Area)
*/
public PrivateForum initializePrivateMessageArea(Area area)
{
String userId = getCurrentUser();
initializeMessageCounts();
getHibernateTemplate().lock(area, LockMode.NONE);
PrivateForum pf;
/** create default user forum/topics if none exist */
if ((pf = forumManager.getPrivateForumByOwner(getCurrentUser())) == null)
{
/** initialize collections */
//getHibernateTemplate().initialize(area.getPrivateForumsSet());
pf = forumManager.createPrivateForum("Private Messages");
//area.addPrivateForum(pf);
//pf.setArea(area);
//areaManager.saveArea(area);
PrivateTopic receivedTopic = forumManager.createPrivateForumTopic("Received", true,false,
userId, pf.getId());
PrivateTopic sentTopic = forumManager.createPrivateForumTopic("Sent", true,false,
userId, pf.getId());
PrivateTopic deletedTopic = forumManager.createPrivateForumTopic("Deleted", true,false,
userId, pf.getId());
//PrivateTopic draftTopic = forumManager.createPrivateForumTopic("Drafts", true,false,
// userId, pf.getId());
/** save individual topics - required to add to forum's topic set */
forumManager.savePrivateForumTopic(receivedTopic);
forumManager.savePrivateForumTopic(sentTopic);
forumManager.savePrivateForumTopic(deletedTopic);
//forumManager.savePrivateForumTopic(draftTopic);
pf.addTopic(receivedTopic);
pf.addTopic(sentTopic);
pf.addTopic(deletedTopic);
//pf.addTopic(draftTopic);
forumManager.savePrivateForum(pf);
}
else{
getHibernateTemplate().initialize(pf.getTopicsSet());
}
return pf;
}
public PrivateForum initializationHelper(PrivateForum forum){
/** reget to load topic foreign keys */
PrivateForum pf = forumManager.getPrivateForumByOwner(getCurrentUser());
getHibernateTemplate().initialize(pf.getTopicsSet());
return pf;
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#savePrivateMessage(org.sakaiproject.api.app.messageforums.Message)
*/
public void savePrivateMessage(Message message)
{
messageManager.saveMessage(message);
}
public Message getMessageById(Long id)
{
return messageManager.getMessageById(id);
}
//Attachment
public Attachment createPvtMsgAttachment(String attachId, String name)
{
try
{
Attachment attach = messageManager.createAttachment();
attach.setAttachmentId(attachId);
attach.setAttachmentName(name);
ContentResource cr = ContentHostingService.getResource(attachId);
attach.setAttachmentSize((new Integer(cr.getContentLength())).toString());
attach.setCreatedBy(cr.getProperties().getProperty(
cr.getProperties().getNamePropCreator()));
attach.setModifiedBy(cr.getProperties().getProperty(
cr.getProperties().getNamePropModifiedBy()));
attach.setAttachmentType(cr.getContentType());
String tempString = cr.getUrl();
String newString = new String();
char[] oneChar = new char[1];
for (int i = 0; i < tempString.length(); i++)
{
if (tempString.charAt(i) != ' ')
{
oneChar[0] = tempString.charAt(i);
String concatString = new String(oneChar);
newString = newString.concat(concatString);
}
else
{
newString = newString.concat("%20");
}
}
//tempString.replaceAll(" ", "%20");
attach.setAttachmentUrl(newString);
return attach;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
// Himansu: I am not quite sure this is what you want... let me know.
// Before saving a message, we need to add all the attachmnets to a perticular message
public void addAttachToPvtMsg(PrivateMessage pvtMsgData,
Attachment pvtMsgAttach)
{
pvtMsgData.addAttachment(pvtMsgAttach);
}
// Required for editing multiple attachments to a message.
// When you reply to a message, you do have option to edit attachments to a message
public void removePvtMsgAttachment(Attachment o)
{
o.getMessage().removeAttachment(o);
}
public Attachment getPvtMsgAttachment(Long pvtMsgAttachId)
{
return messageManager.getAttachmentById(pvtMsgAttachId);
}
public int getTotalNoMessages(Topic topic)
{
return messageManager.findMessageCountByTopicId(topic.getId());
}
public int getUnreadNoMessages(Topic topic)
{
return messageManager.findUnreadMessageCountByTopicId(topic.getId());
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#saveAreaAndForumSettings(org.sakaiproject.api.app.messageforums.Area, org.sakaiproject.api.app.messageforums.PrivateForum)
*/
public void saveAreaAndForumSettings(Area area, PrivateForum forum)
{
/** method calls placed in this function to participate in same transaction */
saveForumSettings(forum);
/** need to evict forum b/c area saves fk on forum (which places two objects w/same id in session */
//getHibernateTemplate().evict(forum);
if (isInstructor()){
savePrivateMessageArea(area);
}
}
public void saveForumSettings(PrivateForum forum)
{
if (LOG.isDebugEnabled())
{
LOG.debug("saveForumSettings(forum: " + forum + ")");
}
if (forum == null)
{
throw new IllegalArgumentException("Null Argument");
}
forumManager.savePrivateForum(forum);
}
/**
* Topic Folder Setting
*/
public boolean isMutableTopicFolder(String parentTopicId)
{
return false;
}
public void createTopicFolderInForum(PrivateForum pf, String folderName)
{
String userId = getCurrentUser();
PrivateTopic createdTopic = forumManager.createPrivateForumTopic(folderName, true,true,
userId, pf.getId());
/** set context and type to differentiate user topics within sites */
createdTopic.setContextId(getContextId());
createdTopic.setTypeUuid(typeManager.getUserDefinedPrivateTopicType());
forumManager.savePrivateForumTopic(createdTopic);
pf.addTopic(createdTopic);
forumManager.savePrivateForum(pf);
}
public void createTopicFolderInTopic(PrivateForum pf, PrivateTopic parentTopic, String folderName)
{
String userId = getCurrentUser();
PrivateTopic createdTopic = forumManager.createPrivateForumTopic(folderName, true,true,
userId, pf.getId());
createdTopic.setParentTopic(parentTopic);
forumManager.savePrivateForumTopic(createdTopic);
pf.addTopic(createdTopic);
forumManager.savePrivateForum(pf);
}
public void renameTopicFolder(PrivateForum pf, String topicUuid, String newName)
{
String userId = getCurrentUser();
List pvtTopics= pf.getTopics();
for (Iterator iter = pvtTopics.iterator(); iter.hasNext();)
{
PrivateTopic element = (PrivateTopic) iter.next();
if(element.getUuid().equals(topicUuid))
{
element.setTitle(newName);
element.setModifiedBy(userId);
element.setModified(new Date());
}
}
forumManager.savePrivateForum(pf);
}
public void deleteTopicFolder(PrivateForum pf,String topicUuid)
{
List pvtTopics= pf.getTopics();
for (Iterator iter = pvtTopics.iterator(); iter.hasNext();)
{
PrivateTopic element = (PrivateTopic) iter.next();
if(element.getUuid().equals(topicUuid))
{
pf.removeTopic(element);
break;
}
}
forumManager.savePrivateForum(pf);
}
/**
* Return Topic based on uuid
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#getTopicByIdWithMessages(java.lang.Long)
*/
public Topic getTopicByUuid(final String topicUuid)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getTopicByIdWithMessages(final Long" + topicUuid + ")");
}
return forumManager.getTopicByUuid(topicUuid);
}
public static final String PVTMSG_MODE_RECEIVED = "Received";
public static final String PVTMSG_MODE_SENT = "Sent";
public static final String PVTMSG_MODE_DELETE = "Deleted";
public static final String PVTMSG_MODE_DRAFT = "Drafts";
public void movePvtMsgTopic(PrivateMessage message, Topic oldTopic, Topic newTopic)
{
List recipients= message.getRecipients();
//get new topic type uuid
String newTopicTypeUuid=getTopicTypeUuid(newTopic.getTitle());
//get pld topic type uuid
String oldTopicTypeUuid=getTopicTypeUuid(oldTopic.getTitle());
//now set the recipiant with new topic type uuid
for (Iterator iter = recipients.iterator(); iter.hasNext();)
{
PrivateMessageRecipient element = (PrivateMessageRecipient) iter.next();
if (element.getTypeUuid().equals(oldTopicTypeUuid) && (element.getUserId().equals(getCurrentUser())))
{
element.setTypeUuid(newTopicTypeUuid);
}
}
savePrivateMessage(message);
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#createPrivateMessage(java.lang.String)
*/
public PrivateMessage createPrivateMessage(String typeUuid)
{
PrivateMessage message = new PrivateMessageImpl();
message.setUuid(idManager.createUuid());
message.setTypeUuid(typeUuid);
message.setCreated(new Date());
message.setCreatedBy(getCurrentUser());
LOG.info("message " + message.getUuid() + " created successfully");
return message;
}
public boolean hasNextMessage(PrivateMessage message)
{
// TODO: Needs optimized
boolean next = false;
if (message != null && message.getTopic() != null
&& message.getTopic().getMessages() != null)
{
for (Iterator iter = message.getTopic().getMessages().iterator(); iter
.hasNext();)
{
Message m = (Message) iter.next();
if (next)
{
return true;
}
if (m.getId().equals(message.getId()))
{
next = true;
}
}
}
// if we get here, there is no next message
return false;
}
public boolean hasPreviousMessage(PrivateMessage message)
{
// TODO: Needs optimized
PrivateMessage prev = null;
if (message != null && message.getTopic() != null
&& message.getTopic().getMessages() != null)
{
for (Iterator iter = message.getTopic().getMessages().iterator(); iter
.hasNext();)
{
Message m = (Message) iter.next();
if (m.getId().equals(message.getId()))
{
// need to check null because we might be on the first message
// which means there is no previous one
return prev != null;
}
prev = (PrivateMessage) m;
}
}
// if we get here, there is no previous message
return false;
}
public PrivateMessage getNextMessage(PrivateMessage message)
{
// TODO: Needs optimized
boolean next = false;
if (message != null && message.getTopic() != null
&& message.getTopic().getMessages() != null)
{
for (Iterator iter = message.getTopic().getMessages().iterator(); iter
.hasNext();)
{
Message m = (Message) iter.next();
if (next)
{
return (PrivateMessage) m;
}
if (m.getId().equals(message.getId()))
{
next = true;
}
}
}
// if we get here, there is no next message
return null;
}
public PrivateMessage getPreviousMessage(PrivateMessage message)
{
// TODO: Needs optimized
PrivateMessage prev = null;
if (message != null && message.getTopic() != null
&& message.getTopic().getMessages() != null)
{
for (Iterator iter = message.getTopic().getMessages().iterator(); iter
.hasNext();)
{
Message m = (Message) iter.next();
if (m.getId().equals(message.getId()))
{
return prev;
}
prev = (PrivateMessage) m;
}
}
// if we get here, there is no previous message
return null;
}
public List getMessagesByTopic(String userId, Long topicId)
{
// TODO Auto-generated method stub
return null;
}
public List getReceivedMessages(String orderField, String order)
{
return getMessagesByType(typeManager.getReceivedPrivateMessageType(),
orderField, order);
}
public List getSentMessages(String orderField, String order)
{
return getMessagesByType(typeManager.getSentPrivateMessageType(),
orderField, order);
}
public List getDeletedMessages(String orderField, String order)
{
return getMessagesByType(typeManager.getDeletedPrivateMessageType(),
orderField, order);
}
public List getDraftedMessages(String orderField, String order)
{
return getMessagesByType(typeManager.getDraftPrivateMessageType(),
orderField, order);
}
public PrivateMessage initMessageWithAttachmentsAndRecipients(PrivateMessage msg){
PrivateMessage pmReturn = (PrivateMessage) messageManager.getMessageByIdWithAttachments(msg.getId());
getHibernateTemplate().initialize(pmReturn.getRecipients());
return pmReturn;
}
/**
* helper method to get messages by type
* @param typeUuid
* @return message list
*/
public List getMessagesByType(final String typeUuid, final String orderField,
final String order)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getMessagesByType(typeUuid:" + typeUuid + ", orderField: "
+ orderField + ", order:" + order + ")");
}
// HibernateCallback hcb = new HibernateCallback() {
// public Object doInHibernate(Session session) throws HibernateException, SQLException {
// Criteria messageCriteria = session.createCriteria(PrivateMessageImpl.class);
// Criteria recipientCriteria = messageCriteria.createCriteria("recipients");
//
// Conjunction conjunction = Expression.conjunction();
// conjunction.add(Expression.eq("userId", getCurrentUser()));
// conjunction.add(Expression.eq("typeUuid", typeUuid));
//
// recipientCriteria.add(conjunction);
//
// if ("asc".equalsIgnoreCase(order)){
// messageCriteria.addOrder(Order.asc(orderField));
// }
// else if ("desc".equalsIgnoreCase(order)){
// messageCriteria.addOrder(Order.desc(orderField));
// }
// else{
// LOG.debug("getMessagesByType failed with (typeUuid:" + typeUuid + ", orderField: " + orderField +
// ", order:" + order + ")");
// throw new IllegalArgumentException("order must have value asc or desc");
// }
//
// //todo: parameterize fetch mode
// messageCriteria.setFetchMode("recipients", FetchMode.EAGER);
// messageCriteria.setFetchMode("attachments", FetchMode.EAGER);
//
// return messageCriteria.list();
// }
// };
HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException,
SQLException
{
Query q = session.getNamedQuery(QUERY_MESSAGES_BY_USER_TYPE_AND_CONTEXT);
Query qOrdered = session.createQuery(q.getQueryString() + " order by "
+ orderField + " " + order);
qOrdered.setParameter("userId", getCurrentUser(), Hibernate.STRING);
qOrdered.setParameter("typeUuid", typeUuid, Hibernate.STRING);
qOrdered.setParameter("contextId", getContextId(), Hibernate.STRING);
return qOrdered.list();
}
};
return (List) getHibernateTemplate().execute(hcb);
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#findMessageCount(java.lang.String)
*/
public int findMessageCount(String typeUuid)
{
if (LOG.isDebugEnabled())
{
LOG.debug("findMessageCount executing with typeUuid: " + typeUuid);
}
if (typeUuid == null)
{
LOG.error("findMessageCount failed with typeUuid: " + typeUuid);
throw new IllegalArgumentException("Null Argument");
}
if (aggregateList == null)
{
LOG.error("findMessageCount failed with aggregateList: " + aggregateList);
throw new IllegalStateException("aggregateList is null");
}
int totalCount = 0;
for (Iterator i = aggregateList.iterator(); i.hasNext();){
Object[] element = (Object[]) i.next();
/** filter on type */
if (typeUuid.equals(element[1])){
/** add read/unread message types */
totalCount += ((Integer) element[2]).intValue();
}
}
return totalCount;
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#findUnreadMessageCount(java.lang.String)
*/
public int findUnreadMessageCount(String typeUuid)
{
if (LOG.isDebugEnabled())
{
LOG.debug("findUnreadMessageCount executing with typeUuid: " + typeUuid);
}
if (typeUuid == null)
{
LOG.error("findUnreadMessageCount failed with typeUuid: " + typeUuid);
throw new IllegalArgumentException("Null Argument");
}
if (aggregateList == null)
{
LOG.error("findMessageCount failed with aggregateList: " + aggregateList);
throw new IllegalStateException("aggregateList is null");
}
int unreadCount = 0;
for (Iterator i = aggregateList.iterator(); i.hasNext();){
Object[] element = (Object[]) i.next();
/** filter on type and read status*/
if (!typeUuid.equals(element[1]) || Boolean.TRUE.equals(element[0])){
continue;
}
else{
unreadCount = ((Integer) element[2]).intValue();
break;
}
}
return unreadCount;
}
/**
* initialize message counts
* @param typeUuid
*/
private void initializeMessageCounts()
{
if (LOG.isDebugEnabled())
{
LOG.debug("initializeMessageCounts executing");
}
HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException,
SQLException
{
Query q = session.getNamedQuery(QUERY_AGGREGATE_COUNT);
q.setParameter("contextId", getContextId(), Hibernate.STRING);
q.setParameter("userId", getCurrentUser(), Hibernate.STRING);
return q.list();
}
};
aggregateList = (List) getHibernateTemplate().execute(hcb);
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#deletePrivateMessage(org.sakaiproject.api.app.messageforums.PrivateMessage, java.lang.String)
*/
public void deletePrivateMessage(PrivateMessage message, String typeUuid)
{
String userId = getCurrentUser();
if (LOG.isDebugEnabled())
{
LOG.debug("deletePrivateMessage(message:" + message + ", typeUuid:"
+ typeUuid + ")");
}
/** fetch recipients for message */
PrivateMessage pvtMessage = getPrivateMessageWithRecipients(message);
/**
* create PrivateMessageRecipient to search
*/
PrivateMessageRecipient pmrReadSearch = new PrivateMessageRecipientImpl(
userId, typeUuid, getContextId(), Boolean.TRUE);
PrivateMessageRecipient pmrNonReadSearch = new PrivateMessageRecipientImpl(
userId, typeUuid, getContextId(), Boolean.FALSE);
int indexDelete = -1;
int indexRead = pvtMessage.getRecipients().indexOf(pmrReadSearch);
if (indexRead != -1)
{
indexDelete = indexRead;
}
else
{
int indexNonRead = pvtMessage.getRecipients().indexOf(pmrNonReadSearch);
if (indexNonRead != -1)
{
indexDelete = indexNonRead;
}
else
{
LOG
.error("deletePrivateMessage -- cannot find private message for user: "
+ userId + ", typeUuid: " + typeUuid);
}
}
if (indexDelete != -1)
{
PrivateMessageRecipient pmrReturned = (PrivateMessageRecipient) pvtMessage
.getRecipients().get(indexDelete);
if (pmrReturned != null)
{
/** check for existing deleted message from user */
PrivateMessageRecipient pmrDeletedSearch = new PrivateMessageRecipientImpl(
userId, typeManager.getDeletedPrivateMessageType(), getContextId(),
Boolean.TRUE);
int indexDeleted = pvtMessage.getRecipients().indexOf(pmrDeletedSearch);
if (indexDeleted == -1)
{
pmrReturned.setRead(Boolean.TRUE);
pmrReturned.setTypeUuid(typeManager.getDeletedPrivateMessageType());
}
else
{
pvtMessage.getRecipients().remove(indexDelete);
}
}
}
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#sendPrivateMessage(org.sakaiproject.api.app.messageforums.PrivateMessage, java.util.Set, boolean)
*/
public void sendPrivateMessage(PrivateMessage message, Set recipients, boolean asEmail)
{
if (LOG.isDebugEnabled())
{
LOG.debug("sendPrivateMessage(message: " + message + ", recipients: "
+ recipients + ")");
}
if (message == null || recipients == null)
{
throw new IllegalArgumentException("Null Argument");
}
if (recipients.size() == 0)
{
/** for no just return out
throw new IllegalArgumentException("Empty recipient list");
**/
return;
}
String currentUserAsString = getCurrentUser();
List recipientList = new UniqueArrayList();
/** test for draft message */
if (message.getDraft().booleanValue())
{
PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
currentUserAsString, typeManager.getDraftPrivateMessageType(),
getContextId(), Boolean.TRUE);
recipientList.add(receiver);
message.setRecipients(recipientList);
savePrivateMessage(message);
return;
}
for (Iterator i = recipients.iterator(); i.hasNext();)
{
User u = (User) i.next();
String userId = u.getId();
/** determine if recipient has forwarding enabled */
PrivateForum pf = forumManager.getPrivateForumByOwner(userId);
boolean forwardingEnabled = false;
if (pf != null && pf.getAutoForward().booleanValue()){
forwardingEnabled = true;
}
List additionalHeaders = new ArrayList(1);
additionalHeaders.add("Content-Type: text/html");
User currentUser = UserDirectoryService.getCurrentUser();
StringBuffer body = new StringBuffer(message.getBody());
body.insert(0, "From: " + currentUser.getDisplayName() + "<p/>");
- body.insert(0, "To:" + message.getRecipientsAsText() + "<p/>");
+ body.insert(0, "To: " + message.getRecipientsAsText() + "<p/>");
if (message.getAttachments() != null && message.getAttachments().size() > 0) {
body.append("<br/><br/>");
for (Iterator iter = message.getAttachments().iterator(); iter.hasNext();) {
Attachment attachment = (Attachment) iter.next();
body.append("<a href=\"" + attachment.getAttachmentUrl() +
"\">" + attachment.getAttachmentName() + "</a><br/>");
}
}
String siteTitle = null;
try{
siteTitle = SiteService.getSite(getContextId()).getTitle();
}
catch (IdUnusedException e){
LOG.error(e.getMessage(), e);
}
String thisPageId = "";
ToolSession ts = sessionManager.getCurrentToolSession();
if (ts != null)
{
ToolConfiguration tool = SiteService.findTool(ts.getPlacementId());
if (tool != null)
{
thisPageId = tool.getPageId();
}
}
String footer = "<p>----------------------<br>" +
"This forwarded message was sent via " + ServerConfigurationService.getString("ui.service") +
" Message Center from the \"" +
siteTitle + "\" site.\n" +
"To reply to this message click this link to access Message Center for this site:" +
" <a href=\"" +
ServerConfigurationService.getPortalUrl() +
"/site/" + ToolManager.getCurrentPlacement().getContext() +
"/page/" + thisPageId+
"\">";
footer += siteTitle + "</a>.</p>";
body.append(footer);
String bodyString = body.toString();
/** determine if current user is equal to recipient */
Boolean isRecipientCurrentUser =
(currentUserAsString.equals(userId) ? Boolean.TRUE : Boolean.FALSE);
if (!asEmail && forwardingEnabled){
emailService.send(u.getEmail(), pf.getAutoForwardEmail(), message.getTitle(),
bodyString, u.getEmail(), null, additionalHeaders);
// use forwarded address if set
PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
userId, typeManager.getReceivedPrivateMessageType(), getContextId(),
isRecipientCurrentUser);
recipientList.add(receiver);
}
else if (asEmail){
emailService.send(u.getEmail(), u.getEmail(), message.getTitle(),
bodyString, u.getEmail(), null, additionalHeaders);
}
else{
PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
userId, typeManager.getReceivedPrivateMessageType(), getContextId(),
isRecipientCurrentUser);
recipientList.add(receiver);
}
}
/** add sender as a saved recipient */
PrivateMessageRecipientImpl sender = new PrivateMessageRecipientImpl(
currentUserAsString, typeManager.getSentPrivateMessageType(),
getContextId(), Boolean.TRUE);
recipientList.add(sender);
message.setRecipients(recipientList);
savePrivateMessage(message);
/** enable if users are stored in message forums user table
Iterator i = recipients.iterator();
while (i.hasNext()){
String userId = (String) i.next();
//getForumUser will create user if forums user does not exist
message.addRecipient(userManager.getForumUser(userId.trim()));
}
**/
}
/**
* @see org.sakaiproject.api.app.messageforums.ui.PrivateMessageManager#markMessageAsReadForUser(org.sakaiproject.api.app.messageforums.PrivateMessage)
*/
public void markMessageAsReadForUser(final PrivateMessage message)
{
if (LOG.isDebugEnabled())
{
LOG.debug("markMessageAsReadForUser(message: " + message + ")");
}
if (message == null)
{
throw new IllegalArgumentException("Null Argument");
}
final String userId = getCurrentUser();
/** fetch recipients for message */
PrivateMessage pvtMessage = getPrivateMessageWithRecipients(message);
/** create PrivateMessageRecipientImpl to search for recipient to update */
PrivateMessageRecipientImpl searchRecipient = new PrivateMessageRecipientImpl(
userId, typeManager.getReceivedPrivateMessageType(), getContextId(),
Boolean.FALSE);
List recipientList = pvtMessage.getRecipients();
if (recipientList == null || recipientList.size() == 0)
{
LOG.error("markMessageAsReadForUser(message: " + message
+ ") has empty recipient list");
throw new Error("markMessageAsReadForUser(message: " + message
+ ") has empty recipient list");
}
int recordIndex = pvtMessage.getRecipients().indexOf(searchRecipient);
if (recordIndex != -1)
{
((PrivateMessageRecipientImpl) recipientList.get(recordIndex))
.setRead(Boolean.TRUE);
}
}
private PrivateMessage getPrivateMessageWithRecipients(
final PrivateMessage message)
{
if (LOG.isDebugEnabled())
{
LOG.debug("getPrivateMessageWithRecipients(message: " + message + ")");
}
if (message == null)
{
throw new IllegalArgumentException("Null Argument");
}
HibernateCallback hcb = new HibernateCallback()
{
public Object doInHibernate(Session session) throws HibernateException,
SQLException
{
Query q = session.getNamedQuery(QUERY_MESSAGES_BY_ID_WITH_RECIPIENTS);
q.setParameter("id", message.getId(), Hibernate.LONG);
return q.uniqueResult();
}
};
PrivateMessage pvtMessage = (PrivateMessage) getHibernateTemplate()
.execute(hcb);
if (pvtMessage == null)
{
LOG.error("getPrivateMessageWithRecipients(message: " + message
+ ") could not find message");
throw new Error("getPrivateMessageWithRecipients(message: " + message
+ ") could not find message");
}
return pvtMessage;
}
public List searchPvtMsgs(String typeUuid, String searchText,Date searchFromDate, Date searchToDate,
Long searchByText,Long searchByAuthor,Long searchByBody, Long searchByLabel,Long searchByDate)
{
return messageManager.findPvtMsgsBySearchText(typeUuid, searchText,searchFromDate, searchToDate,
searchByText,searchByAuthor,searchByBody,searchByLabel,searchByDate);
}
private String getCurrentUser()
{
if (TestUtil.isRunningTests())
{
return "test-user";
}
return sessionManager.getCurrentSessionUserId();
}
public AreaManager getAreaManager()
{
return areaManager;
}
public void setAreaManager(AreaManager areaManager)
{
this.areaManager = areaManager;
}
public MessageForumsMessageManager getMessageManager()
{
return messageManager;
}
public void setMessageManager(MessageForumsMessageManager messageManager)
{
this.messageManager = messageManager;
}
public void setTypeManager(MessageForumsTypeManager typeManager)
{
this.typeManager = typeManager;
}
public void setSessionManager(SessionManager sessionManager)
{
this.sessionManager = sessionManager;
}
public void setIdManager(IdManager idManager)
{
this.idManager = idManager;
}
public void setForumManager(MessageForumsForumManager forumManager)
{
this.forumManager = forumManager;
}
public void setEmailService(EmailService emailService)
{
this.emailService = emailService;
}
public boolean isInstructor()
{
LOG.debug("isInstructor()");
return isInstructor(UserDirectoryService.getCurrentUser());
}
/**
* Check if the given user has site.upd access
*
* @param user
* @return
*/
private boolean isInstructor(User user)
{
if (LOG.isDebugEnabled())
{
LOG.debug("isInstructor(User " + user + ")");
}
if (user != null)
return SecurityService.unlock(user, "site.upd", getContextSiteId());
else
return false;
}
/**
* @return siteId
*/
public String getContextSiteId()
{
LOG.debug("getContextSiteId()");
return ("/site/" + ToolManager.getCurrentPlacement().getContext());
}
public String getContextId()
{
LOG.debug("getContextId()");
if (TestUtil.isRunningTests())
{
return "01001010";
}
else
{
return ToolManager.getCurrentPlacement().getContext();
}
}
//Helper class
public String getTopicTypeUuid(String topicTitle)
{
String topicTypeUuid;
if((PVTMSG_MODE_RECEIVED).equals(topicTitle))
{
topicTypeUuid=typeManager.getReceivedPrivateMessageType();
}
else if((PVTMSG_MODE_SENT).equals(topicTitle))
{
topicTypeUuid=typeManager.getSentPrivateMessageType();
}
else if((PVTMSG_MODE_DELETE).equals(topicTitle))
{
topicTypeUuid=typeManager.getDeletedPrivateMessageType();
}
else if((PVTMSG_MODE_DRAFT).equals(topicTitle))
{
topicTypeUuid=typeManager.getDraftPrivateMessageType();
}
else
{
topicTypeUuid=typeManager.getCustomTopicType(topicTitle);
}
return topicTypeUuid;
}
}
| true | true | public void sendPrivateMessage(PrivateMessage message, Set recipients, boolean asEmail)
{
if (LOG.isDebugEnabled())
{
LOG.debug("sendPrivateMessage(message: " + message + ", recipients: "
+ recipients + ")");
}
if (message == null || recipients == null)
{
throw new IllegalArgumentException("Null Argument");
}
if (recipients.size() == 0)
{
/** for no just return out
throw new IllegalArgumentException("Empty recipient list");
**/
return;
}
String currentUserAsString = getCurrentUser();
List recipientList = new UniqueArrayList();
/** test for draft message */
if (message.getDraft().booleanValue())
{
PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
currentUserAsString, typeManager.getDraftPrivateMessageType(),
getContextId(), Boolean.TRUE);
recipientList.add(receiver);
message.setRecipients(recipientList);
savePrivateMessage(message);
return;
}
for (Iterator i = recipients.iterator(); i.hasNext();)
{
User u = (User) i.next();
String userId = u.getId();
/** determine if recipient has forwarding enabled */
PrivateForum pf = forumManager.getPrivateForumByOwner(userId);
boolean forwardingEnabled = false;
if (pf != null && pf.getAutoForward().booleanValue()){
forwardingEnabled = true;
}
List additionalHeaders = new ArrayList(1);
additionalHeaders.add("Content-Type: text/html");
User currentUser = UserDirectoryService.getCurrentUser();
StringBuffer body = new StringBuffer(message.getBody());
body.insert(0, "From: " + currentUser.getDisplayName() + "<p/>");
body.insert(0, "To:" + message.getRecipientsAsText() + "<p/>");
if (message.getAttachments() != null && message.getAttachments().size() > 0) {
body.append("<br/><br/>");
for (Iterator iter = message.getAttachments().iterator(); iter.hasNext();) {
Attachment attachment = (Attachment) iter.next();
body.append("<a href=\"" + attachment.getAttachmentUrl() +
"\">" + attachment.getAttachmentName() + "</a><br/>");
}
}
String siteTitle = null;
try{
siteTitle = SiteService.getSite(getContextId()).getTitle();
}
catch (IdUnusedException e){
LOG.error(e.getMessage(), e);
}
String thisPageId = "";
ToolSession ts = sessionManager.getCurrentToolSession();
if (ts != null)
{
ToolConfiguration tool = SiteService.findTool(ts.getPlacementId());
if (tool != null)
{
thisPageId = tool.getPageId();
}
}
String footer = "<p>----------------------<br>" +
"This forwarded message was sent via " + ServerConfigurationService.getString("ui.service") +
" Message Center from the \"" +
siteTitle + "\" site.\n" +
"To reply to this message click this link to access Message Center for this site:" +
" <a href=\"" +
ServerConfigurationService.getPortalUrl() +
"/site/" + ToolManager.getCurrentPlacement().getContext() +
"/page/" + thisPageId+
"\">";
footer += siteTitle + "</a>.</p>";
body.append(footer);
String bodyString = body.toString();
/** determine if current user is equal to recipient */
Boolean isRecipientCurrentUser =
(currentUserAsString.equals(userId) ? Boolean.TRUE : Boolean.FALSE);
if (!asEmail && forwardingEnabled){
emailService.send(u.getEmail(), pf.getAutoForwardEmail(), message.getTitle(),
bodyString, u.getEmail(), null, additionalHeaders);
// use forwarded address if set
PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
userId, typeManager.getReceivedPrivateMessageType(), getContextId(),
isRecipientCurrentUser);
recipientList.add(receiver);
}
else if (asEmail){
emailService.send(u.getEmail(), u.getEmail(), message.getTitle(),
bodyString, u.getEmail(), null, additionalHeaders);
}
else{
PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
userId, typeManager.getReceivedPrivateMessageType(), getContextId(),
isRecipientCurrentUser);
recipientList.add(receiver);
}
}
/** add sender as a saved recipient */
PrivateMessageRecipientImpl sender = new PrivateMessageRecipientImpl(
currentUserAsString, typeManager.getSentPrivateMessageType(),
getContextId(), Boolean.TRUE);
recipientList.add(sender);
message.setRecipients(recipientList);
savePrivateMessage(message);
/** enable if users are stored in message forums user table
Iterator i = recipients.iterator();
while (i.hasNext()){
String userId = (String) i.next();
//getForumUser will create user if forums user does not exist
message.addRecipient(userManager.getForumUser(userId.trim()));
}
**/
}
| public void sendPrivateMessage(PrivateMessage message, Set recipients, boolean asEmail)
{
if (LOG.isDebugEnabled())
{
LOG.debug("sendPrivateMessage(message: " + message + ", recipients: "
+ recipients + ")");
}
if (message == null || recipients == null)
{
throw new IllegalArgumentException("Null Argument");
}
if (recipients.size() == 0)
{
/** for no just return out
throw new IllegalArgumentException("Empty recipient list");
**/
return;
}
String currentUserAsString = getCurrentUser();
List recipientList = new UniqueArrayList();
/** test for draft message */
if (message.getDraft().booleanValue())
{
PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
currentUserAsString, typeManager.getDraftPrivateMessageType(),
getContextId(), Boolean.TRUE);
recipientList.add(receiver);
message.setRecipients(recipientList);
savePrivateMessage(message);
return;
}
for (Iterator i = recipients.iterator(); i.hasNext();)
{
User u = (User) i.next();
String userId = u.getId();
/** determine if recipient has forwarding enabled */
PrivateForum pf = forumManager.getPrivateForumByOwner(userId);
boolean forwardingEnabled = false;
if (pf != null && pf.getAutoForward().booleanValue()){
forwardingEnabled = true;
}
List additionalHeaders = new ArrayList(1);
additionalHeaders.add("Content-Type: text/html");
User currentUser = UserDirectoryService.getCurrentUser();
StringBuffer body = new StringBuffer(message.getBody());
body.insert(0, "From: " + currentUser.getDisplayName() + "<p/>");
body.insert(0, "To: " + message.getRecipientsAsText() + "<p/>");
if (message.getAttachments() != null && message.getAttachments().size() > 0) {
body.append("<br/><br/>");
for (Iterator iter = message.getAttachments().iterator(); iter.hasNext();) {
Attachment attachment = (Attachment) iter.next();
body.append("<a href=\"" + attachment.getAttachmentUrl() +
"\">" + attachment.getAttachmentName() + "</a><br/>");
}
}
String siteTitle = null;
try{
siteTitle = SiteService.getSite(getContextId()).getTitle();
}
catch (IdUnusedException e){
LOG.error(e.getMessage(), e);
}
String thisPageId = "";
ToolSession ts = sessionManager.getCurrentToolSession();
if (ts != null)
{
ToolConfiguration tool = SiteService.findTool(ts.getPlacementId());
if (tool != null)
{
thisPageId = tool.getPageId();
}
}
String footer = "<p>----------------------<br>" +
"This forwarded message was sent via " + ServerConfigurationService.getString("ui.service") +
" Message Center from the \"" +
siteTitle + "\" site.\n" +
"To reply to this message click this link to access Message Center for this site:" +
" <a href=\"" +
ServerConfigurationService.getPortalUrl() +
"/site/" + ToolManager.getCurrentPlacement().getContext() +
"/page/" + thisPageId+
"\">";
footer += siteTitle + "</a>.</p>";
body.append(footer);
String bodyString = body.toString();
/** determine if current user is equal to recipient */
Boolean isRecipientCurrentUser =
(currentUserAsString.equals(userId) ? Boolean.TRUE : Boolean.FALSE);
if (!asEmail && forwardingEnabled){
emailService.send(u.getEmail(), pf.getAutoForwardEmail(), message.getTitle(),
bodyString, u.getEmail(), null, additionalHeaders);
// use forwarded address if set
PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
userId, typeManager.getReceivedPrivateMessageType(), getContextId(),
isRecipientCurrentUser);
recipientList.add(receiver);
}
else if (asEmail){
emailService.send(u.getEmail(), u.getEmail(), message.getTitle(),
bodyString, u.getEmail(), null, additionalHeaders);
}
else{
PrivateMessageRecipientImpl receiver = new PrivateMessageRecipientImpl(
userId, typeManager.getReceivedPrivateMessageType(), getContextId(),
isRecipientCurrentUser);
recipientList.add(receiver);
}
}
/** add sender as a saved recipient */
PrivateMessageRecipientImpl sender = new PrivateMessageRecipientImpl(
currentUserAsString, typeManager.getSentPrivateMessageType(),
getContextId(), Boolean.TRUE);
recipientList.add(sender);
message.setRecipients(recipientList);
savePrivateMessage(message);
/** enable if users are stored in message forums user table
Iterator i = recipients.iterator();
while (i.hasNext()){
String userId = (String) i.next();
//getForumUser will create user if forums user does not exist
message.addRecipient(userManager.getForumUser(userId.trim()));
}
**/
}
|
diff --git a/java/target/src/rtapi/javax/safetycritical/PeriodicEventHandler.java b/java/target/src/rtapi/javax/safetycritical/PeriodicEventHandler.java
index 85e8be58..20a98b04 100644
--- a/java/target/src/rtapi/javax/safetycritical/PeriodicEventHandler.java
+++ b/java/target/src/rtapi/javax/safetycritical/PeriodicEventHandler.java
@@ -1,129 +1,129 @@
/*
This file is part of JOP, the Java Optimized Processor
see <http://www.jopdesign.com/>
Copyright (C) 2008-2011, Martin Schoeberl ([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 javax.safetycritical;
import static javax.safetycritical.annotate.Level.LEVEL_1;
import static javax.safetycritical.annotate.Level.LEVEL_0;
import javax.realtime.HighResolutionTime;
import javax.realtime.PeriodicParameters;
import javax.realtime.PriorityParameters;
import javax.realtime.RelativeTime;
import javax.safetycritical.annotate.MemoryAreaEncloses;
import javax.safetycritical.annotate.SCJAllowed;
import javax.safetycritical.annotate.SCJRestricted;
import javax.safetycritical.*;
import com.jopdesign.sys.Memory;
import static javax.safetycritical.annotate.Phase.INITIALIZATION;
import joprt.RtThread;
/**
* The class that represents periodic activity. Should be used as the main
* vehicle for real-time applications.
*
* Now finally we have a class that the implementation can use.
*
* @author Martin Schoeberl
*
*/
@SCJAllowed
public abstract class PeriodicEventHandler extends ManagedEventHandler {
PriorityParameters priority;
RelativeTime start, period;
StorageParameters sp;
// ThreadConfiguration tconf;
String name;
Memory privMem;
RtThread thread;
@MemoryAreaEncloses(inner = { "this", "this", "this" }, outer = {
"priority", "parameters", "scp" })
@SCJAllowed
@SCJRestricted(phase = INITIALIZATION)
public PeriodicEventHandler(PriorityParameters priority,
PeriodicParameters parameters, StorageParameters scp) {
this(priority, parameters, scp, "");
}
@MemoryAreaEncloses(inner = { "this", "this", "this", "this" }, outer = {
"priority", "parameters", "scp", "name" })
@SCJAllowed(LEVEL_1)
public PeriodicEventHandler(PriorityParameters priority,
PeriodicParameters release, StorageParameters scp, String name) {
// TODO: what are we doing with this Managed thing?
super(priority, release, scp, name);
this.priority = priority;
start = (RelativeTime)release.getStart();
period = release.getPeriod();
// TODO scp
// this.tconf = tconf;
this.name = name;
int p = ((int) period.getMilliseconds()) * 1000
+ period.getNanoseconds() / 1000;
if(p < 0) { // Overflow
p = Integer.MAX_VALUE;
}
int off = ((int) start.getMilliseconds()) * 1000
+ start.getNanoseconds() / 1000;
if(off < 0) { // Overflow
off = Integer.MAX_VALUE;
}
// TODO: this is a very quick hack to get privat memory
// working. The StorageParameters is incomplete. Was this
// updated in the spec?
- privMem = new Memory((int) scp.getTotalBackingStoreSize());
+ privMem = new Memory((int) scp.getTotalBackingStoreSize(), (int) scp.getTotalBackingStoreSize());
final Runnable runner = new Runnable() {
@Override
public void run() {
handleAsyncEvent();
}
};
thread = new RtThread(priority.getPriority(), p, off) {
public void run() {
while (!MissionSequencer.terminationRequest) {
privMem.enter(runner);
waitForNextPeriod();
}
}
};
}
@SCJAllowed
@Override
@SCJRestricted(phase = INITIALIZATION)
public final void register() {
}
}
| true | true | public PeriodicEventHandler(PriorityParameters priority,
PeriodicParameters release, StorageParameters scp, String name) {
// TODO: what are we doing with this Managed thing?
super(priority, release, scp, name);
this.priority = priority;
start = (RelativeTime)release.getStart();
period = release.getPeriod();
// TODO scp
// this.tconf = tconf;
this.name = name;
int p = ((int) period.getMilliseconds()) * 1000
+ period.getNanoseconds() / 1000;
if(p < 0) { // Overflow
p = Integer.MAX_VALUE;
}
int off = ((int) start.getMilliseconds()) * 1000
+ start.getNanoseconds() / 1000;
if(off < 0) { // Overflow
off = Integer.MAX_VALUE;
}
// TODO: this is a very quick hack to get privat memory
// working. The StorageParameters is incomplete. Was this
// updated in the spec?
privMem = new Memory((int) scp.getTotalBackingStoreSize());
final Runnable runner = new Runnable() {
@Override
public void run() {
handleAsyncEvent();
}
};
thread = new RtThread(priority.getPriority(), p, off) {
public void run() {
while (!MissionSequencer.terminationRequest) {
privMem.enter(runner);
waitForNextPeriod();
}
}
};
}
| public PeriodicEventHandler(PriorityParameters priority,
PeriodicParameters release, StorageParameters scp, String name) {
// TODO: what are we doing with this Managed thing?
super(priority, release, scp, name);
this.priority = priority;
start = (RelativeTime)release.getStart();
period = release.getPeriod();
// TODO scp
// this.tconf = tconf;
this.name = name;
int p = ((int) period.getMilliseconds()) * 1000
+ period.getNanoseconds() / 1000;
if(p < 0) { // Overflow
p = Integer.MAX_VALUE;
}
int off = ((int) start.getMilliseconds()) * 1000
+ start.getNanoseconds() / 1000;
if(off < 0) { // Overflow
off = Integer.MAX_VALUE;
}
// TODO: this is a very quick hack to get privat memory
// working. The StorageParameters is incomplete. Was this
// updated in the spec?
privMem = new Memory((int) scp.getTotalBackingStoreSize(), (int) scp.getTotalBackingStoreSize());
final Runnable runner = new Runnable() {
@Override
public void run() {
handleAsyncEvent();
}
};
thread = new RtThread(priority.getPriority(), p, off) {
public void run() {
while (!MissionSequencer.terminationRequest) {
privMem.enter(runner);
waitForNextPeriod();
}
}
};
}
|
diff --git a/plugins/net.refractions.udig.legend/src/net/refractions/udig/legend/ui/LegendGraphic.java b/plugins/net.refractions.udig.legend/src/net/refractions/udig/legend/ui/LegendGraphic.java
index f3d3b5613..805e0c34f 100644
--- a/plugins/net.refractions.udig.legend/src/net/refractions/udig/legend/ui/LegendGraphic.java
+++ b/plugins/net.refractions.udig.legend/src/net/refractions/udig/legend/ui/LegendGraphic.java
@@ -1,395 +1,401 @@
/* uDig - User Friendly Desktop Internet GIS client
* http://udig.refractions.net
* (C) 2005, Refractions Research Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package net.refractions.udig.legend.ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.refractions.udig.mapgraphic.MapGraphic;
import net.refractions.udig.mapgraphic.MapGraphicContext;
import net.refractions.udig.mapgraphic.internal.MapGraphicResource;
import net.refractions.udig.mapgraphic.style.FontStyle;
import net.refractions.udig.mapgraphic.style.FontStyleContent;
import net.refractions.udig.mapgraphic.style.LocationStyleContent;
import net.refractions.udig.project.IBlackboard;
import net.refractions.udig.project.ILayer;
import net.refractions.udig.project.internal.Layer;
import net.refractions.udig.project.internal.StyleBlackboard;
import net.refractions.udig.project.ui.internal.LayerGeneratedGlyphDecorator;
import net.refractions.udig.ui.PlatformGIS;
import net.refractions.udig.ui.graphics.AWTSWTImageUtils;
import net.refractions.udig.ui.graphics.SLDs;
import net.refractions.udig.ui.graphics.ViewportGraphics;
import org.eclipse.jface.resource.ImageDescriptor;
import org.geotools.styling.FeatureTypeStyle;
import org.geotools.styling.Rule;
import org.geotools.styling.Style;
import org.opengis.coverage.grid.GridCoverage;
import org.opengis.feature.type.Name;
/**
* Draw a legend based on looking at the current list layer list.
* @author Amr
* @since 1.0.0
*/
public class LegendGraphic implements MapGraphic {
private int verticalMargin; //distance between border and icons/text
private int horizontalMargin; //distance between border and icons/text
private int verticalSpacing; //distance between layers
private int horizontalSpacing; //space between image and text
private Color foregroundColour;
private Color backgroundColour;
private int indentSize;
private int imageWidth;
private int imageHeight; //size of glyph image
public void draw( MapGraphicContext context ) {
IBlackboard blackboard = context.getLayer().getStyleBlackboard();
LegendStyle legendStyle = (LegendStyle) blackboard.get(LegendStyleContent.ID);
if (legendStyle == null) {
legendStyle = LegendStyleContent.createDefault();
blackboard.put(LegendStyleContent.ID, legendStyle);
}
Rectangle locationStyle = (Rectangle) blackboard.get(LocationStyleContent.ID);
if (locationStyle == null) {
locationStyle = new Rectangle(-1,-1,-1,-1);
blackboard.put(LocationStyleContent.ID, locationStyle);
}
FontStyle fontStyle = (FontStyle) blackboard.get(FontStyleContent.ID);
if( fontStyle==null ){
fontStyle = new FontStyle();
blackboard.put(FontStyleContent.ID, fontStyle);
}
this.backgroundColour = legendStyle.backgroundColour;
this.foregroundColour = legendStyle.foregroundColour;
this.horizontalMargin = legendStyle.horizontalMargin;
this.verticalMargin = legendStyle.verticalMargin;
this.horizontalSpacing = legendStyle.horizontalSpacing;
this.verticalSpacing = legendStyle.verticalSpacing;
this.indentSize = legendStyle.indentSize;
this.imageHeight = legendStyle.imageHeight;
this.imageWidth = legendStyle.imageWidth;
final ViewportGraphics graphics = context.getGraphics();
if(fontStyle.getFont()!=null){
graphics.setFont(fontStyle.getFont());
}
List<Map<ILayer, LegendEntry[]>> layers = new ArrayList<Map<ILayer, LegendEntry[]>>();
int longestRow = 0; //used to calculate the width of the graphic
final int[] numberOfEntries = new int[1]; //total number of entries to draw
numberOfEntries[0]=0;
/*
* Set up the layers that we want to draw so we can operate just on
* those ones. Layers at index 0 are on the bottom of the map, so we
* must iterate in reverse.
*
* While we are doing this, determine the longest row so we can properly
* draw the graphic's border.
*/
for (int i = context.getMapLayers().size() - 1; i >= 0; i--) {
ILayer layer = context.getMapLayers().get(i);
if (!(layer.getGeoResource() instanceof MapGraphicResource)
&& layer.isVisible()) {
if (layer.hasResource(MapGraphic.class)) {
//don't include mapgraphics
continue;
}
String layerName = layer.getName();
if (layerName == null){
layerName = null;
}
LegendEntry layerEntry = new LegendEntry(layerName);
FeatureTypeStyle[] styles = locateStyle(layer);
LegendEntry[] entries = null;
if (styles == null) {
// we should have a label but no style
entries = new LegendEntry[]{layerEntry};
}else{
List<Rule> rules = rules(styles);
int ruleCount = rules.size();
if (ruleCount == 1
&& layer.getGeoResource()
.canResolve(GridCoverage.class)) {
//grid coverage with single rule; lets see if it is a theming style
List<LegendEntry> cmEntries = ColorMapLegendCreator.findEntries(styles, new Dimension(imageWidth, imageHeight));
if (cmEntries != null){
cmEntries.add(0, layerEntry); //add layer legend entry
entries = cmEntries.toArray(new LegendEntry[cmEntries.size()]);
}
}
if (entries == null ){
List<LegendEntry> localEntries = new ArrayList<LegendEntry>();
if (ruleCount == 1){
//only one rule so apply this to the layer legend entry
layerEntry.setRule(rules.get(0));
}
localEntries.add(layerEntry); //add layer legend entry
if (ruleCount > 1){
//we have more than one rule so there is likely some
//themeing going on; add each of these rules
for (Rule rule : rules) {
LegendEntry rentry = new LegendEntry(rule);
localEntries.add(rentry);
}
}
entries = localEntries.toArray(new LegendEntry[localEntries.size()]);
}
}
layers.add(Collections.singletonMap(layer, entries));
//compute maximum length for each entry
for (int j = 0; j < entries.length ;j ++){
Rectangle2D bounds = graphics.getStringBounds(entries[j].getText());
int length = indentSize + imageWidth
+ horizontalSpacing + (int) bounds.getWidth();
if (length > longestRow) {
longestRow = length;
}
numberOfEntries[0]++;
}
}
}
if (numberOfEntries[0] == 0) {
//nothing to draw!
return;
}
final int rowHeight = Math.max(imageHeight, graphics.getFontHeight()); //space allocated to each layer
if (locationStyle.width == 0 || locationStyle.height == 0){
//we want to change the location style as needed
//but not change the saved one so we create a copy here
locationStyle = new Rectangle(locationStyle);
if (locationStyle.width == 0){
//we want to grow to whatever size we need
int width = longestRow+horizontalMargin*2;
locationStyle.width = width;
}
if (locationStyle.height == 0){
//we want to grow to whatever size we need
int height = rowHeight*numberOfEntries[0]+verticalMargin*2+verticalSpacing*(numberOfEntries[0]-1);
locationStyle.height = height;
}
}
//ensure box within the display
Dimension displaySize = context.getMapDisplay().getDisplaySize();
if (locationStyle.x < 0){
locationStyle.x = displaySize.width - locationStyle.width + locationStyle.x;
}
if ((locationStyle.x + locationStyle.width + 6) > displaySize.width ){
locationStyle.x = displaySize.width - locationStyle.width - 5;
}
if (locationStyle.y < 0){
locationStyle.y = displaySize.height - locationStyle.height - 5 + locationStyle.y;
}
if ((locationStyle.y + locationStyle.height + 6) > displaySize.height){
locationStyle.y = displaySize.height - locationStyle.height - 5;
}
graphics.setClip(new Rectangle(locationStyle.x, locationStyle.y, locationStyle.width+1, locationStyle.height+1));
/*
* Draw the box containing the layers/icons
*/
drawOutline(graphics, context, locationStyle);
/*
* Draw the layer names/icons
*/
final int[] rowsDrawn = new int[1];
rowsDrawn[0]=0;
final int[] x = new int[1];
x[0]=locationStyle.x + horizontalMargin;
final int[] y = new int[1];
y[0]=locationStyle.y + verticalMargin;
if(fontStyle.getFont()!=null){
graphics.setFont(fontStyle.getFont());
}
for( int i = 0; i < layers.size(); i++ ) {
Map<ILayer, LegendEntry[]> map = layers.get(i);
final ILayer layer = map.keySet().iterator().next();
final LegendEntry[] entries = map.values().iterator().next();
try{
layer.getGeoResources().get(0).getInfo(null);
}catch (Exception ex){}
PlatformGIS.syncInDisplayThread(new Runnable() {
public void run() {
for (int i = 0; i < entries.length; i++) {
BufferedImage awtIcon = null;
if (entries[i].getRule() != null) {
//generate icon from use
ImageDescriptor descriptor = LayerGeneratedGlyphDecorator.generateStyledIcon(layer,entries[i].getRule());
if (descriptor == null){
descriptor = LayerGeneratedGlyphDecorator.generateIcon((Layer)layer);
}
if (descriptor != null){
awtIcon = AWTSWTImageUtils.convertToAWT(descriptor.getImageData());
}
} else if (entries[i].getIcon() != null) {
//use set icon
awtIcon = AWTSWTImageUtils.convertToAWT(entries[i]
.getIcon().getImageData());
+ }else{
+ //no rule, no icon, try default for layer
+ ImageDescriptor descriptor = LayerGeneratedGlyphDecorator.generateIcon((Layer)layer);
+ if (descriptor != null){
+ awtIcon = AWTSWTImageUtils.convertToAWT(descriptor.getImageData());
+ }
}
drawRow(graphics, x[0], y[0], awtIcon, entries[i].getText(), i != 0);
y[0] += rowHeight;
if ((rowsDrawn[0] + 1) < numberOfEntries[0]) {
y[0] += verticalSpacing;
}
rowsDrawn[0]++;
}
}
});
}
//clear the clip so we don't affect other rendering processes
graphics.setClip(null);
}
private List<Rule> rules( FeatureTypeStyle[] styles ) {
List<Rule> rules = new ArrayList<Rule>();
for( FeatureTypeStyle featureTypeStyle : styles ) {
rules.addAll(featureTypeStyle.rules());
}
return rules;
}
private void drawRow(ViewportGraphics graphics, int x, int y,
RenderedImage icon, String text, boolean indent) {
Rectangle2D stringBounds = graphics.getStringBounds(text);
/*
* Center the smaller item (text or icon) according to the taller one.
*/
int textVerticalOffset = 0;
int iconVerticalOffset = 0;
if (imageHeight == (int) stringBounds.getHeight()) {
//items are the same height; do nothing.
} else if (imageHeight > (int) stringBounds.getHeight()) {
int difference = imageHeight - (int) stringBounds.getHeight();
textVerticalOffset = difference / 2;
} else if (imageHeight < (int) stringBounds.getHeight()){
int difference = (int) stringBounds.getHeight() - imageHeight;
iconVerticalOffset = difference / 2;
}
if (indent) {
x += indentSize;
}
if (icon != null) {
graphics.drawImage(icon, x, y+iconVerticalOffset);
x += imageWidth;
}
if (text != null && text.length() != 0) {
graphics.drawString(text,
x+horizontalMargin,
y+graphics.getFontAscent()+textVerticalOffset,
ViewportGraphics.ALIGN_LEFT,
ViewportGraphics.ALIGN_LEFT);
}
}
private FeatureTypeStyle[] locateStyle( ILayer layer ) {
StyleBlackboard blackboard = (StyleBlackboard) layer.getStyleBlackboard();
if (blackboard == null) {
return null;
}
Style sld = (Style) blackboard.lookup( Style.class );
if (sld == null) {
return null;
}
List<FeatureTypeStyle> styles = new ArrayList<FeatureTypeStyle>();
String layerTypeName = null;
if (layer.getSchema() != null && layer.getSchema().getTypeName() != null){
layerTypeName = layer.getSchema().getTypeName();
}
for (FeatureTypeStyle style : sld.featureTypeStyles()) {
Set<Name> names = style.featureTypeNames();
if (names.size() == 0){
styles.add(style);
}else{
for (Name name : names){
if (name.getLocalPart().equals(SLDs.GENERIC_FEATURE_TYPENAME) ||
(layerTypeName != null && layerTypeName.equals(name.getLocalPart()))){
styles.add(style);
break;
}
}
}
}
return styles.toArray(new FeatureTypeStyle[0]);
}
private void drawOutline(ViewportGraphics graphics, MapGraphicContext context, Rectangle locationStyle) {
Rectangle outline = new Rectangle(locationStyle.x, locationStyle.y, locationStyle.width, locationStyle.height);
// reserve this area free of labels!
context.getLabelPainter().put( outline );
graphics.setColor(backgroundColour);
graphics.fill(outline);
graphics.setColor(foregroundColour);
graphics.setBackground(backgroundColour);
graphics.draw(outline);
}
}
| true | true | public void draw( MapGraphicContext context ) {
IBlackboard blackboard = context.getLayer().getStyleBlackboard();
LegendStyle legendStyle = (LegendStyle) blackboard.get(LegendStyleContent.ID);
if (legendStyle == null) {
legendStyle = LegendStyleContent.createDefault();
blackboard.put(LegendStyleContent.ID, legendStyle);
}
Rectangle locationStyle = (Rectangle) blackboard.get(LocationStyleContent.ID);
if (locationStyle == null) {
locationStyle = new Rectangle(-1,-1,-1,-1);
blackboard.put(LocationStyleContent.ID, locationStyle);
}
FontStyle fontStyle = (FontStyle) blackboard.get(FontStyleContent.ID);
if( fontStyle==null ){
fontStyle = new FontStyle();
blackboard.put(FontStyleContent.ID, fontStyle);
}
this.backgroundColour = legendStyle.backgroundColour;
this.foregroundColour = legendStyle.foregroundColour;
this.horizontalMargin = legendStyle.horizontalMargin;
this.verticalMargin = legendStyle.verticalMargin;
this.horizontalSpacing = legendStyle.horizontalSpacing;
this.verticalSpacing = legendStyle.verticalSpacing;
this.indentSize = legendStyle.indentSize;
this.imageHeight = legendStyle.imageHeight;
this.imageWidth = legendStyle.imageWidth;
final ViewportGraphics graphics = context.getGraphics();
if(fontStyle.getFont()!=null){
graphics.setFont(fontStyle.getFont());
}
List<Map<ILayer, LegendEntry[]>> layers = new ArrayList<Map<ILayer, LegendEntry[]>>();
int longestRow = 0; //used to calculate the width of the graphic
final int[] numberOfEntries = new int[1]; //total number of entries to draw
numberOfEntries[0]=0;
/*
* Set up the layers that we want to draw so we can operate just on
* those ones. Layers at index 0 are on the bottom of the map, so we
* must iterate in reverse.
*
* While we are doing this, determine the longest row so we can properly
* draw the graphic's border.
*/
for (int i = context.getMapLayers().size() - 1; i >= 0; i--) {
ILayer layer = context.getMapLayers().get(i);
if (!(layer.getGeoResource() instanceof MapGraphicResource)
&& layer.isVisible()) {
if (layer.hasResource(MapGraphic.class)) {
//don't include mapgraphics
continue;
}
String layerName = layer.getName();
if (layerName == null){
layerName = null;
}
LegendEntry layerEntry = new LegendEntry(layerName);
FeatureTypeStyle[] styles = locateStyle(layer);
LegendEntry[] entries = null;
if (styles == null) {
// we should have a label but no style
entries = new LegendEntry[]{layerEntry};
}else{
List<Rule> rules = rules(styles);
int ruleCount = rules.size();
if (ruleCount == 1
&& layer.getGeoResource()
.canResolve(GridCoverage.class)) {
//grid coverage with single rule; lets see if it is a theming style
List<LegendEntry> cmEntries = ColorMapLegendCreator.findEntries(styles, new Dimension(imageWidth, imageHeight));
if (cmEntries != null){
cmEntries.add(0, layerEntry); //add layer legend entry
entries = cmEntries.toArray(new LegendEntry[cmEntries.size()]);
}
}
if (entries == null ){
List<LegendEntry> localEntries = new ArrayList<LegendEntry>();
if (ruleCount == 1){
//only one rule so apply this to the layer legend entry
layerEntry.setRule(rules.get(0));
}
localEntries.add(layerEntry); //add layer legend entry
if (ruleCount > 1){
//we have more than one rule so there is likely some
//themeing going on; add each of these rules
for (Rule rule : rules) {
LegendEntry rentry = new LegendEntry(rule);
localEntries.add(rentry);
}
}
entries = localEntries.toArray(new LegendEntry[localEntries.size()]);
}
}
layers.add(Collections.singletonMap(layer, entries));
//compute maximum length for each entry
for (int j = 0; j < entries.length ;j ++){
Rectangle2D bounds = graphics.getStringBounds(entries[j].getText());
int length = indentSize + imageWidth
+ horizontalSpacing + (int) bounds.getWidth();
if (length > longestRow) {
longestRow = length;
}
numberOfEntries[0]++;
}
}
}
if (numberOfEntries[0] == 0) {
//nothing to draw!
return;
}
final int rowHeight = Math.max(imageHeight, graphics.getFontHeight()); //space allocated to each layer
if (locationStyle.width == 0 || locationStyle.height == 0){
//we want to change the location style as needed
//but not change the saved one so we create a copy here
locationStyle = new Rectangle(locationStyle);
if (locationStyle.width == 0){
//we want to grow to whatever size we need
int width = longestRow+horizontalMargin*2;
locationStyle.width = width;
}
if (locationStyle.height == 0){
//we want to grow to whatever size we need
int height = rowHeight*numberOfEntries[0]+verticalMargin*2+verticalSpacing*(numberOfEntries[0]-1);
locationStyle.height = height;
}
}
//ensure box within the display
Dimension displaySize = context.getMapDisplay().getDisplaySize();
if (locationStyle.x < 0){
locationStyle.x = displaySize.width - locationStyle.width + locationStyle.x;
}
if ((locationStyle.x + locationStyle.width + 6) > displaySize.width ){
locationStyle.x = displaySize.width - locationStyle.width - 5;
}
if (locationStyle.y < 0){
locationStyle.y = displaySize.height - locationStyle.height - 5 + locationStyle.y;
}
if ((locationStyle.y + locationStyle.height + 6) > displaySize.height){
locationStyle.y = displaySize.height - locationStyle.height - 5;
}
graphics.setClip(new Rectangle(locationStyle.x, locationStyle.y, locationStyle.width+1, locationStyle.height+1));
/*
* Draw the box containing the layers/icons
*/
drawOutline(graphics, context, locationStyle);
/*
* Draw the layer names/icons
*/
final int[] rowsDrawn = new int[1];
rowsDrawn[0]=0;
final int[] x = new int[1];
x[0]=locationStyle.x + horizontalMargin;
final int[] y = new int[1];
y[0]=locationStyle.y + verticalMargin;
if(fontStyle.getFont()!=null){
graphics.setFont(fontStyle.getFont());
}
for( int i = 0; i < layers.size(); i++ ) {
Map<ILayer, LegendEntry[]> map = layers.get(i);
final ILayer layer = map.keySet().iterator().next();
final LegendEntry[] entries = map.values().iterator().next();
try{
layer.getGeoResources().get(0).getInfo(null);
}catch (Exception ex){}
PlatformGIS.syncInDisplayThread(new Runnable() {
public void run() {
for (int i = 0; i < entries.length; i++) {
BufferedImage awtIcon = null;
if (entries[i].getRule() != null) {
//generate icon from use
ImageDescriptor descriptor = LayerGeneratedGlyphDecorator.generateStyledIcon(layer,entries[i].getRule());
if (descriptor == null){
descriptor = LayerGeneratedGlyphDecorator.generateIcon((Layer)layer);
}
if (descriptor != null){
awtIcon = AWTSWTImageUtils.convertToAWT(descriptor.getImageData());
}
} else if (entries[i].getIcon() != null) {
//use set icon
awtIcon = AWTSWTImageUtils.convertToAWT(entries[i]
.getIcon().getImageData());
}
drawRow(graphics, x[0], y[0], awtIcon, entries[i].getText(), i != 0);
y[0] += rowHeight;
if ((rowsDrawn[0] + 1) < numberOfEntries[0]) {
y[0] += verticalSpacing;
}
rowsDrawn[0]++;
}
}
});
}
//clear the clip so we don't affect other rendering processes
graphics.setClip(null);
}
| public void draw( MapGraphicContext context ) {
IBlackboard blackboard = context.getLayer().getStyleBlackboard();
LegendStyle legendStyle = (LegendStyle) blackboard.get(LegendStyleContent.ID);
if (legendStyle == null) {
legendStyle = LegendStyleContent.createDefault();
blackboard.put(LegendStyleContent.ID, legendStyle);
}
Rectangle locationStyle = (Rectangle) blackboard.get(LocationStyleContent.ID);
if (locationStyle == null) {
locationStyle = new Rectangle(-1,-1,-1,-1);
blackboard.put(LocationStyleContent.ID, locationStyle);
}
FontStyle fontStyle = (FontStyle) blackboard.get(FontStyleContent.ID);
if( fontStyle==null ){
fontStyle = new FontStyle();
blackboard.put(FontStyleContent.ID, fontStyle);
}
this.backgroundColour = legendStyle.backgroundColour;
this.foregroundColour = legendStyle.foregroundColour;
this.horizontalMargin = legendStyle.horizontalMargin;
this.verticalMargin = legendStyle.verticalMargin;
this.horizontalSpacing = legendStyle.horizontalSpacing;
this.verticalSpacing = legendStyle.verticalSpacing;
this.indentSize = legendStyle.indentSize;
this.imageHeight = legendStyle.imageHeight;
this.imageWidth = legendStyle.imageWidth;
final ViewportGraphics graphics = context.getGraphics();
if(fontStyle.getFont()!=null){
graphics.setFont(fontStyle.getFont());
}
List<Map<ILayer, LegendEntry[]>> layers = new ArrayList<Map<ILayer, LegendEntry[]>>();
int longestRow = 0; //used to calculate the width of the graphic
final int[] numberOfEntries = new int[1]; //total number of entries to draw
numberOfEntries[0]=0;
/*
* Set up the layers that we want to draw so we can operate just on
* those ones. Layers at index 0 are on the bottom of the map, so we
* must iterate in reverse.
*
* While we are doing this, determine the longest row so we can properly
* draw the graphic's border.
*/
for (int i = context.getMapLayers().size() - 1; i >= 0; i--) {
ILayer layer = context.getMapLayers().get(i);
if (!(layer.getGeoResource() instanceof MapGraphicResource)
&& layer.isVisible()) {
if (layer.hasResource(MapGraphic.class)) {
//don't include mapgraphics
continue;
}
String layerName = layer.getName();
if (layerName == null){
layerName = null;
}
LegendEntry layerEntry = new LegendEntry(layerName);
FeatureTypeStyle[] styles = locateStyle(layer);
LegendEntry[] entries = null;
if (styles == null) {
// we should have a label but no style
entries = new LegendEntry[]{layerEntry};
}else{
List<Rule> rules = rules(styles);
int ruleCount = rules.size();
if (ruleCount == 1
&& layer.getGeoResource()
.canResolve(GridCoverage.class)) {
//grid coverage with single rule; lets see if it is a theming style
List<LegendEntry> cmEntries = ColorMapLegendCreator.findEntries(styles, new Dimension(imageWidth, imageHeight));
if (cmEntries != null){
cmEntries.add(0, layerEntry); //add layer legend entry
entries = cmEntries.toArray(new LegendEntry[cmEntries.size()]);
}
}
if (entries == null ){
List<LegendEntry> localEntries = new ArrayList<LegendEntry>();
if (ruleCount == 1){
//only one rule so apply this to the layer legend entry
layerEntry.setRule(rules.get(0));
}
localEntries.add(layerEntry); //add layer legend entry
if (ruleCount > 1){
//we have more than one rule so there is likely some
//themeing going on; add each of these rules
for (Rule rule : rules) {
LegendEntry rentry = new LegendEntry(rule);
localEntries.add(rentry);
}
}
entries = localEntries.toArray(new LegendEntry[localEntries.size()]);
}
}
layers.add(Collections.singletonMap(layer, entries));
//compute maximum length for each entry
for (int j = 0; j < entries.length ;j ++){
Rectangle2D bounds = graphics.getStringBounds(entries[j].getText());
int length = indentSize + imageWidth
+ horizontalSpacing + (int) bounds.getWidth();
if (length > longestRow) {
longestRow = length;
}
numberOfEntries[0]++;
}
}
}
if (numberOfEntries[0] == 0) {
//nothing to draw!
return;
}
final int rowHeight = Math.max(imageHeight, graphics.getFontHeight()); //space allocated to each layer
if (locationStyle.width == 0 || locationStyle.height == 0){
//we want to change the location style as needed
//but not change the saved one so we create a copy here
locationStyle = new Rectangle(locationStyle);
if (locationStyle.width == 0){
//we want to grow to whatever size we need
int width = longestRow+horizontalMargin*2;
locationStyle.width = width;
}
if (locationStyle.height == 0){
//we want to grow to whatever size we need
int height = rowHeight*numberOfEntries[0]+verticalMargin*2+verticalSpacing*(numberOfEntries[0]-1);
locationStyle.height = height;
}
}
//ensure box within the display
Dimension displaySize = context.getMapDisplay().getDisplaySize();
if (locationStyle.x < 0){
locationStyle.x = displaySize.width - locationStyle.width + locationStyle.x;
}
if ((locationStyle.x + locationStyle.width + 6) > displaySize.width ){
locationStyle.x = displaySize.width - locationStyle.width - 5;
}
if (locationStyle.y < 0){
locationStyle.y = displaySize.height - locationStyle.height - 5 + locationStyle.y;
}
if ((locationStyle.y + locationStyle.height + 6) > displaySize.height){
locationStyle.y = displaySize.height - locationStyle.height - 5;
}
graphics.setClip(new Rectangle(locationStyle.x, locationStyle.y, locationStyle.width+1, locationStyle.height+1));
/*
* Draw the box containing the layers/icons
*/
drawOutline(graphics, context, locationStyle);
/*
* Draw the layer names/icons
*/
final int[] rowsDrawn = new int[1];
rowsDrawn[0]=0;
final int[] x = new int[1];
x[0]=locationStyle.x + horizontalMargin;
final int[] y = new int[1];
y[0]=locationStyle.y + verticalMargin;
if(fontStyle.getFont()!=null){
graphics.setFont(fontStyle.getFont());
}
for( int i = 0; i < layers.size(); i++ ) {
Map<ILayer, LegendEntry[]> map = layers.get(i);
final ILayer layer = map.keySet().iterator().next();
final LegendEntry[] entries = map.values().iterator().next();
try{
layer.getGeoResources().get(0).getInfo(null);
}catch (Exception ex){}
PlatformGIS.syncInDisplayThread(new Runnable() {
public void run() {
for (int i = 0; i < entries.length; i++) {
BufferedImage awtIcon = null;
if (entries[i].getRule() != null) {
//generate icon from use
ImageDescriptor descriptor = LayerGeneratedGlyphDecorator.generateStyledIcon(layer,entries[i].getRule());
if (descriptor == null){
descriptor = LayerGeneratedGlyphDecorator.generateIcon((Layer)layer);
}
if (descriptor != null){
awtIcon = AWTSWTImageUtils.convertToAWT(descriptor.getImageData());
}
} else if (entries[i].getIcon() != null) {
//use set icon
awtIcon = AWTSWTImageUtils.convertToAWT(entries[i]
.getIcon().getImageData());
}else{
//no rule, no icon, try default for layer
ImageDescriptor descriptor = LayerGeneratedGlyphDecorator.generateIcon((Layer)layer);
if (descriptor != null){
awtIcon = AWTSWTImageUtils.convertToAWT(descriptor.getImageData());
}
}
drawRow(graphics, x[0], y[0], awtIcon, entries[i].getText(), i != 0);
y[0] += rowHeight;
if ((rowsDrawn[0] + 1) < numberOfEntries[0]) {
y[0] += verticalSpacing;
}
rowsDrawn[0]++;
}
}
});
}
//clear the clip so we don't affect other rendering processes
graphics.setClip(null);
}
|
diff --git a/src/main/java/com/ibm/opensocial/landos/email/EmailRenderer.java b/src/main/java/com/ibm/opensocial/landos/email/EmailRenderer.java
index 6a58d88..6168805 100644
--- a/src/main/java/com/ibm/opensocial/landos/email/EmailRenderer.java
+++ b/src/main/java/com/ibm/opensocial/landos/email/EmailRenderer.java
@@ -1,52 +1,52 @@
package com.ibm.opensocial.landos.email;
import java.text.DateFormat;
import java.util.Date;
import java.util.Scanner;
import javax.el.ExpressionFactory;
import de.odysseus.el.util.SimpleContext;
public class EmailRenderer {
private final ExpressionFactory factory;
private final SimpleContext context;
- public EmailRenderer(long id, long start, long end, boolean isTest) {
+ public EmailRenderer(Integer id, long start, long end, boolean isTest) {
factory = ExpressionFactory.newInstance();
context = new SimpleContext();
- context.setVariable("id", factory.createValueExpression(id, long.class));
+ context.setVariable("id", factory.createValueExpression(id, Integer.class));
context.setVariable("start", factory.createValueExpression(new Date(start), Date.class));
context.setVariable("end", factory.createValueExpression(new Date(end), Date.class));
context.setVariable("isTest", factory.createValueExpression(isTest, boolean.class));
context.setVariable("dFormat", factory.createValueExpression(DateFormat.getDateInstance(DateFormat.FULL), DateFormat.class));
context.setVariable("tFormat", factory.createValueExpression(DateFormat.getTimeInstance(), DateFormat.class));
context.setVariable("dtFormat", factory.createValueExpression(DateFormat.getDateTimeInstance(), DateFormat.class));
context.setVariable("subject", factory.createValueExpression(getEmailSubject(), String.class));
}
public String renderHtmlEmail() {
return render(getTemplate("email.html"));
}
public String renderTextEmail() {
return render(getTemplate("email.txt"));
}
public String getEmailSubject() {
return render(getTemplate("subject.txt"));
}
private String getTemplate(String template) {
return new Scanner(EmailRenderer.class.getResourceAsStream(template), "UTF-8")
.useDelimiter("\\z").next();
}
private String render(String template) {
return (String) factory.createValueExpression(context, template, String.class).getValue(context);
}
}
| false | true | public EmailRenderer(long id, long start, long end, boolean isTest) {
factory = ExpressionFactory.newInstance();
context = new SimpleContext();
context.setVariable("id", factory.createValueExpression(id, long.class));
context.setVariable("start", factory.createValueExpression(new Date(start), Date.class));
context.setVariable("end", factory.createValueExpression(new Date(end), Date.class));
context.setVariable("isTest", factory.createValueExpression(isTest, boolean.class));
context.setVariable("dFormat", factory.createValueExpression(DateFormat.getDateInstance(DateFormat.FULL), DateFormat.class));
context.setVariable("tFormat", factory.createValueExpression(DateFormat.getTimeInstance(), DateFormat.class));
context.setVariable("dtFormat", factory.createValueExpression(DateFormat.getDateTimeInstance(), DateFormat.class));
context.setVariable("subject", factory.createValueExpression(getEmailSubject(), String.class));
}
| public EmailRenderer(Integer id, long start, long end, boolean isTest) {
factory = ExpressionFactory.newInstance();
context = new SimpleContext();
context.setVariable("id", factory.createValueExpression(id, Integer.class));
context.setVariable("start", factory.createValueExpression(new Date(start), Date.class));
context.setVariable("end", factory.createValueExpression(new Date(end), Date.class));
context.setVariable("isTest", factory.createValueExpression(isTest, boolean.class));
context.setVariable("dFormat", factory.createValueExpression(DateFormat.getDateInstance(DateFormat.FULL), DateFormat.class));
context.setVariable("tFormat", factory.createValueExpression(DateFormat.getTimeInstance(), DateFormat.class));
context.setVariable("dtFormat", factory.createValueExpression(DateFormat.getDateTimeInstance(), DateFormat.class));
context.setVariable("subject", factory.createValueExpression(getEmailSubject(), String.class));
}
|
diff --git a/plugins/org.eclipse.tm.tcf/src/org/eclipse/tm/tcf/Activator.java b/plugins/org.eclipse.tm.tcf/src/org/eclipse/tm/tcf/Activator.java
index 87c990c12..53532ecd8 100644
--- a/plugins/org.eclipse.tm.tcf/src/org/eclipse/tm/tcf/Activator.java
+++ b/plugins/org.eclipse.tm.tcf/src/org/eclipse/tm/tcf/Activator.java
@@ -1,114 +1,114 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 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:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tm.tcf;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.eclipse.tm.tcf.protocol.ILogger;
import org.eclipse.tm.tcf.protocol.Protocol;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends Plugin {
public static final String PLUGIN_ID = "org.eclipse.tm.tcf";
private static Activator plugin;
private static boolean debug;
private static final EventQueue queue = new EventQueue();
private static final BundleListener bundle_listener = new BundleListener() {
private boolean started = false;
public void bundleChanged(BundleEvent event) {
if (plugin != null && !started && event.getBundle() == plugin.getBundle() &&
plugin.getBundle().getState() == Bundle.ACTIVE) {
queue.start();
started = true;
}
}
};
public Activator() {
plugin = this;
}
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
debug = Platform.inDebugMode();
Protocol.setLogger(new ILogger() {
public void log(String msg, Throwable x) {
if (debug) {
System.err.println(msg);
x.printStackTrace();
}
if (plugin != null && getLog() != null) {
getLog().log(new Status(IStatus.ERROR,
getBundle().getSymbolicName(), IStatus.OK, msg, x));
}
}
});
Protocol.setEventQueue(queue);
Protocol.invokeLater(new Runnable() {
public void run() {
runTCFStartup();
}
});
context.addBundleListener(bundle_listener);
}
@Override
public void stop(BundleContext context) throws Exception {
context.removeBundleListener(bundle_listener);
queue.shutdown();
plugin = null;
super.stop(context);
}
@SuppressWarnings("unchecked")
private void runTCFStartup() {
try {
IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(PLUGIN_ID, "startup");
IExtension[] extensions = point.getExtensions();
for (int i = 0; i < extensions.length; i++) {
try {
Bundle bundle = Platform.getBundle(extensions[i].getNamespaceIdentifier());
- bundle.start();
+ bundle.start(Bundle.START_TRANSIENT);
IConfigurationElement[] e = extensions[i].getConfigurationElements();
for (int j = 0; j < e.length; j++) {
String nm = e[j].getName();
if (nm.equals("class")) { //$NON-NLS-1$
Class c = bundle.loadClass(e[j].getAttribute("name")); //$NON-NLS-1$
Class.forName(c.getName(), true, c.getClassLoader());
}
}
}
catch (Throwable x) {
Protocol.log("TCF startup error", x);
}
}
}
catch (Exception x) {
Protocol.log("TCF startup error", x);
}
}
}
| true | true | private void runTCFStartup() {
try {
IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(PLUGIN_ID, "startup");
IExtension[] extensions = point.getExtensions();
for (int i = 0; i < extensions.length; i++) {
try {
Bundle bundle = Platform.getBundle(extensions[i].getNamespaceIdentifier());
bundle.start();
IConfigurationElement[] e = extensions[i].getConfigurationElements();
for (int j = 0; j < e.length; j++) {
String nm = e[j].getName();
if (nm.equals("class")) { //$NON-NLS-1$
Class c = bundle.loadClass(e[j].getAttribute("name")); //$NON-NLS-1$
Class.forName(c.getName(), true, c.getClassLoader());
}
}
}
catch (Throwable x) {
Protocol.log("TCF startup error", x);
}
}
}
catch (Exception x) {
Protocol.log("TCF startup error", x);
}
}
| private void runTCFStartup() {
try {
IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(PLUGIN_ID, "startup");
IExtension[] extensions = point.getExtensions();
for (int i = 0; i < extensions.length; i++) {
try {
Bundle bundle = Platform.getBundle(extensions[i].getNamespaceIdentifier());
bundle.start(Bundle.START_TRANSIENT);
IConfigurationElement[] e = extensions[i].getConfigurationElements();
for (int j = 0; j < e.length; j++) {
String nm = e[j].getName();
if (nm.equals("class")) { //$NON-NLS-1$
Class c = bundle.loadClass(e[j].getAttribute("name")); //$NON-NLS-1$
Class.forName(c.getName(), true, c.getClassLoader());
}
}
}
catch (Throwable x) {
Protocol.log("TCF startup error", x);
}
}
}
catch (Exception x) {
Protocol.log("TCF startup error", x);
}
}
|
diff --git a/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/layer/AbstractLayer.java b/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/layer/AbstractLayer.java
index 85f38432..f8d4e5a7 100644
--- a/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/layer/AbstractLayer.java
+++ b/org.eclipse.nebula.widgets.nattable.core/src/org/eclipse/nebula/widgets/nattable/layer/AbstractLayer.java
@@ -1,331 +1,331 @@
/*******************************************************************************
* Copyright (c) 2012 Original authors 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:
* Original authors and others - initial API and implementation
******************************************************************************/
package org.eclipse.nebula.widgets.nattable.layer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.nebula.widgets.nattable.command.ILayerCommand;
import org.eclipse.nebula.widgets.nattable.command.ILayerCommandHandler;
import org.eclipse.nebula.widgets.nattable.config.CellConfigAttributes;
import org.eclipse.nebula.widgets.nattable.config.ConfigRegistry;
import org.eclipse.nebula.widgets.nattable.config.IConfigRegistry;
import org.eclipse.nebula.widgets.nattable.config.IConfiguration;
import org.eclipse.nebula.widgets.nattable.layer.cell.IConfigLabelAccumulator;
import org.eclipse.nebula.widgets.nattable.layer.cell.ILayerCell;
import org.eclipse.nebula.widgets.nattable.layer.cell.LayerCell;
import org.eclipse.nebula.widgets.nattable.layer.event.ILayerEvent;
import org.eclipse.nebula.widgets.nattable.layer.event.ILayerEventHandler;
import org.eclipse.nebula.widgets.nattable.painter.cell.ICellPainter;
import org.eclipse.nebula.widgets.nattable.painter.layer.GridLineCellLayerPainter;
import org.eclipse.nebula.widgets.nattable.painter.layer.ILayerPainter;
import org.eclipse.nebula.widgets.nattable.persistence.IPersistable;
import org.eclipse.nebula.widgets.nattable.style.DisplayMode;
import org.eclipse.nebula.widgets.nattable.ui.binding.UiBindingRegistry;
import org.eclipse.nebula.widgets.nattable.util.IClientAreaProvider;
/**
* Base layer implementation with common methods for managing listeners and caching, etc.
*/
public abstract class AbstractLayer implements ILayer {
private String regionName;
protected ILayerPainter layerPainter;
private IClientAreaProvider clientAreaProvider = IClientAreaProvider.DEFAULT;
private IConfigLabelAccumulator configLabelAccumulator;
private final Map<Class<? extends ILayerCommand>, ILayerCommandHandler<? extends ILayerCommand>> commandHandlers = new LinkedHashMap<Class<? extends ILayerCommand>, ILayerCommandHandler<? extends ILayerCommand>>();
private final Map<Class<? extends ILayerEvent>, ILayerEventHandler<? extends ILayerEvent>> eventHandlers = new HashMap<Class<? extends ILayerEvent>, ILayerEventHandler<? extends ILayerEvent>>();
private final List<IPersistable> persistables = new LinkedList<IPersistable>();
private final Set<ILayerListener> listeners = new LinkedHashSet<ILayerListener>();
private final Collection<IConfiguration> configurations = new LinkedList<IConfiguration>();
// Dispose
public void dispose() {
}
// Regions
public LabelStack getRegionLabelsByXY(int x, int y) {
LabelStack regionLabels = new LabelStack();
if (regionName != null) {
regionLabels.addLabel(regionName);
}
return regionLabels;
}
public String getRegionName() {
return regionName;
}
public void setRegionName(String regionName) {
this.regionName = regionName;
}
// Config lables
public LabelStack getConfigLabelsByPosition(int columnPosition, int rowPosition) {
LabelStack configLabels = new LabelStack();
if (configLabelAccumulator != null) {
configLabelAccumulator.accumulateConfigLabels(configLabels, columnPosition, rowPosition);
}
if (regionName != null) {
configLabels.addLabel(regionName);
}
return configLabels;
}
public IConfigLabelAccumulator getConfigLabelAccumulator() {
return configLabelAccumulator;
}
public void setConfigLabelAccumulator(IConfigLabelAccumulator cellLabelAccumulator) {
this.configLabelAccumulator = cellLabelAccumulator;
}
// Persistence
public void saveState(String prefix, Properties properties) {
for (IPersistable persistable : persistables) {
persistable.saveState(prefix, properties);
}
}
public void loadState(String prefix, Properties properties) {
for (IPersistable persistable : persistables) {
persistable.loadState(prefix, properties);
}
}
public void registerPersistable(IPersistable persistable){
persistables.add(persistable);
}
public void unregisterPersistable(IPersistable persistable){
persistables.remove(persistable);
}
// Configuration
public void addConfiguration(IConfiguration configuration) {
configurations.add(configuration);
}
public void clearConfiguration() {
configurations.clear();
}
public void configure(ConfigRegistry configRegistry, UiBindingRegistry uiBindingRegistry) {
for (IConfiguration configuration : configurations) {
configuration.configureLayer(this);
configuration.configureRegistry(configRegistry);
configuration.configureUiBindings(uiBindingRegistry);
}
}
// Commands
@SuppressWarnings("unchecked")
public boolean doCommand(ILayerCommand command) {
for (Class<? extends ILayerCommand> commandClass : commandHandlers.keySet()) {
if (commandClass.isInstance(command)) {
ILayerCommandHandler commandHandler = commandHandlers.get(commandClass);
if (commandHandler.doCommand(this, command)) {
return true;
}
}
}
return false;
}
// Command handlers
/**
* Layers should use this method to register their command handlers
* and call it from their constructor. This allows easy overriding if
* required of command handlers
*/
protected void registerCommandHandlers() {
// No op
}
public void registerCommandHandler(ILayerCommandHandler<?> commandHandler) {
commandHandlers.put(commandHandler.getCommandClass(), commandHandler);
}
public void unregisterCommandHandler(Class<? extends ILayerCommand> commandClass) {
commandHandlers.remove(commandClass);
}
// Events
public void addLayerListener(ILayerListener listener) {
listeners.add(listener);
}
public void removeLayerListener(ILayerListener listener) {
listeners.remove(listener);
}
public boolean hasLayerListener(Class<? extends ILayerListener> layerListenerClass) {
for (ILayerListener listener : listeners) {
if (listener.getClass().equals(layerListenerClass)) {
return true;
}
}
return false;
}
/**
* Handle layer event notification. Convert it to your context
* and propagate <i>UP</i>.
*
* If you override this method you <strong>MUST NOT FORGET</strong> to raise
* the event up the layer stack by calling <code>super.fireLayerEvent(event)</code>
* - unless you plan to eat the event yourself.
**/
@SuppressWarnings("unchecked")
public void handleLayerEvent(ILayerEvent event) {
for (Class<? extends ILayerEvent> eventClass : eventHandlers.keySet()) {
if (eventClass.isInstance(event)) {
ILayerEventHandler eventHandler = eventHandlers.get(eventClass);
eventHandler.handleLayerEvent(event);
}
}
// Pass on the event to our parent
if (event.convertToLocal(this)) {
fireLayerEvent(event);
}
}
public void registerEventHandler(ILayerEventHandler<?> eventHandler) {
eventHandlers.put(eventHandler.getLayerEventClass(), eventHandler);
}
/**
* Pass the event to all the {@link ILayerListener} registered on this layer.
* A cloned copy is passed to each listener.
*/
public void fireLayerEvent(ILayerEvent event) {
if (listeners.size() > 0) {
Iterator<ILayerListener> it = listeners.iterator();
boolean isLastListener = false;
do {
ILayerListener l = it.next();
isLastListener = !it.hasNext(); // Lookahead
// Fire cloned event to first n-1 listeners; fire original event to last listener
ILayerEvent eventToFire = isLastListener ? event : event.cloneEvent();
l.handleLayerEvent(eventToFire);
} while (!isLastListener);
}
}
/**
* @return {@link ILayerPainter}. Defaults to {@link GridLineCellLayerPainter}
*/
public ILayerPainter getLayerPainter() {
if (layerPainter == null) {
layerPainter = new GridLineCellLayerPainter();
}
return layerPainter;
}
protected void setLayerPainter(ILayerPainter layerPainter) {
this.layerPainter = layerPainter;
}
// Client area
public IClientAreaProvider getClientAreaProvider() {
return clientAreaProvider;
}
public void setClientAreaProvider(IClientAreaProvider clientAreaProvider) {
this.clientAreaProvider = clientAreaProvider;
}
@Override
public String toString() {
return getClass().getSimpleName();
}
public ILayerCell getCellByPosition(int columnPosition, int rowPosition) {
if (columnPosition < 0 || columnPosition >= getColumnCount()
|| rowPosition < 0 || rowPosition >= getRowCount()) {
return null;
}
return new LayerCell(this, columnPosition, rowPosition);
}
public Rectangle getBoundsByPosition(int columnPosition, int rowPosition) {
ILayerCell cell = getCellByPosition(columnPosition, rowPosition);
ILayer cellLayer = cell.getLayer();
int xOffset = -1;
int yOffset = -1;
int width = 0;
int height = 0;
{ int column = cell.getOriginColumnPosition();
int end = column + cell.getColumnSpan();
for (; column < end; column++) {
int columnOffset = cellLayer.getStartXOfColumnPosition(column);
- if (columnOffset >= 0) {
+ if (column < cellLayer.getColumnCount()) {
xOffset = columnOffset;
break;
}
}
for (; column < end; column++) {
width += cellLayer.getColumnWidthByPosition(column);
}
}
{ int row = cell.getOriginRowPosition();
int end = row + cell.getRowSpan();
for (; row < end; row++) {
int rowOffset = cellLayer.getStartYOfRowPosition(row);
- if (rowOffset >= 0) {
+ if (row < cellLayer.getRowCount()) {
yOffset = rowOffset;
break;
}
}
for (; row < end; row++) {
height += cellLayer.getRowHeightByPosition(row);
}
}
- return (xOffset >= 0 && yOffset >= 0) ? new Rectangle(xOffset, yOffset, width, height) : null;
+ return new Rectangle(xOffset, yOffset, width, height);
}
public String getDisplayModeByPosition(int columnPosition, int rowPosition) {
return DisplayMode.NORMAL;
}
public ICellPainter getCellPainter(int columnPosition, int rowPosition, ILayerCell cell, IConfigRegistry configRegistry) {
return configRegistry.getConfigAttribute(CellConfigAttributes.CELL_PAINTER, cell.getDisplayMode(), cell.getConfigLabels().getLabels());
}
}
| false | true | public Rectangle getBoundsByPosition(int columnPosition, int rowPosition) {
ILayerCell cell = getCellByPosition(columnPosition, rowPosition);
ILayer cellLayer = cell.getLayer();
int xOffset = -1;
int yOffset = -1;
int width = 0;
int height = 0;
{ int column = cell.getOriginColumnPosition();
int end = column + cell.getColumnSpan();
for (; column < end; column++) {
int columnOffset = cellLayer.getStartXOfColumnPosition(column);
if (columnOffset >= 0) {
xOffset = columnOffset;
break;
}
}
for (; column < end; column++) {
width += cellLayer.getColumnWidthByPosition(column);
}
}
{ int row = cell.getOriginRowPosition();
int end = row + cell.getRowSpan();
for (; row < end; row++) {
int rowOffset = cellLayer.getStartYOfRowPosition(row);
if (rowOffset >= 0) {
yOffset = rowOffset;
break;
}
}
for (; row < end; row++) {
height += cellLayer.getRowHeightByPosition(row);
}
}
return (xOffset >= 0 && yOffset >= 0) ? new Rectangle(xOffset, yOffset, width, height) : null;
}
| public Rectangle getBoundsByPosition(int columnPosition, int rowPosition) {
ILayerCell cell = getCellByPosition(columnPosition, rowPosition);
ILayer cellLayer = cell.getLayer();
int xOffset = -1;
int yOffset = -1;
int width = 0;
int height = 0;
{ int column = cell.getOriginColumnPosition();
int end = column + cell.getColumnSpan();
for (; column < end; column++) {
int columnOffset = cellLayer.getStartXOfColumnPosition(column);
if (column < cellLayer.getColumnCount()) {
xOffset = columnOffset;
break;
}
}
for (; column < end; column++) {
width += cellLayer.getColumnWidthByPosition(column);
}
}
{ int row = cell.getOriginRowPosition();
int end = row + cell.getRowSpan();
for (; row < end; row++) {
int rowOffset = cellLayer.getStartYOfRowPosition(row);
if (row < cellLayer.getRowCount()) {
yOffset = rowOffset;
break;
}
}
for (; row < end; row++) {
height += cellLayer.getRowHeightByPosition(row);
}
}
return new Rectangle(xOffset, yOffset, width, height);
}
|
diff --git a/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_bankickreason.java b/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_bankickreason.java
index ec6fac6..8993e3b 100644
--- a/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_bankickreason.java
+++ b/CommandsEX/src/com/github/zathrus_writer/commandsex/handlers/Handler_bankickreason.java
@@ -1,89 +1,89 @@
package com.github.zathrus_writer.commandsex.handlers;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerLoginEvent.Result;
import com.github.zathrus_writer.commandsex.CommandsEX;
import com.github.zathrus_writer.commandsex.SQLManager;
import static com.github.zathrus_writer.commandsex.Language._;
public class Handler_bankickreason implements Listener {
public Handler_bankickreason(){
CommandsEX.plugin.getServer().getPluginManager().registerEvents(this, CommandsEX.plugin);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerLogin(PlayerLoginEvent e){
if (e.getResult() == Result.KICK_BANNED){
if (CommandsEX.sqlEnabled) {
try {
Player player = e.getPlayer();
String pName = player.getName();
String kickReason = ChatColor.RED + _("bansHeader", pName) + ChatColor.AQUA + "\n" + _("bansReason", pName)
+ ChatColor.GOLD + "%reason%\n" + ChatColor.AQUA + _("bansExpires", pName) + ChatColor.GOLD + "%expire%\n"
+ ChatColor.AQUA + _("bansBanTime", pName) + ChatColor.GOLD + "%date% " + ChatColor.AQUA + _("by", pName)
+ ChatColor.GOLD + " %banner%";
ResultSet res = SQLManager.query_res("SELECT player_name, creation_date, expiration_date, creator, reason FROM " + SQLManager.prefix + "bans WHERE player_name = ? ORDER BY id_ban DESC LIMIT 1", player.getName());
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:s");
final String creation_date = dateFormat.format(res.getTimestamp("creation_date").getTime());
final String expiration_date = dateFormat.format(res.getTimestamp("expiration_date").getTime());
kickReason = kickReason.replaceFirst("%banner%", res.getString("creator"));
kickReason = kickReason.replaceFirst("%date%", creation_date);
if (res.getString("expiration_date").equals("0000-00-00 00:00:00")){
kickReason = kickReason.replaceFirst("%expire%", "NEVER");
} else {
Date d;
Date c = new Date();
try {
d = new Date(dateFormat.parse(res.getString("expiration_date")).getTime());
} catch (Throwable ex) {
d = new Date(res.getTimestamp("expiration_date").getTime());
}
Integer timeAll = (int) ((d.getTime() - c.getTime()) / 1000); // total ban time
Integer days = (int) Math.floor(timeAll / 86400);
Integer hours = (int) Math.floor((timeAll - (days * 86400)) / 3600);
Integer minutes = (int) Math.floor((timeAll - (days * 86400) - (hours * 3600)) / 60);
Integer seconds = (timeAll - (days * 86400) - (hours * 3600) - (minutes * 60));
kickReason = kickReason.replaceFirst("%expire%", expiration_date);
- kickReason = kickReason + "\n Remaining Time: " + (days != 0 ? days + " " + _("days", pName)
+ kickReason = kickReason + ChatColor.AQUA + "\n" + _("bansRemainingTime", pName) + ChatColor.GOLD + (days != 0 ? days + " " + _("days", pName)
+ " " : "") + (hours != 0 ? hours + " " + _("hours", pName) + " " : "")
+ (minutes != 0 ? minutes + " " + _("minutes", pName) + " " : "") + seconds
+ " " + _("seconds", pName);
}
String reason = res.getString("reason");
kickReason = kickReason.replaceFirst("%reason%", (!reason.equals("") ? reason : _("bansGenericReason", pName)));
e.setKickMessage(kickReason);
res.close();
} catch (SQLException ex){
if (CommandsEX.getConf().getBoolean("debugMode")){
ex.printStackTrace();
}
}
}
}
}
}
| true | true | public void onPlayerLogin(PlayerLoginEvent e){
if (e.getResult() == Result.KICK_BANNED){
if (CommandsEX.sqlEnabled) {
try {
Player player = e.getPlayer();
String pName = player.getName();
String kickReason = ChatColor.RED + _("bansHeader", pName) + ChatColor.AQUA + "\n" + _("bansReason", pName)
+ ChatColor.GOLD + "%reason%\n" + ChatColor.AQUA + _("bansExpires", pName) + ChatColor.GOLD + "%expire%\n"
+ ChatColor.AQUA + _("bansBanTime", pName) + ChatColor.GOLD + "%date% " + ChatColor.AQUA + _("by", pName)
+ ChatColor.GOLD + " %banner%";
ResultSet res = SQLManager.query_res("SELECT player_name, creation_date, expiration_date, creator, reason FROM " + SQLManager.prefix + "bans WHERE player_name = ? ORDER BY id_ban DESC LIMIT 1", player.getName());
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:s");
final String creation_date = dateFormat.format(res.getTimestamp("creation_date").getTime());
final String expiration_date = dateFormat.format(res.getTimestamp("expiration_date").getTime());
kickReason = kickReason.replaceFirst("%banner%", res.getString("creator"));
kickReason = kickReason.replaceFirst("%date%", creation_date);
if (res.getString("expiration_date").equals("0000-00-00 00:00:00")){
kickReason = kickReason.replaceFirst("%expire%", "NEVER");
} else {
Date d;
Date c = new Date();
try {
d = new Date(dateFormat.parse(res.getString("expiration_date")).getTime());
} catch (Throwable ex) {
d = new Date(res.getTimestamp("expiration_date").getTime());
}
Integer timeAll = (int) ((d.getTime() - c.getTime()) / 1000); // total ban time
Integer days = (int) Math.floor(timeAll / 86400);
Integer hours = (int) Math.floor((timeAll - (days * 86400)) / 3600);
Integer minutes = (int) Math.floor((timeAll - (days * 86400) - (hours * 3600)) / 60);
Integer seconds = (timeAll - (days * 86400) - (hours * 3600) - (minutes * 60));
kickReason = kickReason.replaceFirst("%expire%", expiration_date);
kickReason = kickReason + "\n Remaining Time: " + (days != 0 ? days + " " + _("days", pName)
+ " " : "") + (hours != 0 ? hours + " " + _("hours", pName) + " " : "")
+ (minutes != 0 ? minutes + " " + _("minutes", pName) + " " : "") + seconds
+ " " + _("seconds", pName);
}
String reason = res.getString("reason");
kickReason = kickReason.replaceFirst("%reason%", (!reason.equals("") ? reason : _("bansGenericReason", pName)));
e.setKickMessage(kickReason);
res.close();
} catch (SQLException ex){
if (CommandsEX.getConf().getBoolean("debugMode")){
ex.printStackTrace();
}
}
}
}
}
| public void onPlayerLogin(PlayerLoginEvent e){
if (e.getResult() == Result.KICK_BANNED){
if (CommandsEX.sqlEnabled) {
try {
Player player = e.getPlayer();
String pName = player.getName();
String kickReason = ChatColor.RED + _("bansHeader", pName) + ChatColor.AQUA + "\n" + _("bansReason", pName)
+ ChatColor.GOLD + "%reason%\n" + ChatColor.AQUA + _("bansExpires", pName) + ChatColor.GOLD + "%expire%\n"
+ ChatColor.AQUA + _("bansBanTime", pName) + ChatColor.GOLD + "%date% " + ChatColor.AQUA + _("by", pName)
+ ChatColor.GOLD + " %banner%";
ResultSet res = SQLManager.query_res("SELECT player_name, creation_date, expiration_date, creator, reason FROM " + SQLManager.prefix + "bans WHERE player_name = ? ORDER BY id_ban DESC LIMIT 1", player.getName());
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:s");
final String creation_date = dateFormat.format(res.getTimestamp("creation_date").getTime());
final String expiration_date = dateFormat.format(res.getTimestamp("expiration_date").getTime());
kickReason = kickReason.replaceFirst("%banner%", res.getString("creator"));
kickReason = kickReason.replaceFirst("%date%", creation_date);
if (res.getString("expiration_date").equals("0000-00-00 00:00:00")){
kickReason = kickReason.replaceFirst("%expire%", "NEVER");
} else {
Date d;
Date c = new Date();
try {
d = new Date(dateFormat.parse(res.getString("expiration_date")).getTime());
} catch (Throwable ex) {
d = new Date(res.getTimestamp("expiration_date").getTime());
}
Integer timeAll = (int) ((d.getTime() - c.getTime()) / 1000); // total ban time
Integer days = (int) Math.floor(timeAll / 86400);
Integer hours = (int) Math.floor((timeAll - (days * 86400)) / 3600);
Integer minutes = (int) Math.floor((timeAll - (days * 86400) - (hours * 3600)) / 60);
Integer seconds = (timeAll - (days * 86400) - (hours * 3600) - (minutes * 60));
kickReason = kickReason.replaceFirst("%expire%", expiration_date);
kickReason = kickReason + ChatColor.AQUA + "\n" + _("bansRemainingTime", pName) + ChatColor.GOLD + (days != 0 ? days + " " + _("days", pName)
+ " " : "") + (hours != 0 ? hours + " " + _("hours", pName) + " " : "")
+ (minutes != 0 ? minutes + " " + _("minutes", pName) + " " : "") + seconds
+ " " + _("seconds", pName);
}
String reason = res.getString("reason");
kickReason = kickReason.replaceFirst("%reason%", (!reason.equals("") ? reason : _("bansGenericReason", pName)));
e.setKickMessage(kickReason);
res.close();
} catch (SQLException ex){
if (CommandsEX.getConf().getBoolean("debugMode")){
ex.printStackTrace();
}
}
}
}
}
|
diff --git a/MayhemAndHell/src/com/friendlyblob/mayhemandhell/client/screens/GameScreen.java b/MayhemAndHell/src/com/friendlyblob/mayhemandhell/client/screens/GameScreen.java
index 090445e..c6afda8 100644
--- a/MayhemAndHell/src/com/friendlyblob/mayhemandhell/client/screens/GameScreen.java
+++ b/MayhemAndHell/src/com/friendlyblob/mayhemandhell/client/screens/GameScreen.java
@@ -1,199 +1,199 @@
package com.friendlyblob.mayhemandhell.client.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.HorizontalGroup;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.friendlyblob.mayhemandhell.client.MyGame;
import com.friendlyblob.mayhemandhell.client.entities.gui.EventNotifications;
import com.friendlyblob.mayhemandhell.client.entities.gui.GuiManager;
import com.friendlyblob.mayhemandhell.client.entities.gui.LiveNotifications;
import com.friendlyblob.mayhemandhell.client.gameworld.GameWorld;
import com.friendlyblob.mayhemandhell.client.helpers.Assets;
import com.friendlyblob.mayhemandhell.client.network.packets.client.ChatMessagePacket;
public class GameScreen extends BaseScreen{
private GameWorld gameWorld;
public LiveNotifications notifications;
public EventNotifications eventNotifications;
public GuiManager guiManager;
// Music stuff
private Music music;
private final float MAX_VOLUME = .2f;
private final float VOLUME_GROWTH_SPEED = .05f;
private float currVolume;
// UI related
private Skin skin;
private Stage stage;
// TODO: find better solution
private boolean touchedUiElement;
private Table root;
public GameScreen(MyGame game) {
super(game);
initGuiElements();
GameWorld.initialize();
gameWorld = GameWorld.getInstance();
gameWorld.setGame(game);
notifications = new LiveNotifications();
eventNotifications = new EventNotifications();
}
private void initGuiElements() {
stage = new Stage(MyGame.SCREEN_WIDTH, MyGame.SCREEN_HEIGHT);
skin = new Skin(Gdx.files.internal("data/ui2/uiskin.json"));
// Create a table that fills the screen. Everything else will go inside this table.
root = new Table();
root.setFillParent(true);
root.center().top();
root.padTop(5);
stage.addActor(root);
// Create a button with the "default" TextButtonStyle. A 3rd parameter can be used to specify a name other than "default".
TextFieldStyle whiteStyle = skin.get("input_white", TextFieldStyle.class);
final TextField chatMessageField = new TextField("", whiteStyle);
chatMessageField.setMessageText("Say something!");
chatMessageField.setVisible(false);
chatMessageField.addListener(new ClickListener() {
@Override
public void clicked (InputEvent event, float x, float y) {
super.clicked(event, x, y);
touchedUiElement = true;
}
});
TextButtonStyle greenStyle = skin.get("green", TextButtonStyle.class);
final TextButton sayButton = new TextButton("Say", greenStyle);
sayButton.setWidth(35);
sayButton.setVisible(false);
sayButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
touchedUiElement = true;
// Send the packet with broadcast type
- MyGame.connection.sendPacket(new ChatMessagePacket("/b " + chatMessageField.getText()));
+ MyGame.connection.sendPacket(new ChatMessagePacket(chatMessageField.getText()));
// Lose the focus
chatMessageField.setText("");
stage.unfocusAll();
}
});
Group textGroup = new Group();
textGroup.addActor(chatMessageField);
textGroup.size(chatMessageField.getWidth(), chatMessageField.getHeight());
Group sayButtonGroup = new Group();
sayButtonGroup.addActor(sayButton);
sayButtonGroup.size(sayButton.getWidth(), sayButton.getHeight());
HorizontalGroup horizontalGroup = new HorizontalGroup();
horizontalGroup.addActor(textGroup);
horizontalGroup.addActor(sayButtonGroup);
horizontalGroup.setSpacing(5);
root.add(horizontalGroup).expandX().padLeft(25);
ButtonStyle toggleStyle = skin.get("button_chat", ButtonStyle.class);
final Button chatToggleButton = new Button(toggleStyle);
chatToggleButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
touchedUiElement = true;
boolean visible = chatMessageField.isVisible();
chatMessageField.setVisible(!visible);
sayButton.setVisible(!visible);
}
});
root.add(chatToggleButton).right().padRight(5);
}
@Override
public void draw(float deltaTime) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
spriteBatch.begin();
/*---------------------------------------
* World
*/
gameWorld.draw(spriteBatch);
spriteBatch.end();
/*---------------------------------------
* GUI Elements
*/
spriteBatch.begin();
spriteBatch.setProjectionMatrix(guiCam.combined);
// Assets.defaultFont.draw(spriteBatch, fpsText, 20, 20);
spriteBatch.end();
stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
stage.draw();
}
@Override
public void update(float deltaTime) {
gameWorld.update(deltaTime);
if (!touchedUiElement) {
gameWorld.updateWorldInput();
}
touchedUiElement = false;
if (currVolume < MAX_VOLUME) {
currVolume += deltaTime * VOLUME_GROWTH_SPEED;
music.setVolume(currVolume);
}
}
@Override
public void prepare() {
currVolume = 0;
music = Assets.manager.get("sounds/bg.wav");
music.setLooping(true);
music.setVolume(currVolume);
music.stop();
music.play();
Gdx.input.setInputProcessor(stage);
}
public GameWorld getWorld() {
return gameWorld;
}
}
| true | true | private void initGuiElements() {
stage = new Stage(MyGame.SCREEN_WIDTH, MyGame.SCREEN_HEIGHT);
skin = new Skin(Gdx.files.internal("data/ui2/uiskin.json"));
// Create a table that fills the screen. Everything else will go inside this table.
root = new Table();
root.setFillParent(true);
root.center().top();
root.padTop(5);
stage.addActor(root);
// Create a button with the "default" TextButtonStyle. A 3rd parameter can be used to specify a name other than "default".
TextFieldStyle whiteStyle = skin.get("input_white", TextFieldStyle.class);
final TextField chatMessageField = new TextField("", whiteStyle);
chatMessageField.setMessageText("Say something!");
chatMessageField.setVisible(false);
chatMessageField.addListener(new ClickListener() {
@Override
public void clicked (InputEvent event, float x, float y) {
super.clicked(event, x, y);
touchedUiElement = true;
}
});
TextButtonStyle greenStyle = skin.get("green", TextButtonStyle.class);
final TextButton sayButton = new TextButton("Say", greenStyle);
sayButton.setWidth(35);
sayButton.setVisible(false);
sayButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
touchedUiElement = true;
// Send the packet with broadcast type
MyGame.connection.sendPacket(new ChatMessagePacket("/b " + chatMessageField.getText()));
// Lose the focus
chatMessageField.setText("");
stage.unfocusAll();
}
});
Group textGroup = new Group();
textGroup.addActor(chatMessageField);
textGroup.size(chatMessageField.getWidth(), chatMessageField.getHeight());
Group sayButtonGroup = new Group();
sayButtonGroup.addActor(sayButton);
sayButtonGroup.size(sayButton.getWidth(), sayButton.getHeight());
HorizontalGroup horizontalGroup = new HorizontalGroup();
horizontalGroup.addActor(textGroup);
horizontalGroup.addActor(sayButtonGroup);
horizontalGroup.setSpacing(5);
root.add(horizontalGroup).expandX().padLeft(25);
ButtonStyle toggleStyle = skin.get("button_chat", ButtonStyle.class);
final Button chatToggleButton = new Button(toggleStyle);
chatToggleButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
touchedUiElement = true;
boolean visible = chatMessageField.isVisible();
chatMessageField.setVisible(!visible);
sayButton.setVisible(!visible);
}
});
root.add(chatToggleButton).right().padRight(5);
}
| private void initGuiElements() {
stage = new Stage(MyGame.SCREEN_WIDTH, MyGame.SCREEN_HEIGHT);
skin = new Skin(Gdx.files.internal("data/ui2/uiskin.json"));
// Create a table that fills the screen. Everything else will go inside this table.
root = new Table();
root.setFillParent(true);
root.center().top();
root.padTop(5);
stage.addActor(root);
// Create a button with the "default" TextButtonStyle. A 3rd parameter can be used to specify a name other than "default".
TextFieldStyle whiteStyle = skin.get("input_white", TextFieldStyle.class);
final TextField chatMessageField = new TextField("", whiteStyle);
chatMessageField.setMessageText("Say something!");
chatMessageField.setVisible(false);
chatMessageField.addListener(new ClickListener() {
@Override
public void clicked (InputEvent event, float x, float y) {
super.clicked(event, x, y);
touchedUiElement = true;
}
});
TextButtonStyle greenStyle = skin.get("green", TextButtonStyle.class);
final TextButton sayButton = new TextButton("Say", greenStyle);
sayButton.setWidth(35);
sayButton.setVisible(false);
sayButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
touchedUiElement = true;
// Send the packet with broadcast type
MyGame.connection.sendPacket(new ChatMessagePacket(chatMessageField.getText()));
// Lose the focus
chatMessageField.setText("");
stage.unfocusAll();
}
});
Group textGroup = new Group();
textGroup.addActor(chatMessageField);
textGroup.size(chatMessageField.getWidth(), chatMessageField.getHeight());
Group sayButtonGroup = new Group();
sayButtonGroup.addActor(sayButton);
sayButtonGroup.size(sayButton.getWidth(), sayButton.getHeight());
HorizontalGroup horizontalGroup = new HorizontalGroup();
horizontalGroup.addActor(textGroup);
horizontalGroup.addActor(sayButtonGroup);
horizontalGroup.setSpacing(5);
root.add(horizontalGroup).expandX().padLeft(25);
ButtonStyle toggleStyle = skin.get("button_chat", ButtonStyle.class);
final Button chatToggleButton = new Button(toggleStyle);
chatToggleButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
touchedUiElement = true;
boolean visible = chatMessageField.isVisible();
chatMessageField.setVisible(!visible);
sayButton.setVisible(!visible);
}
});
root.add(chatToggleButton).right().padRight(5);
}
|
diff --git a/src/java/org/xhtmlrenderer/layout/InlineBoxing.java b/src/java/org/xhtmlrenderer/layout/InlineBoxing.java
index 4be9d6e1..a156455c 100644
--- a/src/java/org/xhtmlrenderer/layout/InlineBoxing.java
+++ b/src/java/org/xhtmlrenderer/layout/InlineBoxing.java
@@ -1,835 +1,838 @@
/*
* {{{ header & license
* Copyright (c) 2004, 2005 Joshua Marinacci, Torbjoern Gannholm
* Copyright (c) 2005 Wisconsin Court System
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
* }}}
*/
package org.xhtmlrenderer.layout;
import java.awt.Font;
import java.awt.font.LineMetrics;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.xhtmlrenderer.css.constants.CSSName;
import org.xhtmlrenderer.css.constants.IdentValue;
import org.xhtmlrenderer.css.newmatch.CascadedStyle;
import org.xhtmlrenderer.css.style.CalculatedStyle;
import org.xhtmlrenderer.css.style.derived.BorderPropertySet;
import org.xhtmlrenderer.css.style.derived.RectPropertySet;
import org.xhtmlrenderer.layout.content.AbsolutelyPositionedContent;
import org.xhtmlrenderer.layout.content.Content;
import org.xhtmlrenderer.layout.content.FirstLetterStyle;
import org.xhtmlrenderer.layout.content.FirstLineStyle;
import org.xhtmlrenderer.layout.content.FloatedBlockContent;
import org.xhtmlrenderer.layout.content.InlineBlockContent;
import org.xhtmlrenderer.layout.content.StylePop;
import org.xhtmlrenderer.layout.content.StylePush;
import org.xhtmlrenderer.layout.content.TextContent;
import org.xhtmlrenderer.layout.content.WhitespaceStripper;
import org.xhtmlrenderer.render.AnonymousBlockBox;
import org.xhtmlrenderer.render.BlockBox;
import org.xhtmlrenderer.render.Box;
import org.xhtmlrenderer.render.FloatDistances;
import org.xhtmlrenderer.render.FloatedBlockBox;
import org.xhtmlrenderer.render.InlineBox;
import org.xhtmlrenderer.render.InlineText;
import org.xhtmlrenderer.render.LineBox;
import org.xhtmlrenderer.render.MarkerData;
import org.xhtmlrenderer.render.StrutMetrics;
import org.xhtmlrenderer.render.Style;
import org.xhtmlrenderer.render.TextDecoration;
public class InlineBoxing {
public static void layoutContent(LayoutContext c, Box box, List contentList) {
int maxAvailableWidth = c.getExtents().width;
int remainingWidth = maxAvailableWidth;
int minimumLineHeight = (int) c.getCurrentStyle().getLineHeight(c);
LineBox currentLine = newLine(c, null, box);
LineBox previousLine = null;
InlineBox currentIB = null;
InlineBox previousIB = null;
List elementStack = new ArrayList();
if (box instanceof AnonymousBlockBox) {
List pending = ((BlockBox) box.getParent()).getPendingInlineElements();
if (pending != null) {
currentIB = addNestedInlineBoxes(c, currentLine, pending,
maxAvailableWidth);
elementStack = pending;
}
}
CalculatedStyle parentStyle = c.getCurrentStyle();
int indent = (int) parentStyle.getFloatPropertyProportionalWidth(CSSName.TEXT_INDENT, maxAvailableWidth, c);
remainingWidth -= indent;
currentLine.x = indent;
MarkerData markerData = c.getCurrentMarkerData();
if (markerData != null &&
box.getStyle().getCalculatedStyle().isIdent(
CSSName.LIST_STYLE_POSITION, IdentValue.INSIDE)) {
remainingWidth -= markerData.getLayoutWidth();
currentLine.x += markerData.getLayoutWidth();
}
c.setCurrentMarkerData(null);
remainingWidth -= c.getBlockFormattingContext().getFloatDistance(c, currentLine, remainingWidth);
List pendingFloats = new ArrayList();
int pendingLeftMBP = 0;
int pendingRightMBP = 0;
boolean hasFirstLinePCs = false;
List pendingInlineLayers = new ArrayList();
if (c.getFirstLinesTracker().hasStyles()) {
c.getFirstLinesTracker().pushStyles(c);
hasFirstLinePCs = true;
}
boolean needFirstLetter = c.getFirstLettersTracker().hasStyles();
for (int i = 0; i < contentList.size(); i++) {
Object o = contentList.get(i);
if (o instanceof FirstLineStyle || o instanceof FirstLetterStyle) {
continue;
}
if (o instanceof StylePush) {
StylePush sp = (StylePush) o;
CascadedStyle cascaded = sp.getStyle(c);
c.pushStyle(cascaded);
CalculatedStyle style = c.getCurrentStyle();
previousIB = currentIB;
currentIB = new InlineBox(sp.getElement(), style, maxAvailableWidth);
currentIB.calculateHeight(c);
elementStack.add(new InlineBoxInfo(cascaded, currentIB));
if (previousIB == null) {
currentLine.addChild(c, currentIB);
} else {
previousIB.addInlineChild(c, currentIB);
}
//To break the line well, assume we don't just want to paint padding on next line
pendingLeftMBP += style.getLeftMarginBorderPadding(c, maxAvailableWidth);
pendingRightMBP += style.getRightMarginBorderPadding(c, maxAvailableWidth);
continue;
}
if (o instanceof StylePop) {
CalculatedStyle style = c.getCurrentStyle();
int rightMBP = style.getRightMarginBorderPadding(c, maxAvailableWidth);
pendingRightMBP -= rightMBP;
remainingWidth -= rightMBP;
elementStack.remove(elementStack.size() - 1);
currentIB.setEndsHere(true);
if (currentIB.getStyle().requiresLayer()) {
if (currentIB.element == null ||
currentIB.element != c.getLayer().getMaster().element) {
throw new RuntimeException("internal error");
}
c.getLayer().setEnd(currentIB);
c.popLayer();
pendingInlineLayers.add(currentIB.getContainingLayer());
}
previousIB = currentIB;
currentIB = currentIB.getParent() instanceof LineBox ?
null : (InlineBox) currentIB.getParent();
c.popStyle();
continue;
}
Content content = (Content) o;
if (mustBeTakenOutOfFlow(content)) {
remainingWidth -= processOutOfFlowContent(c, content, currentLine,
remainingWidth, pendingFloats);
} else if (isInlineBlock(content)) {
Box inlineBlock = layoutInlineBlock(c, box, content);
if (inlineBlock.getWidth() > remainingWidth && currentLine.isContainsContent()) {
saveLine(currentLine, previousLine, c, box, minimumLineHeight,
maxAvailableWidth, elementStack, pendingFloats,
hasFirstLinePCs, pendingInlineLayers, markerData);
+ markerData = null;
previousLine = currentLine;
currentLine = newLine(c, previousLine, box);
currentIB = addNestedInlineBoxes(c, currentLine, elementStack,
maxAvailableWidth);
previousIB = currentIB == null || currentIB.getParent() instanceof LineBox ?
null : (InlineBox) currentIB.getParent();
remainingWidth = maxAvailableWidth;
remainingWidth -= c.getBlockFormattingContext().getFloatDistance(c, currentLine, remainingWidth);
if (inlineBlock.getLayer() != null) {
inlineBlock.getLayer().detach();
}
inlineBlock = layoutInlineBlock(c, box, content);
}
if (currentIB == null) {
currentLine.addChild(c, inlineBlock);
} else {
currentIB.addInlineChild(c, inlineBlock);
}
currentLine.setContainsContent(true);
currentLine.setContainsBlockLevelContent(true);
remainingWidth -= inlineBlock.getWidth();
needFirstLetter = false;
} else {
TextContent text = (TextContent) content;
LineBreakContext lbContext = new LineBreakContext();
lbContext.setMaster(TextUtil.transformText(text.getText(), c.getCurrentStyle()));
do {
lbContext.reset();
int fit = 0;
if (lbContext.getStart() == 0) {
fit += pendingLeftMBP;
}
if (hasTrimmableLeadingSpace(currentLine, c.getCurrentStyle(),
lbContext)) {
lbContext.setStart(lbContext.getStart() + 1);
}
if (needFirstLetter && !lbContext.isFinished()) {
InlineBox firstLetter =
addFirstLetterBox(c, currentLine, currentIB, lbContext,
maxAvailableWidth, remainingWidth);
remainingWidth -= firstLetter.getInlineWidth();
needFirstLetter = false;
} else {
lbContext.saveEnd();
InlineText inlineText = layoutText(
c, remainingWidth - fit, lbContext, false);
if (!lbContext.isUnbreakable() ||
(lbContext.isUnbreakable() && ! currentLine.isContainsContent())) {
currentIB.addInlineChild(c, inlineText);
currentLine.setContainsContent(true);
lbContext.setStart(lbContext.getEnd());
remainingWidth -= inlineText.getWidth();
} else {
lbContext.resetEnd();
}
}
if (lbContext.isNeedsNewLine()) {
saveLine(currentLine, previousLine, c, box, minimumLineHeight,
maxAvailableWidth, elementStack, pendingFloats,
hasFirstLinePCs, pendingInlineLayers, markerData);
+ markerData = null;
if (currentLine.isFirstLine() && hasFirstLinePCs) {
lbContext.setMaster(TextUtil.transformText(
text.getText(), c.getCurrentStyle()));
}
previousLine = currentLine;
currentLine = newLine(c, previousLine, box);
currentIB = addNestedInlineBoxes(c, currentLine, elementStack,
maxAvailableWidth);
previousIB = currentIB.getParent() instanceof LineBox ?
null : (InlineBox) currentIB.getParent();
remainingWidth = maxAvailableWidth;
remainingWidth -= c.getBlockFormattingContext().getFloatDistance(c, currentLine, remainingWidth);
}
} while (!lbContext.isFinished());
}
}
saveLine(currentLine, previousLine, c, box, minimumLineHeight,
maxAvailableWidth, elementStack, pendingFloats, hasFirstLinePCs,
pendingInlineLayers, markerData);
+ markerData = null;
if (box instanceof AnonymousBlockBox) {
((BlockBox) box.getParent()).setPendingInlineElements(elementStack.size() == 0 ? null : elementStack);
}
if (!c.shrinkWrap()) box.contentWidth = maxAvailableWidth;
box.setHeight(currentLine.y + currentLine.getHeight());
}
private static InlineBox addFirstLetterBox(LayoutContext c, LineBox current,
InlineBox currentIB, LineBreakContext lbContext, int maxAvailableWidth,
int remainingWidth) {
c.getFirstLettersTracker().pushStyles(c);
InlineBox iB = new InlineBox(null, c.getCurrentStyle(), maxAvailableWidth);
iB.calculateHeight(c);
iB.setStartsHere(true);
iB.setEndsHere(true);
currentIB.addInlineChild(c, iB);
current.setContainsContent(true);
InlineText text = layoutText(c, remainingWidth, lbContext, true);
iB.addInlineChild(c, text);
lbContext.setStart(lbContext.getEnd());
c.getFirstLettersTracker().popStyles(c);
c.getFirstLettersTracker().clearStyles();
return iB;
}
private static Box layoutInlineBlock(LayoutContext c,
Box containingBlock, Content content) {
Box inlineBlock = Boxing.preLayout(c, content);
inlineBlock.setContainingBlock(containingBlock);
inlineBlock.setContainingLayer(c.getLayer());
Boxing.realLayout(c, inlineBlock, content);
return inlineBlock;
}
private static int positionHorizontally(LayoutContext c, Box current, int start) {
int x = start;
InlineBox currentIB = null;
if (current instanceof InlineBox) {
currentIB = (InlineBox) currentIB;
x += currentIB.getLeftMarginBorderPadding(c);
}
for (int i = 0; i < current.getChildCount(); i++) {
Box b = current.getChild(i);
if (b instanceof InlineBox) {
InlineBox iB = (InlineBox) current.getChild(i);
iB.x = x;
x += positionHorizontally(c, iB, x);
} else {
b.x = x;
x += b.getWidth();
}
}
if (currentIB != null) {
x += currentIB.getRightMarginPaddingBorder(c);
currentIB.setInlineWidth(x - start);
}
return x - start;
}
private static int positionHorizontally(LayoutContext c, InlineBox current, int start) {
int x = start;
x += current.getLeftMarginBorderPadding(c);
for (int i = 0; i < current.getInlineChildCount(); i++) {
Object child = current.getInlineChild(i);
if (child instanceof InlineBox) {
InlineBox iB = (InlineBox) child;
iB.x = x;
x += positionHorizontally(c, iB, x);
} else if (child instanceof InlineText) {
InlineText iT = (InlineText) child;
iT.setX(x - start);
x += iT.getWidth();
} else if (child instanceof Box) {
Box b = (Box) child;
b.x = x;
x += b.getWidth();
}
}
x += current.getRightMarginPaddingBorder(c);
current.setInlineWidth(x - start);
return x - start;
}
public static StrutMetrics createDefaultStrutMetrics(LayoutContext c, Box container) {
LineMetrics strutLM = container.getStyle().getLineMetrics(c);
InlineBoxMeasurements measurements = getInitialMeasurements(c, container, strutLM);
return new StrutMetrics(
strutLM.getAscent(), measurements.getBaseline(), strutLM.getDescent());
}
private static void positionVertically(
LayoutContext c, Box container, LineBox current, MarkerData markerData) {
if (current.getChildCount() == 0) {
current.height = 0;
} else {
LineMetrics strutLM = container.getStyle().getLineMetrics(c);
VerticalAlignContext vaContext = new VerticalAlignContext();
InlineBoxMeasurements measurements = getInitialMeasurements(c, container, strutLM);
vaContext.pushMeasurements(measurements);
TextDecoration lBDecoration = calculateTextDecoration(
container, measurements.getBaseline(), strutLM);
if (lBDecoration != null) {
current.setTextDecoration(lBDecoration);
}
for (int i = 0; i < current.getChildCount(); i++) {
Box child = current.getChild(i);
positionInlineContentVertically(c, vaContext, child);
}
vaContext.alignChildren();
current.setHeight(vaContext.getLineBoxHeight());
int paintingTop = vaContext.getPaintingTop();
int paintingBottom = vaContext.getPaintingBottom();
if (vaContext.getInlineTop() < 0) {
moveLineContents(current, -vaContext.getInlineTop());
if (lBDecoration != null) {
lBDecoration.setOffset(lBDecoration.getOffset() - vaContext.getInlineTop());
}
paintingTop -= vaContext.getInlineTop();
paintingBottom -= vaContext.getInlineTop();
}
if (markerData != null) {
StrutMetrics strutMetrics = markerData.getStructMetrics();
strutMetrics.setBaseline(measurements.getBaseline() - vaContext.getInlineTop());
markerData.setReferenceLine(current);
}
current.setPaintingTop(paintingTop);
current.setPaintingHeight(paintingBottom - paintingTop);
}
}
private static void positionInlineVertically(LayoutContext c,
VerticalAlignContext vaContext, InlineBox iB) {
InlineBoxMeasurements iBMeasurements = calculateInlineMeasurements(c, iB, vaContext);
vaContext.pushMeasurements(iBMeasurements);
positionInlineChildrenVertically(c, iB, vaContext);
vaContext.popMeasurements();
}
private static void positionInlineBlockVertically(LayoutContext c,
VerticalAlignContext vaContext, Box inlineBlock) {
alignInlineContent(c, inlineBlock, inlineBlock.getHeight(), 0, vaContext);
vaContext.updateInlineTop(inlineBlock.y);
vaContext.updatePaintingTop(inlineBlock.y);
vaContext.updateInlineBottom(inlineBlock.y + inlineBlock.getHeight());
vaContext.updatePaintingBottom(inlineBlock.y + inlineBlock.getHeight());
}
private static void moveLineContents(LineBox current, int ty) {
for (int i = 0; i < current.getChildCount(); i++) {
Box child = (Box) current.getChild(i);
child.y += ty;
if (child instanceof InlineBox) {
moveInlineContents((InlineBox) child, ty);
}
}
}
private static void moveInlineContents(InlineBox box, int ty) {
for (int i = 0; i < box.getInlineChildCount(); i++) {
Object obj = (Object) box.getInlineChild(i);
if (obj instanceof Box) {
((Box) obj).y += ty;
if (obj instanceof InlineBox) {
moveInlineContents((InlineBox) obj, ty);
}
}
}
}
private static InlineBoxMeasurements calculateInlineMeasurements(LayoutContext c, InlineBox iB,
VerticalAlignContext vaContext) {
LineMetrics lm = iB.getStyle().getLineMetrics(c);
CalculatedStyle style = iB.getStyle().getCalculatedStyle();
float lineHeight = style.getLineHeight(c);
int halfLeading = Math.round((lineHeight -
(lm.getAscent() + lm.getDescent())) / 2);
iB.setBaseline(Math.round(lm.getAscent()));
alignInlineContent(c, iB, lm.getAscent(), lm.getDescent(), vaContext);
TextDecoration decoration = calculateTextDecoration(iB, iB.getBaseline(), lm);
if (decoration != null) {
iB.setTextDecoration(decoration);
}
InlineBoxMeasurements result = new InlineBoxMeasurements();
result.setBaseline(iB.y + iB.getBaseline());
result.setInlineTop(iB.y - halfLeading);
result.setInlineBottom(Math.round(result.getInlineTop() + lineHeight));
result.setTextTop(iB.y);
result.setTextBottom((int) (result.getBaseline() + lm.getDescent()));
RectPropertySet padding = iB.getStyle().getPaddingWidth(c);
BorderPropertySet border = style.getBorder(c);
result.setPaintingTop((int)Math.floor(iB.y - border.top() - padding.top()));
result.setPaintingBottom((int)Math.ceil(iB.y +
lm.getAscent() + lm.getDescent() +
border.bottom() + padding.bottom()));
result.setContainsContent(iB.containsContent());
return result;
}
private static TextDecoration calculateTextDecoration(Box box, int baseline,
LineMetrics lm) {
CalculatedStyle style = box.getStyle().getCalculatedStyle();
IdentValue val = style.getIdent(CSSName.TEXT_DECORATION);
TextDecoration decoration = null;
if (val == IdentValue.UNDERLINE) {
decoration = new TextDecoration();
decoration.setOffset((int)(baseline +
lm.getUnderlineOffset() + lm.getUnderlineThickness()));
decoration.setThickness((int)lm.getUnderlineThickness());
} else if (val == IdentValue.LINE_THROUGH) {
decoration = new TextDecoration();
decoration.setOffset(Math.round(baseline + lm.getStrikethroughOffset()));
decoration.setThickness((int)lm.getStrikethroughThickness());
} else if (val == IdentValue.OVERLINE) {
decoration = new TextDecoration();
decoration.setOffset(0);
decoration.setThickness((int)lm.getUnderlineThickness());
}
return decoration;
}
// XXX vertical-align: super/middle/sub could be improved
private static void alignInlineContent(LayoutContext c, Box box,
float ascent, float descent, VerticalAlignContext vaContext) {
InlineBoxMeasurements measurements = vaContext.getParentMeasurements();
CalculatedStyle style = box.getStyle().getCalculatedStyle();
if (style.isLengthValue(CSSName.VERTICAL_ALIGN)) {
box.y = (int) (measurements.getBaseline() - ascent -
style.getFloatPropertyProportionalTo(CSSName.VERTICAL_ALIGN, style.getLineHeight(c), c));
} else {
IdentValue vAlign = style.getIdent(CSSName.VERTICAL_ALIGN);
if (vAlign == IdentValue.BASELINE) {
box.y = Math.round(measurements.getBaseline() - ascent);
} else if (vAlign == IdentValue.TEXT_TOP) {
box.y = measurements.getTextTop();
} else if (vAlign == IdentValue.TEXT_BOTTOM) {
box.y = Math.round(measurements.getTextBottom() - descent - ascent);
} else if (vAlign == IdentValue.MIDDLE) {
box.y = Math.round((measurements.getTextTop() - measurements.getBaseline()) / 2
- ascent / 2);
} else if (vAlign == IdentValue.SUPER) {
box.y = Math.round((measurements.getTextTop() - measurements.getBaseline()) / 2
- ascent);
} else if (vAlign == IdentValue.SUB) {
box.y = Math.round(measurements.getBaseline() + ascent / 2);
} else {
box.y = Math.round(measurements.getBaseline() - ascent);
}
}
}
private static InlineBoxMeasurements getInitialMeasurements(
LayoutContext c, Box container, LineMetrics strutLM) {
Style style = container.getStyle();
float lineHeight = style.getCalculatedStyle().getLineHeight(c);
int halfLeading = Math.round((lineHeight -
(strutLM.getAscent() + strutLM.getDescent())) / 2);
InlineBoxMeasurements measurements = new InlineBoxMeasurements();
measurements.setBaseline((int) (halfLeading + strutLM.getAscent()));
measurements.setTextTop((int) halfLeading);
measurements.setTextBottom((int) (measurements.getBaseline() + strutLM.getDescent()));
measurements.setInlineTop((int) halfLeading);
measurements.setInlineBottom((int) (halfLeading + lineHeight));
return measurements;
}
private static void positionInlineChildrenVertically(LayoutContext c, InlineBox current,
VerticalAlignContext vaContext) {
for (int i = 0; i < current.getInlineChildCount(); i++) {
Object child = current.getInlineChild(i);
if (child instanceof Box) {
positionInlineContentVertically(c, vaContext, (Box)child);
}
}
}
private static void positionInlineContentVertically(LayoutContext c,
VerticalAlignContext vaContext, Box child) {
VerticalAlignContext vaTarget = vaContext;
IdentValue vAlign = child.getStyle().getCalculatedStyle().getIdent(
CSSName.VERTICAL_ALIGN);
if (vAlign == IdentValue.TOP || vAlign == IdentValue.BOTTOM) {
vaTarget = vaContext.createChild(child);
}
if (child instanceof InlineBox) {
InlineBox iB = (InlineBox) child;
positionInlineVertically(c, vaTarget, iB);
} else if (child instanceof Box) {
positionInlineBlockVertically(c, vaTarget, (Box) child);
}
}
private static void saveLine(final LineBox current, LineBox previous,
final LayoutContext c, Box block, int minHeight,
final int maxAvailableWidth, List elementStack,
List pendingFloats, boolean hasFirstLinePCs,
List pendingInlineLayers, MarkerData markerData) {
current.prunePendingInlineBoxes();
int totalLineWidth = positionHorizontally(c, current, 0);
current.contentWidth = totalLineWidth;
positionVertically(c, block, current, markerData);
if (!c.shrinkWrap()) {
current.setFloatDistances(new FloatDistances() {
public int getLeftFloatDistance() {
return c.getBlockFormattingContext().getLeftFloatDistance(c, current, maxAvailableWidth);
}
public int getRightFloatDistance() {
return c.getBlockFormattingContext().getRightFloatDistance(c, current, maxAvailableWidth);
}
});
current.align();
current.setFloatDistances(null);
} else {
// FIXME Not right, but can't calculated float distance yet
// because we don't know how wide the line is. Should save
// BFC and BFC offset and use that to calculate float distance
// correctly when we're ready to align the line.
FloatDistances distances = new FloatDistances();
distances.setLeftFloatDistance(0);
distances.setRightFloatDistance(0);
current.setFloatDistances(distances);
}
if (c.shrinkWrap()) {
block.adjustWidthForChild(current.contentWidth);
}
current.y = previous == null ? 0 : previous.y + previous.height;
if (current.height != 0 && current.height < minHeight) {//would like to discard it otherwise, but that could lose inline elements
current.height = minHeight;
}
block.addChild(c, current);
if (pendingFloats.size() > 0) {
c.setFloatingY(c.getFloatingY() + current.height);
c.getBlockFormattingContext().floatPending(c, pendingFloats);
}
// new float code
if (!block.getStyle().isClearLeft()) {
current.x += c.getBlockFormattingContext().getLeftFloatDistance(c, current, maxAvailableWidth);
}
if (pendingInlineLayers.size() > 0) {
finishPendingInlineLayers(c, pendingInlineLayers);
pendingInlineLayers.clear();
}
if (hasFirstLinePCs && current.isFirstLine()) {
for (int i = 0; i < elementStack.size(); i++) {
c.popStyle();
}
c.getFirstLinesTracker().popStyles(c);
c.getFirstLinesTracker().clearStyles();
for (Iterator i = elementStack.iterator(); i.hasNext(); ) {
InlineBoxInfo iBInfo = (InlineBoxInfo)i.next();
c.pushStyle(iBInfo.getCascadedStyle());
iBInfo.setCalculatedStyle(c.getCurrentStyle());
}
}
}
private static void finishPendingInlineLayers(LayoutContext c, List layers) {
for (int i = 0; i < layers.size(); i++) {
Layer l = (Layer)layers.get(i);
l.positionChildren(c);
}
}
private static InlineText layoutText(LayoutContext c, int remainingWidth,
LineBreakContext lbContext, boolean needFirstLetter) {
InlineText result = null;
result = new InlineText();
result.setMasterText(lbContext.getMaster());
Font font = c.getCurrentStyle().getAWTFont(c);
if (needFirstLetter) {
Breaker.breakFirstLetter(c, lbContext, remainingWidth, font);
} else {
Breaker.breakText(c, lbContext, remainingWidth,
c.getCurrentStyle().getWhitespace(), font);
}
result.setSubstring(lbContext.getStart(), lbContext.getEnd());
result.setWidth(lbContext.getWidth());
return result;
}
private static boolean mustBeTakenOutOfFlow(Content content) {
return content instanceof FloatedBlockContent ||
content instanceof AbsolutelyPositionedContent;
}
private static boolean isInlineBlock(Content content) {
return content instanceof InlineBlockContent;
}
private static int processOutOfFlowContent(LayoutContext c, Content content, LineBox current, int available, List pendingFloats) {
int result = 0;
c.pushStyle(content.getStyle());
if (content instanceof AbsolutelyPositionedContent) {
LayoutUtil.generateAbsolute(c, content, current);
} else if (content instanceof FloatedBlockContent) {
FloatedBlockBox floater = LayoutUtil.generateFloated(c, content, available, current, pendingFloats);
if (!floater.isPending()) {
result = floater.getWidth();
}
}
c.popStyle();
return result;
}
private static boolean hasTrimmableLeadingSpace(LineBox line, CalculatedStyle style,
LineBreakContext lbContext) {
if (!line.isContainsContent() && lbContext.getStartSubstring().startsWith(WhitespaceStripper.SPACE)) {
IdentValue whitespace = style.getWhitespace();
if (whitespace == IdentValue.NORMAL || whitespace == IdentValue.NOWRAP) {
return true;
}
}
return false;
}
private static LineBox newLine(LayoutContext c, LineBox previousLine, Box box) {
LineBox result = new LineBox();
result.createDefaultStyle(c);
result.setParent(box);
result.initContainingLayer(c);
if (previousLine != null) {
result.y = previousLine.y + previousLine.getHeight();
}
return result;
}
private static InlineBox addNestedInlineBoxes(LayoutContext c, LineBox line,
List elementStack, int cbWidth) {
InlineBox currentIB = null;
InlineBox previousIB = null;
boolean first = true;
for (Iterator i = elementStack.iterator(); i.hasNext();) {
InlineBoxInfo info = (InlineBoxInfo) i.next();
currentIB = info.getInlineBox().copyOf();
// :first-line transition
if (info.getCalculatedStyle() != null) {
currentIB.setStyle(new Style(info.getCalculatedStyle(), cbWidth));
currentIB.calculateHeight(c);
info.setCalculatedStyle(null);
info.setInlineBox(currentIB);
}
if (first) {
line.addChild(c, currentIB);
first = false;
} else {
previousIB.addInlineChild(c, currentIB, false);
}
previousIB = currentIB;
}
return currentIB;
}
private static class InlineBoxInfo {
private CascadedStyle cascadedStyle;
private CalculatedStyle calculatedStyle;
private InlineBox inlineBox;
public InlineBoxInfo(CascadedStyle cascadedStyle, InlineBox inlineBox) {
this.cascadedStyle = cascadedStyle;
this.inlineBox = inlineBox;
}
public InlineBoxInfo() {
}
public CascadedStyle getCascadedStyle() {
return cascadedStyle;
}
public void setCascadedStyle(CascadedStyle cascadedStyle) {
this.cascadedStyle = cascadedStyle;
}
public InlineBox getInlineBox() {
return inlineBox;
}
public void setInlineBox(InlineBox inlineBox) {
this.inlineBox = inlineBox;
}
public CalculatedStyle getCalculatedStyle() {
return calculatedStyle;
}
public void setCalculatedStyle(CalculatedStyle calculatedStyle) {
this.calculatedStyle = calculatedStyle;
}
}
}
| false | true | public static void layoutContent(LayoutContext c, Box box, List contentList) {
int maxAvailableWidth = c.getExtents().width;
int remainingWidth = maxAvailableWidth;
int minimumLineHeight = (int) c.getCurrentStyle().getLineHeight(c);
LineBox currentLine = newLine(c, null, box);
LineBox previousLine = null;
InlineBox currentIB = null;
InlineBox previousIB = null;
List elementStack = new ArrayList();
if (box instanceof AnonymousBlockBox) {
List pending = ((BlockBox) box.getParent()).getPendingInlineElements();
if (pending != null) {
currentIB = addNestedInlineBoxes(c, currentLine, pending,
maxAvailableWidth);
elementStack = pending;
}
}
CalculatedStyle parentStyle = c.getCurrentStyle();
int indent = (int) parentStyle.getFloatPropertyProportionalWidth(CSSName.TEXT_INDENT, maxAvailableWidth, c);
remainingWidth -= indent;
currentLine.x = indent;
MarkerData markerData = c.getCurrentMarkerData();
if (markerData != null &&
box.getStyle().getCalculatedStyle().isIdent(
CSSName.LIST_STYLE_POSITION, IdentValue.INSIDE)) {
remainingWidth -= markerData.getLayoutWidth();
currentLine.x += markerData.getLayoutWidth();
}
c.setCurrentMarkerData(null);
remainingWidth -= c.getBlockFormattingContext().getFloatDistance(c, currentLine, remainingWidth);
List pendingFloats = new ArrayList();
int pendingLeftMBP = 0;
int pendingRightMBP = 0;
boolean hasFirstLinePCs = false;
List pendingInlineLayers = new ArrayList();
if (c.getFirstLinesTracker().hasStyles()) {
c.getFirstLinesTracker().pushStyles(c);
hasFirstLinePCs = true;
}
boolean needFirstLetter = c.getFirstLettersTracker().hasStyles();
for (int i = 0; i < contentList.size(); i++) {
Object o = contentList.get(i);
if (o instanceof FirstLineStyle || o instanceof FirstLetterStyle) {
continue;
}
if (o instanceof StylePush) {
StylePush sp = (StylePush) o;
CascadedStyle cascaded = sp.getStyle(c);
c.pushStyle(cascaded);
CalculatedStyle style = c.getCurrentStyle();
previousIB = currentIB;
currentIB = new InlineBox(sp.getElement(), style, maxAvailableWidth);
currentIB.calculateHeight(c);
elementStack.add(new InlineBoxInfo(cascaded, currentIB));
if (previousIB == null) {
currentLine.addChild(c, currentIB);
} else {
previousIB.addInlineChild(c, currentIB);
}
//To break the line well, assume we don't just want to paint padding on next line
pendingLeftMBP += style.getLeftMarginBorderPadding(c, maxAvailableWidth);
pendingRightMBP += style.getRightMarginBorderPadding(c, maxAvailableWidth);
continue;
}
if (o instanceof StylePop) {
CalculatedStyle style = c.getCurrentStyle();
int rightMBP = style.getRightMarginBorderPadding(c, maxAvailableWidth);
pendingRightMBP -= rightMBP;
remainingWidth -= rightMBP;
elementStack.remove(elementStack.size() - 1);
currentIB.setEndsHere(true);
if (currentIB.getStyle().requiresLayer()) {
if (currentIB.element == null ||
currentIB.element != c.getLayer().getMaster().element) {
throw new RuntimeException("internal error");
}
c.getLayer().setEnd(currentIB);
c.popLayer();
pendingInlineLayers.add(currentIB.getContainingLayer());
}
previousIB = currentIB;
currentIB = currentIB.getParent() instanceof LineBox ?
null : (InlineBox) currentIB.getParent();
c.popStyle();
continue;
}
Content content = (Content) o;
if (mustBeTakenOutOfFlow(content)) {
remainingWidth -= processOutOfFlowContent(c, content, currentLine,
remainingWidth, pendingFloats);
} else if (isInlineBlock(content)) {
Box inlineBlock = layoutInlineBlock(c, box, content);
if (inlineBlock.getWidth() > remainingWidth && currentLine.isContainsContent()) {
saveLine(currentLine, previousLine, c, box, minimumLineHeight,
maxAvailableWidth, elementStack, pendingFloats,
hasFirstLinePCs, pendingInlineLayers, markerData);
previousLine = currentLine;
currentLine = newLine(c, previousLine, box);
currentIB = addNestedInlineBoxes(c, currentLine, elementStack,
maxAvailableWidth);
previousIB = currentIB == null || currentIB.getParent() instanceof LineBox ?
null : (InlineBox) currentIB.getParent();
remainingWidth = maxAvailableWidth;
remainingWidth -= c.getBlockFormattingContext().getFloatDistance(c, currentLine, remainingWidth);
if (inlineBlock.getLayer() != null) {
inlineBlock.getLayer().detach();
}
inlineBlock = layoutInlineBlock(c, box, content);
}
if (currentIB == null) {
currentLine.addChild(c, inlineBlock);
} else {
currentIB.addInlineChild(c, inlineBlock);
}
currentLine.setContainsContent(true);
currentLine.setContainsBlockLevelContent(true);
remainingWidth -= inlineBlock.getWidth();
needFirstLetter = false;
} else {
TextContent text = (TextContent) content;
LineBreakContext lbContext = new LineBreakContext();
lbContext.setMaster(TextUtil.transformText(text.getText(), c.getCurrentStyle()));
do {
lbContext.reset();
int fit = 0;
if (lbContext.getStart() == 0) {
fit += pendingLeftMBP;
}
if (hasTrimmableLeadingSpace(currentLine, c.getCurrentStyle(),
lbContext)) {
lbContext.setStart(lbContext.getStart() + 1);
}
if (needFirstLetter && !lbContext.isFinished()) {
InlineBox firstLetter =
addFirstLetterBox(c, currentLine, currentIB, lbContext,
maxAvailableWidth, remainingWidth);
remainingWidth -= firstLetter.getInlineWidth();
needFirstLetter = false;
} else {
lbContext.saveEnd();
InlineText inlineText = layoutText(
c, remainingWidth - fit, lbContext, false);
if (!lbContext.isUnbreakable() ||
(lbContext.isUnbreakable() && ! currentLine.isContainsContent())) {
currentIB.addInlineChild(c, inlineText);
currentLine.setContainsContent(true);
lbContext.setStart(lbContext.getEnd());
remainingWidth -= inlineText.getWidth();
} else {
lbContext.resetEnd();
}
}
if (lbContext.isNeedsNewLine()) {
saveLine(currentLine, previousLine, c, box, minimumLineHeight,
maxAvailableWidth, elementStack, pendingFloats,
hasFirstLinePCs, pendingInlineLayers, markerData);
if (currentLine.isFirstLine() && hasFirstLinePCs) {
lbContext.setMaster(TextUtil.transformText(
text.getText(), c.getCurrentStyle()));
}
previousLine = currentLine;
currentLine = newLine(c, previousLine, box);
currentIB = addNestedInlineBoxes(c, currentLine, elementStack,
maxAvailableWidth);
previousIB = currentIB.getParent() instanceof LineBox ?
null : (InlineBox) currentIB.getParent();
remainingWidth = maxAvailableWidth;
remainingWidth -= c.getBlockFormattingContext().getFloatDistance(c, currentLine, remainingWidth);
}
} while (!lbContext.isFinished());
}
}
saveLine(currentLine, previousLine, c, box, minimumLineHeight,
maxAvailableWidth, elementStack, pendingFloats, hasFirstLinePCs,
pendingInlineLayers, markerData);
if (box instanceof AnonymousBlockBox) {
((BlockBox) box.getParent()).setPendingInlineElements(elementStack.size() == 0 ? null : elementStack);
}
if (!c.shrinkWrap()) box.contentWidth = maxAvailableWidth;
box.setHeight(currentLine.y + currentLine.getHeight());
}
| public static void layoutContent(LayoutContext c, Box box, List contentList) {
int maxAvailableWidth = c.getExtents().width;
int remainingWidth = maxAvailableWidth;
int minimumLineHeight = (int) c.getCurrentStyle().getLineHeight(c);
LineBox currentLine = newLine(c, null, box);
LineBox previousLine = null;
InlineBox currentIB = null;
InlineBox previousIB = null;
List elementStack = new ArrayList();
if (box instanceof AnonymousBlockBox) {
List pending = ((BlockBox) box.getParent()).getPendingInlineElements();
if (pending != null) {
currentIB = addNestedInlineBoxes(c, currentLine, pending,
maxAvailableWidth);
elementStack = pending;
}
}
CalculatedStyle parentStyle = c.getCurrentStyle();
int indent = (int) parentStyle.getFloatPropertyProportionalWidth(CSSName.TEXT_INDENT, maxAvailableWidth, c);
remainingWidth -= indent;
currentLine.x = indent;
MarkerData markerData = c.getCurrentMarkerData();
if (markerData != null &&
box.getStyle().getCalculatedStyle().isIdent(
CSSName.LIST_STYLE_POSITION, IdentValue.INSIDE)) {
remainingWidth -= markerData.getLayoutWidth();
currentLine.x += markerData.getLayoutWidth();
}
c.setCurrentMarkerData(null);
remainingWidth -= c.getBlockFormattingContext().getFloatDistance(c, currentLine, remainingWidth);
List pendingFloats = new ArrayList();
int pendingLeftMBP = 0;
int pendingRightMBP = 0;
boolean hasFirstLinePCs = false;
List pendingInlineLayers = new ArrayList();
if (c.getFirstLinesTracker().hasStyles()) {
c.getFirstLinesTracker().pushStyles(c);
hasFirstLinePCs = true;
}
boolean needFirstLetter = c.getFirstLettersTracker().hasStyles();
for (int i = 0; i < contentList.size(); i++) {
Object o = contentList.get(i);
if (o instanceof FirstLineStyle || o instanceof FirstLetterStyle) {
continue;
}
if (o instanceof StylePush) {
StylePush sp = (StylePush) o;
CascadedStyle cascaded = sp.getStyle(c);
c.pushStyle(cascaded);
CalculatedStyle style = c.getCurrentStyle();
previousIB = currentIB;
currentIB = new InlineBox(sp.getElement(), style, maxAvailableWidth);
currentIB.calculateHeight(c);
elementStack.add(new InlineBoxInfo(cascaded, currentIB));
if (previousIB == null) {
currentLine.addChild(c, currentIB);
} else {
previousIB.addInlineChild(c, currentIB);
}
//To break the line well, assume we don't just want to paint padding on next line
pendingLeftMBP += style.getLeftMarginBorderPadding(c, maxAvailableWidth);
pendingRightMBP += style.getRightMarginBorderPadding(c, maxAvailableWidth);
continue;
}
if (o instanceof StylePop) {
CalculatedStyle style = c.getCurrentStyle();
int rightMBP = style.getRightMarginBorderPadding(c, maxAvailableWidth);
pendingRightMBP -= rightMBP;
remainingWidth -= rightMBP;
elementStack.remove(elementStack.size() - 1);
currentIB.setEndsHere(true);
if (currentIB.getStyle().requiresLayer()) {
if (currentIB.element == null ||
currentIB.element != c.getLayer().getMaster().element) {
throw new RuntimeException("internal error");
}
c.getLayer().setEnd(currentIB);
c.popLayer();
pendingInlineLayers.add(currentIB.getContainingLayer());
}
previousIB = currentIB;
currentIB = currentIB.getParent() instanceof LineBox ?
null : (InlineBox) currentIB.getParent();
c.popStyle();
continue;
}
Content content = (Content) o;
if (mustBeTakenOutOfFlow(content)) {
remainingWidth -= processOutOfFlowContent(c, content, currentLine,
remainingWidth, pendingFloats);
} else if (isInlineBlock(content)) {
Box inlineBlock = layoutInlineBlock(c, box, content);
if (inlineBlock.getWidth() > remainingWidth && currentLine.isContainsContent()) {
saveLine(currentLine, previousLine, c, box, minimumLineHeight,
maxAvailableWidth, elementStack, pendingFloats,
hasFirstLinePCs, pendingInlineLayers, markerData);
markerData = null;
previousLine = currentLine;
currentLine = newLine(c, previousLine, box);
currentIB = addNestedInlineBoxes(c, currentLine, elementStack,
maxAvailableWidth);
previousIB = currentIB == null || currentIB.getParent() instanceof LineBox ?
null : (InlineBox) currentIB.getParent();
remainingWidth = maxAvailableWidth;
remainingWidth -= c.getBlockFormattingContext().getFloatDistance(c, currentLine, remainingWidth);
if (inlineBlock.getLayer() != null) {
inlineBlock.getLayer().detach();
}
inlineBlock = layoutInlineBlock(c, box, content);
}
if (currentIB == null) {
currentLine.addChild(c, inlineBlock);
} else {
currentIB.addInlineChild(c, inlineBlock);
}
currentLine.setContainsContent(true);
currentLine.setContainsBlockLevelContent(true);
remainingWidth -= inlineBlock.getWidth();
needFirstLetter = false;
} else {
TextContent text = (TextContent) content;
LineBreakContext lbContext = new LineBreakContext();
lbContext.setMaster(TextUtil.transformText(text.getText(), c.getCurrentStyle()));
do {
lbContext.reset();
int fit = 0;
if (lbContext.getStart() == 0) {
fit += pendingLeftMBP;
}
if (hasTrimmableLeadingSpace(currentLine, c.getCurrentStyle(),
lbContext)) {
lbContext.setStart(lbContext.getStart() + 1);
}
if (needFirstLetter && !lbContext.isFinished()) {
InlineBox firstLetter =
addFirstLetterBox(c, currentLine, currentIB, lbContext,
maxAvailableWidth, remainingWidth);
remainingWidth -= firstLetter.getInlineWidth();
needFirstLetter = false;
} else {
lbContext.saveEnd();
InlineText inlineText = layoutText(
c, remainingWidth - fit, lbContext, false);
if (!lbContext.isUnbreakable() ||
(lbContext.isUnbreakable() && ! currentLine.isContainsContent())) {
currentIB.addInlineChild(c, inlineText);
currentLine.setContainsContent(true);
lbContext.setStart(lbContext.getEnd());
remainingWidth -= inlineText.getWidth();
} else {
lbContext.resetEnd();
}
}
if (lbContext.isNeedsNewLine()) {
saveLine(currentLine, previousLine, c, box, minimumLineHeight,
maxAvailableWidth, elementStack, pendingFloats,
hasFirstLinePCs, pendingInlineLayers, markerData);
markerData = null;
if (currentLine.isFirstLine() && hasFirstLinePCs) {
lbContext.setMaster(TextUtil.transformText(
text.getText(), c.getCurrentStyle()));
}
previousLine = currentLine;
currentLine = newLine(c, previousLine, box);
currentIB = addNestedInlineBoxes(c, currentLine, elementStack,
maxAvailableWidth);
previousIB = currentIB.getParent() instanceof LineBox ?
null : (InlineBox) currentIB.getParent();
remainingWidth = maxAvailableWidth;
remainingWidth -= c.getBlockFormattingContext().getFloatDistance(c, currentLine, remainingWidth);
}
} while (!lbContext.isFinished());
}
}
saveLine(currentLine, previousLine, c, box, minimumLineHeight,
maxAvailableWidth, elementStack, pendingFloats, hasFirstLinePCs,
pendingInlineLayers, markerData);
markerData = null;
if (box instanceof AnonymousBlockBox) {
((BlockBox) box.getParent()).setPendingInlineElements(elementStack.size() == 0 ? null : elementStack);
}
if (!c.shrinkWrap()) box.contentWidth = maxAvailableWidth;
box.setHeight(currentLine.y + currentLine.getHeight());
}
|
diff --git a/src/com/vaadin/terminal/gwt/client/ApplicationConfiguration.java b/src/com/vaadin/terminal/gwt/client/ApplicationConfiguration.java
index 37b62a447..eccd92545 100644
--- a/src/com/vaadin/terminal/gwt/client/ApplicationConfiguration.java
+++ b/src/com/vaadin/terminal/gwt/client/ApplicationConfiguration.java
@@ -1,433 +1,433 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;
import com.vaadin.terminal.gwt.client.ui.VUnknownComponent;
public class ApplicationConfiguration implements EntryPoint {
/**
* Builds number. For example 0-custom_tag in 5.0.0-custom_tag.
*/
public static final String VERSION;
/* Initialize version numbers from string replaced by build-script. */
static {
if ("@VERSION@".equals("@" + "VERSION" + "@")) {
VERSION = "9.9.9.INTERNAL-DEBUG-BUILD";
} else {
VERSION = "@VERSION@";
}
}
private static WidgetSet widgetSet = GWT.create(WidgetSet.class);
private String id;
private String themeUri;
private String pathInfo;
private String appUri;
private JavaScriptObject versionInfo;
private String windowName;
private String communicationErrorCaption;
private String communicationErrorMessage;
private String communicationErrorUrl;
private String authorizationErrorCaption;
private String authorizationErrorMessage;
private String authorizationErrorUrl;
private boolean useDebugIdInDom = true;
private boolean usePortletURLs = false;
private String portletUidlURLBase;
private HashMap<String, String> unknownComponents;
private Class<? extends Paintable>[] classes = new Class[1024];
private String windowId;
static// TODO consider to make this hashmap per application
LinkedList<Command> callbacks = new LinkedList<Command>();
private static int widgetsLoading;
private static ArrayList<ApplicationConnection> unstartedApplications = new ArrayList<ApplicationConnection>();
private static ArrayList<ApplicationConnection> runningApplications = new ArrayList<ApplicationConnection>();
public boolean usePortletURLs() {
return usePortletURLs;
}
public String getPortletUidlURLBase() {
return portletUidlURLBase;
}
public String getRootPanelId() {
return id;
}
/**
* Gets the application base URI. Using this other than as the download
* action URI can cause problems in Portlet 2.0 deployments.
*
* @return application base URI
*/
public String getApplicationUri() {
return appUri;
}
public String getPathInfo() {
return pathInfo;
}
public String getThemeUri() {
return themeUri;
}
public void setAppId(String appId) {
id = appId;
}
public void setInitialWindowName(String name) {
windowName = name;
}
public String getInitialWindowName() {
return windowName;
}
public JavaScriptObject getVersionInfoJSObject() {
return versionInfo;
}
public String getCommunicationErrorCaption() {
return communicationErrorCaption;
}
public String getCommunicationErrorMessage() {
return communicationErrorMessage;
}
public String getCommunicationErrorUrl() {
return communicationErrorUrl;
}
public String getAuthorizationErrorCaption() {
return authorizationErrorCaption;
}
public String getAuthorizationErrorMessage() {
return authorizationErrorMessage;
}
public String getAuthorizationErrorUrl() {
return authorizationErrorUrl;
}
private native void loadFromDOM()
/*-{
var id = [email protected]::id;
if($wnd.vaadin.vaadinConfigurations && $wnd.vaadin.vaadinConfigurations[id]) {
var jsobj = $wnd.vaadin.vaadinConfigurations[id];
var uri = jsobj.appUri;
if(uri != null && uri[uri.length -1] != "/") {
uri = uri + "/";
}
[email protected]::appUri = uri;
[email protected]::pathInfo = jsobj.pathInfo;
[email protected]::themeUri = jsobj.themeUri;
if(jsobj.windowName) {
[email protected]::windowName = jsobj.windowName;
}
if('useDebugIdInDom' in jsobj && typeof(jsobj.useDebugIdInDom) == "boolean") {
[email protected]::useDebugIdInDom = jsobj.useDebugIdInDom;
}
if(jsobj.versionInfo) {
[email protected]::versionInfo = jsobj.versionInfo;
}
if(jsobj.comErrMsg) {
[email protected]::communicationErrorCaption = jsobj.comErrMsg.caption;
[email protected]::communicationErrorMessage = jsobj.comErrMsg.message;
[email protected]::communicationErrorUrl = jsobj.comErrMsg.url;
}
if(jsobj.authErrMsg) {
[email protected]::authorizationErrorCaption = jsobj.authErrMsg.caption;
[email protected]::authorizationErrorMessage = jsobj.authErrMsg.message;
[email protected]::authorizationErrorUrl = jsobj.authErrMsg.url;
}
if (jsobj.usePortletURLs) {
[email protected]::usePortletURLs = jsobj.usePortletURLs;
}
if (jsobj.portletUidlURLBase) {
[email protected]::portletUidlURLBase = jsobj.portletUidlURLBase;
}
} else {
$wnd.alert("Vaadin app failed to initialize: " + this.id);
}
}-*/;
/**
* Inits the ApplicationConfiguration by reading the DOM and instantiating
* ApplicationConnections accordingly. Call {@link #startNextApplication()}
* to actually start the applications.
*
* @param widgetset
* the widgetset that is running the apps
*/
public static void initConfigurations() {
ArrayList<String> appIds = new ArrayList<String>();
loadAppIdListFromDOM(appIds);
for (Iterator<String> it = appIds.iterator(); it.hasNext();) {
String appId = it.next();
ApplicationConfiguration appConf = getConfigFromDOM(appId);
ApplicationConnection a = new ApplicationConnection(widgetSet,
appConf);
unstartedApplications.add(a);
}
deferredWidgetLoadLoop.scheduleRepeating(100);
}
/**
* Starts the next unstarted application. The WidgetSet should call this
* once to start the first application; after that, each application should
* call this once it has started. This ensures that the applications are
* started synchronously, which is neccessary to avoid session-id problems.
*
* @return true if an unstarted application was found
*/
public static boolean startNextApplication() {
if (unstartedApplications.size() > 0) {
ApplicationConnection a = unstartedApplications.remove(0);
a.start();
runningApplications.add(a);
return true;
} else {
return false;
}
}
public static List<ApplicationConnection> getRunningApplications() {
return runningApplications;
}
private native static void loadAppIdListFromDOM(ArrayList<String> list)
/*-{
var j;
for(j in $wnd.vaadin.vaadinConfigurations) {
[email protected]::add(Ljava/lang/Object;)(j);
}
}-*/;
public static ApplicationConfiguration getConfigFromDOM(String appId) {
ApplicationConfiguration conf = new ApplicationConfiguration();
conf.setAppId(appId);
conf.loadFromDOM();
return conf;
}
public native String getServletVersion()
/*-{
return [email protected]::versionInfo.vaadinVersion;
}-*/;
public native String getApplicationVersion()
/*-{
return [email protected]::versionInfo.applicationVersion;
}-*/;
public boolean useDebugIdInDOM() {
return useDebugIdInDom;
}
public Class<? extends Paintable> getWidgetClassByEncodedTag(String tag) {
try {
int parseInt = Integer.parseInt(tag);
return classes[parseInt];
} catch (Exception e) {
// component was not present in mappings
return VUnknownComponent.class;
}
}
public void addComponentMappings(ValueMap valueMap, WidgetSet widgetSet) {
JsArrayString keyArray = valueMap.getKeyArray();
for (int i = 0; i < keyArray.length(); i++) {
String key = keyArray.get(i).intern();
int value = valueMap.getInt(key);
classes[value] = widgetSet.getImplementationByClassName(key);
if (classes[value] == VUnknownComponent.class) {
if (unknownComponents == null) {
unknownComponents = new HashMap<String, String>();
}
unknownComponents.put("" + value, key);
} else if (key == "com.vaadin.ui.Window") {
windowId = "" + value;
}
}
}
/**
* @return the integer value that is used to code top level windows
* "com.vaadin.ui.Window"
*/
String getEncodedWindowTag() {
return windowId;
}
String getUnknownServerClassNameByEncodedTagName(String tag) {
if (unknownComponents != null) {
return unknownComponents.get(tag);
}
return null;
}
/**
*
* @param c
*/
static void runWhenWidgetsLoaded(Command c) {
if (widgetsLoading == 0) {
c.execute();
} else {
callbacks.add(c);
}
}
static void startWidgetLoading() {
widgetsLoading++;
}
static void endWidgetLoading() {
widgetsLoading--;
if (widgetsLoading == 0 && !callbacks.isEmpty()) {
for (Command cmd : callbacks) {
cmd.execute();
}
callbacks.clear();
}
}
/*
* This loop loads widget implementation that should be loaded deferred.
*/
private static final Timer deferredWidgetLoadLoop = new Timer() {
private static final int FREE_LIMIT = 4;
int communicationFree = 0;
int nextWidgetIndex = 0;
@Override
public void run() {
if (!isBusy()) {
Class<? extends Paintable> nextType = getNextType();
if (nextType == null) {
// ensured that all widgets are loaded
cancel();
} else {
widgetSet.loadImplementation(nextType);
}
}
}
private Class<? extends Paintable> getNextType() {
Class<? extends Paintable>[] deferredLoadedWidgets = widgetSet
.getDeferredLoadedWidgets();
if (deferredLoadedWidgets.length <= nextWidgetIndex) {
return null;
} else {
return deferredLoadedWidgets[nextWidgetIndex++];
}
}
private boolean isBusy() {
if (widgetsLoading > 0) {
communicationFree = 0;
return false;
}
for (ApplicationConnection app : runningApplications) {
if (app.hasActiveRequest()) {
// if an UIDL request or widget loading is active, mark as
// busy
communicationFree = 0;
return false;
}
}
communicationFree++;
return communicationFree < FREE_LIMIT;
}
};
public void onModuleLoad() {
// Prepare VConsole for debugging
if (isDebugMode()) {
VDebugConsole console = GWT.create(VDebugConsole.class);
console.setQuietMode(isQuietDebugMode());
console.init();
VConsole.setImplementation(console);
} else {
VConsole.setImplementation((Console) GWT.create(NullConsole.class));
}
/*
* Display some sort of error of exceptions in web mode to debug
* console. After this, exceptions are reported to VConsole and possible
* GWT hosted mode.
*/
GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void onUncaughtException(Throwable e) {
/*
* Note in case of null console (without ?debug) we eat
* exceptions. "a1 is not an object" style errors helps nobody,
* especially end user. It does not work tells just as much.
*/
- VConsole.getImplementation().error(e.getMessage());
+ VConsole.getImplementation().error(e);
}
});
initConfigurations();
startNextApplication();
}
/**
* Checks if client side is in debug mode. Practically this is invoked by
* adding ?debug parameter to URI.
*
* @return true if client side is currently been debugged
*/
public native static boolean isDebugMode()
/*-{
if($wnd.vaadin.debug) {
var parameters = $wnd.location.search;
var re = /debug[^\/]*$/;
return re.test(parameters);
} else {
return false;
}
}-*/;
private native static boolean isQuietDebugMode()
/*-{
var uri = $wnd.location;
var re = /debug=q[^\/]*$/;
return re.test(uri);
}-*/;
}
| true | true | public void onModuleLoad() {
// Prepare VConsole for debugging
if (isDebugMode()) {
VDebugConsole console = GWT.create(VDebugConsole.class);
console.setQuietMode(isQuietDebugMode());
console.init();
VConsole.setImplementation(console);
} else {
VConsole.setImplementation((Console) GWT.create(NullConsole.class));
}
/*
* Display some sort of error of exceptions in web mode to debug
* console. After this, exceptions are reported to VConsole and possible
* GWT hosted mode.
*/
GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void onUncaughtException(Throwable e) {
/*
* Note in case of null console (without ?debug) we eat
* exceptions. "a1 is not an object" style errors helps nobody,
* especially end user. It does not work tells just as much.
*/
VConsole.getImplementation().error(e.getMessage());
}
});
initConfigurations();
startNextApplication();
}
| public void onModuleLoad() {
// Prepare VConsole for debugging
if (isDebugMode()) {
VDebugConsole console = GWT.create(VDebugConsole.class);
console.setQuietMode(isQuietDebugMode());
console.init();
VConsole.setImplementation(console);
} else {
VConsole.setImplementation((Console) GWT.create(NullConsole.class));
}
/*
* Display some sort of error of exceptions in web mode to debug
* console. After this, exceptions are reported to VConsole and possible
* GWT hosted mode.
*/
GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void onUncaughtException(Throwable e) {
/*
* Note in case of null console (without ?debug) we eat
* exceptions. "a1 is not an object" style errors helps nobody,
* especially end user. It does not work tells just as much.
*/
VConsole.getImplementation().error(e);
}
});
initConfigurations();
startNextApplication();
}
|
diff --git a/src/no/hist/aitel/chess/position/SpecialPosition.java b/src/no/hist/aitel/chess/position/SpecialPosition.java
index b28d1f9..56f37a3 100644
--- a/src/no/hist/aitel/chess/position/SpecialPosition.java
+++ b/src/no/hist/aitel/chess/position/SpecialPosition.java
@@ -1,138 +1,140 @@
/*
* SpecialPosition.java
*
*/
package no.hist.aitel.chess.position;
import no.hist.aitel.chess.board.Board;
import no.hist.aitel.chess.piece.Piece;
import static no.hist.aitel.chess.piece.PieceConstants.*;
/**
*
* @author martin
*/
public class SpecialPosition extends Position {
/**
* Creates a position object for a board which is used to validate regular and special moves
* @param board
*/
public SpecialPosition(Board board) {
super(board);
}
/**
* Check if pawn can be promoted
* @return True if pawn can be promoted
*/
public boolean isPromotion() {
Piece fromPiece = board.getPiece(from);
if (fromPiece.getType() == PAWN) {
if (fromPiece.getColor() == WHITE && to >= 48 && to <= 63) {
return true;
} else if (fromPiece.getColor() == BLACK && to >= 0 && to <= 7) {
return true;
}
}
return false;
}
/**
* Check if we're castling
* @return True if we're castling or false otherwise
*/
public boolean isCastling() {
Piece fromPiece = board.getPiece(from);
int rookFrom;
if (fromPiece.getType() == KING && !fromPiece.isMoved()) {
if (fromPiece.getColor() == WHITE) {
if (to == 6 && isEmptyRange(5, 6)) {
rookFrom = 7;
} else if (to == 2 && isEmptyRange(1, 3)) {
rookFrom = 0;
} else {
- throw new IllegalPositionException("Can't perform castling because fields" +
- " between king and rook aren't empty");
+// throw new IllegalPositionException("Can't perform castling because fields" +
+// " between king and rook aren't empty");
+ return false;
}
Piece rook;
if (rookFrom == 0 || rookFrom == 7) {
rook = board.getPiece(rookFrom);
} else {
return false;
}
if (rook.getColor() == WHITE && rook.getType() == ROOK && !rook.isMoved()) {
return true;
}
} else if (fromPiece.getColor() == BLACK) {
if (to == 62 && isEmptyRange(61, 62)) {
rookFrom = 63;
} else if (to == 58 && isEmptyRange(57, 59)) {
rookFrom = 56;
} else {
- throw new IllegalPositionException("Can't perform castling because fields" +
- " between king and rook aren't empty");
+// throw new IllegalPositionException("Can't perform castling because fields" +
+// " between king and rook aren't empty");
+ return false;
}
Piece rook;
if (rookFrom == 56 || rookFrom == 63) {
rook = board.getPiece(rookFrom);
} else {
return false;
}
if (rook.getColor() == BLACK && rook.getType() == ROOK && rook.isMoved()) {
return true;
}
}
}
return false;
}
/**
* Perform castling
*/
public void doCastling() {
if (from != 4 && from != 60) {
throw new IllegalPositionException("Castling can only be performed from position 4 " +
"(white) or 60 (black)");
}
int rookTo = -1, rookFrom = -1;
if (from == 4 || from == 60) {
if (to == (from + 2)) {
rookTo = from + 1;
rookFrom = from + 3;
} else if (to == (from - 2)) {
rookTo = from - 2;
rookFrom = from - 4;
}
board.setPiece(to, board.getPiece(from));
board.setPiece(from, new Piece());
board.setPiece(rookTo, board.getPiece(rookFrom));
board.setPiece(rookFrom, new Piece());
}
}
/**
* Check if all positions between (and including) two positions is empty
* @param from
* @param to
* @return True if range is empty and false otherwise
*/
private boolean isEmptyRange(int from, int to) {
if (to < from) {
for (int i = from; i >= to; i--) {
if (!board.getPiece(i).isEmpty()) {
return false;
}
}
} else {
for (int i = from; i <= to; i++) {
if (!board.getPiece(i).isEmpty()) {
return false;
}
}
}
return true;
}
}
| false | true | public boolean isCastling() {
Piece fromPiece = board.getPiece(from);
int rookFrom;
if (fromPiece.getType() == KING && !fromPiece.isMoved()) {
if (fromPiece.getColor() == WHITE) {
if (to == 6 && isEmptyRange(5, 6)) {
rookFrom = 7;
} else if (to == 2 && isEmptyRange(1, 3)) {
rookFrom = 0;
} else {
throw new IllegalPositionException("Can't perform castling because fields" +
" between king and rook aren't empty");
}
Piece rook;
if (rookFrom == 0 || rookFrom == 7) {
rook = board.getPiece(rookFrom);
} else {
return false;
}
if (rook.getColor() == WHITE && rook.getType() == ROOK && !rook.isMoved()) {
return true;
}
} else if (fromPiece.getColor() == BLACK) {
if (to == 62 && isEmptyRange(61, 62)) {
rookFrom = 63;
} else if (to == 58 && isEmptyRange(57, 59)) {
rookFrom = 56;
} else {
throw new IllegalPositionException("Can't perform castling because fields" +
" between king and rook aren't empty");
}
Piece rook;
if (rookFrom == 56 || rookFrom == 63) {
rook = board.getPiece(rookFrom);
} else {
return false;
}
if (rook.getColor() == BLACK && rook.getType() == ROOK && rook.isMoved()) {
return true;
}
}
}
return false;
}
| public boolean isCastling() {
Piece fromPiece = board.getPiece(from);
int rookFrom;
if (fromPiece.getType() == KING && !fromPiece.isMoved()) {
if (fromPiece.getColor() == WHITE) {
if (to == 6 && isEmptyRange(5, 6)) {
rookFrom = 7;
} else if (to == 2 && isEmptyRange(1, 3)) {
rookFrom = 0;
} else {
// throw new IllegalPositionException("Can't perform castling because fields" +
// " between king and rook aren't empty");
return false;
}
Piece rook;
if (rookFrom == 0 || rookFrom == 7) {
rook = board.getPiece(rookFrom);
} else {
return false;
}
if (rook.getColor() == WHITE && rook.getType() == ROOK && !rook.isMoved()) {
return true;
}
} else if (fromPiece.getColor() == BLACK) {
if (to == 62 && isEmptyRange(61, 62)) {
rookFrom = 63;
} else if (to == 58 && isEmptyRange(57, 59)) {
rookFrom = 56;
} else {
// throw new IllegalPositionException("Can't perform castling because fields" +
// " between king and rook aren't empty");
return false;
}
Piece rook;
if (rookFrom == 56 || rookFrom == 63) {
rook = board.getPiece(rookFrom);
} else {
return false;
}
if (rook.getColor() == BLACK && rook.getType() == ROOK && rook.isMoved()) {
return true;
}
}
}
return false;
}
|
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/delete/TransportDeleteIndexAction.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/delete/TransportDeleteIndexAction.java
index 04d99e9a928..cf680f6be7a 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/delete/TransportDeleteIndexAction.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/delete/TransportDeleteIndexAction.java
@@ -1,135 +1,138 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search 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.elasticsearch.action.admin.indices.delete;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.TransportActions;
import org.elasticsearch.action.admin.indices.mapping.delete.DeleteMappingRequest;
import org.elasticsearch.action.admin.indices.mapping.delete.DeleteMappingResponse;
import org.elasticsearch.action.admin.indices.mapping.delete.TransportDeleteMappingAction;
import org.elasticsearch.action.support.master.TransportMasterNodeOperationAction;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaDataDeleteIndexService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.percolator.PercolatorService;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
/**
* Delete index action.
*
* @author kimchy (shay.banon)
*/
public class TransportDeleteIndexAction extends TransportMasterNodeOperationAction<DeleteIndexRequest, DeleteIndexResponse> {
private final MetaDataDeleteIndexService deleteIndexService;
private final TransportDeleteMappingAction deleteMappingAction;
@Inject public TransportDeleteIndexAction(Settings settings, TransportService transportService, ClusterService clusterService,
ThreadPool threadPool, MetaDataDeleteIndexService deleteIndexService, TransportDeleteMappingAction deleteMappingAction) {
super(settings, transportService, clusterService, threadPool);
this.deleteIndexService = deleteIndexService;
this.deleteMappingAction = deleteMappingAction;
}
@Override protected String executor() {
return ThreadPool.Names.CACHED;
}
@Override protected String transportAction() {
return TransportActions.Admin.Indices.DELETE;
}
@Override protected DeleteIndexRequest newRequest() {
return new DeleteIndexRequest();
}
@Override protected DeleteIndexResponse newResponse() {
return new DeleteIndexResponse();
}
@Override protected void doExecute(DeleteIndexRequest request, ActionListener<DeleteIndexResponse> listener) {
request.indices(clusterService.state().metaData().concreteIndices(request.indices()));
super.doExecute(request, listener);
}
@Override protected ClusterBlockException checkBlock(DeleteIndexRequest request, ClusterState state) {
return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA, request.indices());
}
@Override protected DeleteIndexResponse masterOperation(DeleteIndexRequest request, final ClusterState state) throws ElasticSearchException {
+ if (request.indices().length == 0) {
+ return new DeleteIndexResponse(true);
+ }
final AtomicReference<DeleteIndexResponse> responseRef = new AtomicReference<DeleteIndexResponse>();
final AtomicReference<Throwable> failureRef = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(request.indices().length);
for (final String index : request.indices()) {
deleteIndexService.deleteIndex(new MetaDataDeleteIndexService.Request(index).timeout(request.timeout()), new MetaDataDeleteIndexService.Listener() {
@Override public void onResponse(MetaDataDeleteIndexService.Response response) {
responseRef.set(new DeleteIndexResponse(response.acknowledged()));
// YACK, but here we go: If this index is also percolated, make sure to delete all percolated queries from the _percolator index
IndexMetaData percolatorMetaData = state.metaData().index(PercolatorService.INDEX_NAME);
if (percolatorMetaData != null && percolatorMetaData.mappings().containsKey(index)) {
deleteMappingAction.execute(new DeleteMappingRequest(PercolatorService.INDEX_NAME).type(index), new ActionListener<DeleteMappingResponse>() {
@Override public void onResponse(DeleteMappingResponse deleteMappingResponse) {
latch.countDown();
}
@Override public void onFailure(Throwable e) {
latch.countDown();
}
});
} else {
latch.countDown();
}
}
@Override public void onFailure(Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
failureRef.set(e);
}
if (failureRef.get() != null) {
if (failureRef.get() instanceof ElasticSearchException) {
throw (ElasticSearchException) failureRef.get();
} else {
throw new ElasticSearchException(failureRef.get().getMessage(), failureRef.get());
}
}
return responseRef.get();
}
}
| true | true | @Override protected DeleteIndexResponse masterOperation(DeleteIndexRequest request, final ClusterState state) throws ElasticSearchException {
final AtomicReference<DeleteIndexResponse> responseRef = new AtomicReference<DeleteIndexResponse>();
final AtomicReference<Throwable> failureRef = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(request.indices().length);
for (final String index : request.indices()) {
deleteIndexService.deleteIndex(new MetaDataDeleteIndexService.Request(index).timeout(request.timeout()), new MetaDataDeleteIndexService.Listener() {
@Override public void onResponse(MetaDataDeleteIndexService.Response response) {
responseRef.set(new DeleteIndexResponse(response.acknowledged()));
// YACK, but here we go: If this index is also percolated, make sure to delete all percolated queries from the _percolator index
IndexMetaData percolatorMetaData = state.metaData().index(PercolatorService.INDEX_NAME);
if (percolatorMetaData != null && percolatorMetaData.mappings().containsKey(index)) {
deleteMappingAction.execute(new DeleteMappingRequest(PercolatorService.INDEX_NAME).type(index), new ActionListener<DeleteMappingResponse>() {
@Override public void onResponse(DeleteMappingResponse deleteMappingResponse) {
latch.countDown();
}
@Override public void onFailure(Throwable e) {
latch.countDown();
}
});
} else {
latch.countDown();
}
}
@Override public void onFailure(Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
failureRef.set(e);
}
if (failureRef.get() != null) {
if (failureRef.get() instanceof ElasticSearchException) {
throw (ElasticSearchException) failureRef.get();
} else {
throw new ElasticSearchException(failureRef.get().getMessage(), failureRef.get());
}
}
return responseRef.get();
}
| @Override protected DeleteIndexResponse masterOperation(DeleteIndexRequest request, final ClusterState state) throws ElasticSearchException {
if (request.indices().length == 0) {
return new DeleteIndexResponse(true);
}
final AtomicReference<DeleteIndexResponse> responseRef = new AtomicReference<DeleteIndexResponse>();
final AtomicReference<Throwable> failureRef = new AtomicReference<Throwable>();
final CountDownLatch latch = new CountDownLatch(request.indices().length);
for (final String index : request.indices()) {
deleteIndexService.deleteIndex(new MetaDataDeleteIndexService.Request(index).timeout(request.timeout()), new MetaDataDeleteIndexService.Listener() {
@Override public void onResponse(MetaDataDeleteIndexService.Response response) {
responseRef.set(new DeleteIndexResponse(response.acknowledged()));
// YACK, but here we go: If this index is also percolated, make sure to delete all percolated queries from the _percolator index
IndexMetaData percolatorMetaData = state.metaData().index(PercolatorService.INDEX_NAME);
if (percolatorMetaData != null && percolatorMetaData.mappings().containsKey(index)) {
deleteMappingAction.execute(new DeleteMappingRequest(PercolatorService.INDEX_NAME).type(index), new ActionListener<DeleteMappingResponse>() {
@Override public void onResponse(DeleteMappingResponse deleteMappingResponse) {
latch.countDown();
}
@Override public void onFailure(Throwable e) {
latch.countDown();
}
});
} else {
latch.countDown();
}
}
@Override public void onFailure(Throwable t) {
failureRef.set(t);
latch.countDown();
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
failureRef.set(e);
}
if (failureRef.get() != null) {
if (failureRef.get() instanceof ElasticSearchException) {
throw (ElasticSearchException) failureRef.get();
} else {
throw new ElasticSearchException(failureRef.get().getMessage(), failureRef.get());
}
}
return responseRef.get();
}
|
diff --git a/src/main/java/nl/surfnet/bod/idd/IddLiveClient.java b/src/main/java/nl/surfnet/bod/idd/IddLiveClient.java
index 466d90a3a..446a56042 100644
--- a/src/main/java/nl/surfnet/bod/idd/IddLiveClient.java
+++ b/src/main/java/nl/surfnet/bod/idd/IddLiveClient.java
@@ -1,74 +1,76 @@
/**
* The owner of the original code is SURFnet BV.
*
* Portions created by the original owner are Copyright (C) 2011-2012 the
* original owner. All Rights Reserved.
*
* Portions created by other contributors are Copyright (C) the contributor.
* All Rights Reserved.
*
* Contributor(s):
* (Contributors insert name & email here)
*
* This file is part of the SURFnet7 Bandwidth on Demand software.
*
* The SURFnet7 Bandwidth on Demand software is free software: you can
* redistribute it and/or modify it under the terms of the BSD license
* included with this distribution.
*
* If the BSD license cannot be found with this distribution, it is available
* at the following location <http://www.opensource.org/licenses/BSD-3-Clause>
*/
package nl.surfnet.bod.idd;
import java.util.Arrays;
import java.util.Collection;
import nl.surfnet.bod.idd.generated.InvoerKlant;
import nl.surfnet.bod.idd.generated.Klanten;
import nl.surfnet.bod.idd.generated.KsrBindingStub;
import nl.surfnet.bod.idd.generated.KsrLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
public class IddLiveClient implements IddClient {
private static final String IDD_VERSION = "1.09";
private Logger logger = LoggerFactory.getLogger(IddLiveClient.class);
private final String username;
private final String password;
private final String endPoint;
@Autowired
public IddLiveClient(@Value("${idd.user}") String username, @Value("${idd.password}") String password,
@Value("${idd.url}") String endPoint) {
this.username = username;
this.password = password;
this.endPoint = endPoint;
}
@Override
public synchronized Collection<Klanten> getKlanten() {
logger.info("Calling IDD");
try {
KsrLocator locator = new KsrLocator();
locator.setksrPortEndpointAddress(endPoint);
KsrBindingStub port = (KsrBindingStub) locator.getksrPort();
port.setUsername(username);
port.setPassword(password);
Klanten[] klantnamen = port.getKlantList(new InvoerKlant("list", "", IDD_VERSION)).getKlantnamen();
return Arrays.asList(klantnamen);
}
catch (Exception e) {
+ // Keep this logger because somehow we lost all acix realted errors by re-throwing.
+ logger.error("Error: ", e);
throw new RuntimeException(e);
}
}
}
| true | true | public synchronized Collection<Klanten> getKlanten() {
logger.info("Calling IDD");
try {
KsrLocator locator = new KsrLocator();
locator.setksrPortEndpointAddress(endPoint);
KsrBindingStub port = (KsrBindingStub) locator.getksrPort();
port.setUsername(username);
port.setPassword(password);
Klanten[] klantnamen = port.getKlantList(new InvoerKlant("list", "", IDD_VERSION)).getKlantnamen();
return Arrays.asList(klantnamen);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
| public synchronized Collection<Klanten> getKlanten() {
logger.info("Calling IDD");
try {
KsrLocator locator = new KsrLocator();
locator.setksrPortEndpointAddress(endPoint);
KsrBindingStub port = (KsrBindingStub) locator.getksrPort();
port.setUsername(username);
port.setPassword(password);
Klanten[] klantnamen = port.getKlantList(new InvoerKlant("list", "", IDD_VERSION)).getKlantnamen();
return Arrays.asList(klantnamen);
}
catch (Exception e) {
// Keep this logger because somehow we lost all acix realted errors by re-throwing.
logger.error("Error: ", e);
throw new RuntimeException(e);
}
}
|
diff --git a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ModuleCoreEclipseAdapterFactory.java b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ModuleCoreEclipseAdapterFactory.java
index 1d1ea3b2..693a71c4 100644
--- a/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ModuleCoreEclipseAdapterFactory.java
+++ b/plugins/org.eclipse.wst.common.modulecore/modulecore-src/org/eclipse/wst/common/componentcore/internal/util/ModuleCoreEclipseAdapterFactory.java
@@ -1,77 +1,78 @@
/*******************************************************************************
* Copyright (c) 2003, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.wst.common.componentcore.internal.util;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.wst.common.componentcore.ComponentCore;
import org.eclipse.wst.common.componentcore.UnresolveableURIException;
import org.eclipse.wst.common.componentcore.internal.ModuleStructuralModel;
import org.eclipse.wst.common.componentcore.internal.StructureEdit;
import org.eclipse.wst.common.componentcore.internal.WorkbenchComponent;
import org.eclipse.wst.common.componentcore.internal.impl.ResourceTreeNode;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
/**
* <p>
* The following class is experimental until fully documented.
* </p>
*/
public class ModuleCoreEclipseAdapterFactory implements IAdapterFactory {
private static final Class MODULE_CORE_CLASS = StructureEdit.class;
private static final Class VIRTUAL_COMPONENT_CLASS = IVirtualComponent.class;
private static final Class[] ADAPTER_LIST = new Class[] { MODULE_CORE_CLASS, VIRTUAL_COMPONENT_CLASS};
/* (non-Javadoc)
* @see org.eclipse.core.runtime.IAdapterFactory#getAdapter(java.lang.Object, java.lang.Class)
*/
public Object getAdapter(Object adaptable, Class anAdapterType) {
if(anAdapterType == MODULE_CORE_CLASS)
return new StructureEdit((ModuleStructuralModel)adaptable);
if(anAdapterType == VIRTUAL_COMPONENT_CLASS)
return getComponent((IResource)adaptable);
return null;
}
private Object getComponent(IResource resource) {
StructureEdit moduleCore = null;
WorkbenchComponent module = null;
if (!resource.exists()) return null;
try {
moduleCore = StructureEdit.getStructureEditForRead(resource.getProject());
if (resource.getType() == IResource.PROJECT) {
WorkbenchComponent[] comps = moduleCore.getWorkbenchModules();
- if (comps.length == 1)
- return comps[0];
+ if (comps.length > 0){
+ return ComponentCore.createComponent(resource.getProject(), comps[0].getName());
+ }
else
return null;
}
module = moduleCore.findComponent(resource.getFullPath(),ResourceTreeNode.CREATE_NONE);
} catch (UnresolveableURIException e) {
// Ignore
} finally {
if (moduleCore != null)
moduleCore.dispose();
}
return module == null ? null : ComponentCore.createComponent(resource.getProject(), module.getName());
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.IAdapterFactory#getAdapterList()
*/
public Class[] getAdapterList() {
return ADAPTER_LIST;
}
}
| true | true | private Object getComponent(IResource resource) {
StructureEdit moduleCore = null;
WorkbenchComponent module = null;
if (!resource.exists()) return null;
try {
moduleCore = StructureEdit.getStructureEditForRead(resource.getProject());
if (resource.getType() == IResource.PROJECT) {
WorkbenchComponent[] comps = moduleCore.getWorkbenchModules();
if (comps.length == 1)
return comps[0];
else
return null;
}
module = moduleCore.findComponent(resource.getFullPath(),ResourceTreeNode.CREATE_NONE);
} catch (UnresolveableURIException e) {
// Ignore
} finally {
if (moduleCore != null)
moduleCore.dispose();
}
return module == null ? null : ComponentCore.createComponent(resource.getProject(), module.getName());
}
| private Object getComponent(IResource resource) {
StructureEdit moduleCore = null;
WorkbenchComponent module = null;
if (!resource.exists()) return null;
try {
moduleCore = StructureEdit.getStructureEditForRead(resource.getProject());
if (resource.getType() == IResource.PROJECT) {
WorkbenchComponent[] comps = moduleCore.getWorkbenchModules();
if (comps.length > 0){
return ComponentCore.createComponent(resource.getProject(), comps[0].getName());
}
else
return null;
}
module = moduleCore.findComponent(resource.getFullPath(),ResourceTreeNode.CREATE_NONE);
} catch (UnresolveableURIException e) {
// Ignore
} finally {
if (moduleCore != null)
moduleCore.dispose();
}
return module == null ? null : ComponentCore.createComponent(resource.getProject(), module.getName());
}
|
diff --git a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/KeyStrokeTranslator.java b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/KeyStrokeTranslator.java
index 9e237dad..6a8dcfe0 100644
--- a/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/KeyStrokeTranslator.java
+++ b/net.sourceforge.vrapper.core/src/net/sourceforge/vrapper/vim/KeyStrokeTranslator.java
@@ -1,91 +1,90 @@
package net.sourceforge.vrapper.vim;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import net.sourceforge.vrapper.keymap.KeyMap;
import net.sourceforge.vrapper.keymap.KeyStroke;
import net.sourceforge.vrapper.keymap.Remapping;
import net.sourceforge.vrapper.keymap.State;
import net.sourceforge.vrapper.keymap.Transition;
/**
* Determines whether keystrokes are part of a mapping or not and handles
* the current state of multi-keystroke mappings.
*
* @author Matthias Radig
*/
public class KeyStrokeTranslator {
private State<Remapping> currentState;
private Remapping lastValue;
private final List<RemappedKeyStroke> unconsumedKeyStrokes;
private final LinkedList<RemappedKeyStroke> resultingKeyStrokes;
public KeyStrokeTranslator() {
unconsumedKeyStrokes = new LinkedList<RemappedKeyStroke>();
resultingKeyStrokes = new LinkedList<RemappedKeyStroke>();
}
public boolean processKeyStroke(KeyMap keymap, KeyStroke key) {
Transition<Remapping> trans;
if (currentState == null) {
trans = keymap.press(key);
if (trans == null) {
return false;
}
} else {
trans = currentState.press(key);
}
if (trans != null) {
// mapping exists
if (trans.getValue() != null) {
lastValue = trans.getValue();
unconsumedKeyStrokes.clear();
} else {
// as long as no preliminary result is found, keystrokes
// should not be evaluated again
- boolean recursive = lastValue != null;
+ boolean recursive = !unconsumedKeyStrokes.isEmpty() || lastValue != null;
unconsumedKeyStrokes.add(new RemappedKeyStroke(key, recursive));
}
if (trans.getNextState() == null) {
prependUnconsumed();
prependLastValue();
currentState = null;
} else {
currentState = trans.getNextState();
}
} else {
// mapping ends here
- boolean recursive = lastValue != null;
- unconsumedKeyStrokes.add(new RemappedKeyStroke(key, recursive));
+ unconsumedKeyStrokes.add(new RemappedKeyStroke(key, true));
prependUnconsumed();
prependLastValue();
currentState = null;
}
return true;
}
public Queue<RemappedKeyStroke> resultingKeyStrokes() {
return resultingKeyStrokes;
}
private void prependUnconsumed() {
resultingKeyStrokes.addAll(0, unconsumedKeyStrokes);
unconsumedKeyStrokes.clear();
}
private void prependLastValue() {
if (lastValue == null) {
return;
}
boolean recursive = lastValue.isRecursive();
int i = 0;
for (KeyStroke key : lastValue.getKeyStrokes()) {
resultingKeyStrokes.add(i++, new RemappedKeyStroke(key, recursive));
}
lastValue = null;
}
}
| false | true | public boolean processKeyStroke(KeyMap keymap, KeyStroke key) {
Transition<Remapping> trans;
if (currentState == null) {
trans = keymap.press(key);
if (trans == null) {
return false;
}
} else {
trans = currentState.press(key);
}
if (trans != null) {
// mapping exists
if (trans.getValue() != null) {
lastValue = trans.getValue();
unconsumedKeyStrokes.clear();
} else {
// as long as no preliminary result is found, keystrokes
// should not be evaluated again
boolean recursive = lastValue != null;
unconsumedKeyStrokes.add(new RemappedKeyStroke(key, recursive));
}
if (trans.getNextState() == null) {
prependUnconsumed();
prependLastValue();
currentState = null;
} else {
currentState = trans.getNextState();
}
} else {
// mapping ends here
boolean recursive = lastValue != null;
unconsumedKeyStrokes.add(new RemappedKeyStroke(key, recursive));
prependUnconsumed();
prependLastValue();
currentState = null;
}
return true;
}
| public boolean processKeyStroke(KeyMap keymap, KeyStroke key) {
Transition<Remapping> trans;
if (currentState == null) {
trans = keymap.press(key);
if (trans == null) {
return false;
}
} else {
trans = currentState.press(key);
}
if (trans != null) {
// mapping exists
if (trans.getValue() != null) {
lastValue = trans.getValue();
unconsumedKeyStrokes.clear();
} else {
// as long as no preliminary result is found, keystrokes
// should not be evaluated again
boolean recursive = !unconsumedKeyStrokes.isEmpty() || lastValue != null;
unconsumedKeyStrokes.add(new RemappedKeyStroke(key, recursive));
}
if (trans.getNextState() == null) {
prependUnconsumed();
prependLastValue();
currentState = null;
} else {
currentState = trans.getNextState();
}
} else {
// mapping ends here
unconsumedKeyStrokes.add(new RemappedKeyStroke(key, true));
prependUnconsumed();
prependLastValue();
currentState = null;
}
return true;
}
|
diff --git a/services/src/main/java/org/keycloak/services/FormService.java b/services/src/main/java/org/keycloak/services/FormService.java
index 02e4af9e0d..210fad6b1e 100755
--- a/services/src/main/java/org/keycloak/services/FormService.java
+++ b/services/src/main/java/org/keycloak/services/FormService.java
@@ -1,207 +1,209 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file 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.keycloak.services;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import javax.imageio.spi.ServiceRegistry;
import javax.ws.rs.core.MultivaluedMap;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel;
import org.keycloak.services.resources.flows.FormFlows;
import org.keycloak.social.SocialProvider;
/**
* @author <a href="mailto:[email protected]">Viliam Rockai</a>
*/
public interface FormService {
String getId();
public String process(String pageId, FormServiceDataBean data);
public static class FormServiceDataBean {
private RealmModel realm;
private UserModel userModel;
private String message;
private FormFlows.MessageType messageType;
private MultivaluedMap<String, String> formData;
private URI baseURI;
private List<SocialProvider> socialProviders;
public Boolean getSocialRegistration() {
return socialRegistration;
}
public void setSocialRegistration(Boolean socialRegistration) {
this.socialRegistration = socialRegistration;
}
private Boolean socialRegistration;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
private String code;
public String getContextPath() {
return contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
private String contextPath;
- public FormServiceDataBean(RealmModel realm, UserModel userModel, MultivaluedMap<String, String> formData, String message){
+ public FormServiceDataBean(RealmModel realm, UserModel userModel, MultivaluedMap<String, String> formData, String message) {
this.realm = realm;
this.userModel = userModel;
this.formData = formData;
this.message = message;
socialProviders = new LinkedList<SocialProvider>();
- HashMap<String,String> socialConfig = realm.getSocialConfig();
- for (Iterator<SocialProvider> itr = ServiceRegistry.lookupProviders(org.keycloak.social.SocialProvider.class); itr.hasNext();) {
- SocialProvider p = itr.next();
- if (socialConfig.containsKey(p.getId() + ".key") && socialConfig.containsKey(p.getId() + ".secret")) {
- socialProviders.add(p);
+ HashMap<String, String> socialConfig = realm.getSocialConfig();
+ if (socialConfig != null) {
+ for (Iterator<SocialProvider> itr = ServiceRegistry.lookupProviders(org.keycloak.social.SocialProvider.class); itr.hasNext(); ) {
+ SocialProvider p = itr.next();
+ if (socialConfig.containsKey(p.getId() + ".key") && socialConfig.containsKey(p.getId() + ".secret")) {
+ socialProviders.add(p);
+ }
}
}
}
public URI getBaseURI() {
return baseURI;
}
public void setBaseURI(URI baseURI) {
this.baseURI = baseURI;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public MultivaluedMap<String, String> getFormData() {
return formData;
}
public void setFormData(MultivaluedMap<String, String> formData) {
this.formData = formData;
}
public RealmModel getRealm() {
return realm;
}
public RealmModel setRealm(RealmModel realm) {
return realm;
}
public UserModel getUserModel() {
return userModel;
}
public void setUserModel(UserModel userModel) {
this.userModel = userModel;
}
public List<SocialProvider> getSocialProviders() {
return socialProviders;
}
public FormFlows.MessageType getMessageType() {
return messageType;
}
public void setMessageType(FormFlows.MessageType messageType) {
this.messageType = messageType;
}
/* OAuth Part */
private MultivaluedMap<String, RoleModel> oAuthResourceRolesRequested;
private List<RoleModel> oAuthRealmRolesRequested;
private UserModel oAuthClient;
private String oAuthCode;
private String oAuthAction;
public String getOAuthAction() {
return oAuthAction;
}
public void setOAuthAction(String action) {
this.oAuthAction = action;
}
public MultivaluedMap<String, RoleModel> getOAuthResourceRolesRequested() {
return oAuthResourceRolesRequested;
}
public void setOAuthResourceRolesRequested(MultivaluedMap<String, RoleModel> resourceRolesRequested) {
this.oAuthResourceRolesRequested = resourceRolesRequested;
}
public List<RoleModel> getOAuthRealmRolesRequested() {
return oAuthRealmRolesRequested;
}
public void setOAuthRealmRolesRequested(List<RoleModel> realmRolesRequested) {
this.oAuthRealmRolesRequested = realmRolesRequested;
}
public UserModel getOAuthClient() {
return oAuthClient;
}
public void setOAuthClient(UserModel client) {
this.oAuthClient = client;
}
public String getOAuthCode() {
return oAuthCode;
}
public void setOAuthCode(String oAuthCode) {
this.oAuthCode = oAuthCode;
}
}
}
| false | true | public FormServiceDataBean(RealmModel realm, UserModel userModel, MultivaluedMap<String, String> formData, String message){
this.realm = realm;
this.userModel = userModel;
this.formData = formData;
this.message = message;
socialProviders = new LinkedList<SocialProvider>();
HashMap<String,String> socialConfig = realm.getSocialConfig();
for (Iterator<SocialProvider> itr = ServiceRegistry.lookupProviders(org.keycloak.social.SocialProvider.class); itr.hasNext();) {
SocialProvider p = itr.next();
if (socialConfig.containsKey(p.getId() + ".key") && socialConfig.containsKey(p.getId() + ".secret")) {
socialProviders.add(p);
}
}
}
| public FormServiceDataBean(RealmModel realm, UserModel userModel, MultivaluedMap<String, String> formData, String message) {
this.realm = realm;
this.userModel = userModel;
this.formData = formData;
this.message = message;
socialProviders = new LinkedList<SocialProvider>();
HashMap<String, String> socialConfig = realm.getSocialConfig();
if (socialConfig != null) {
for (Iterator<SocialProvider> itr = ServiceRegistry.lookupProviders(org.keycloak.social.SocialProvider.class); itr.hasNext(); ) {
SocialProvider p = itr.next();
if (socialConfig.containsKey(p.getId() + ".key") && socialConfig.containsKey(p.getId() + ".secret")) {
socialProviders.add(p);
}
}
}
}
|
diff --git a/src/org/antlr/works/prefs/AWPrefs.java b/src/org/antlr/works/prefs/AWPrefs.java
index 7eda769..657a6ba 100644
--- a/src/org/antlr/works/prefs/AWPrefs.java
+++ b/src/org/antlr/works/prefs/AWPrefs.java
@@ -1,610 +1,610 @@
/*
[The "BSD licence"]
Copyright (c) 2005 Jean Bovet
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR 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.antlr.works.prefs;
import org.antlr.xjlib.appkit.app.XJApplication;
import org.antlr.xjlib.appkit.app.XJPreferences;
import org.antlr.xjlib.foundation.XJSystem;
import java.awt.*;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AWPrefs {
// General
public static final String PREF_STARTUP_ACTION = "PREF_STARTUP_ACTION";
public static final String PREF_LAST_SAVED_DOCUMENT = "PREF_LAST_SAVED_DOCUMENT";
public static final String PREF_ALL_OPENED_DOCUMENTS = "PREF_ALL_OPENED_DOCUMENTS";
public static final String PREF_RESTORE_WINDOWS = "PREF_RESTORE_WINDOWS";
public static final String PREF_LOOK_AND_FEEL = "PREF_LOOK_AND_FEEL";
public static final String PREF_DESKTOP_MODE = "PREF_DESKTOP_MODE";
public static final String PREF_DEBUG_VERBOSE = "PREF_DEBUG_VERBOSE";
public static final String PREF_DEBUG_DONT_OPTIMIZE_NFA = "PREF_DONT_OPTIMIZE_NFA";
public static final String PREF_DOT_TOOL_PATH = "PREF_DOT_TOOL_PATH";
public static final String PREF_ANTLR3_OPTIONS = "PREF_ANTLR3_OPTIONS";
public static final String PREF_TOOLBAR_SORT = "PREF_TOOLBAR_SORT";
public static final int STARTUP_NEW_DOC = 0;
public static final int STARTUP_OPEN_LAST_OPENED_DOC = 1;
public static final int STARTUP_OPEN_LAST_SAVED_DOC = 2;
public static final int STARTUP_OPEN_ALL_OPENED_DOC = 3;
public static final boolean DEFAULT_DESKTOP_MODE;
public static final String DEFAULT_DOT_TOOL_PATH;
public static final String DEFAULT_ANTLR3_OPTIONS="";
public static final boolean DEFAULT_RESTORE_WINDOWS = true;
// Editor
public static final String PREF_TAB_WIDTH = "PREF_TAB_WIDTH";
public static final String PREF_AUTOSAVE_ENABLED = "PREF_AUTOSAVE_ENABLED";
public static final String PREF_AUTOSAVE_DELAY = "PREF_AUTOSAVE_DELAY";
public static final String PREF_BACKUP_FILE_ENABLED = "PREF_BACKUP_FILE_ENABLED";
public static final String PREF_HIGHLIGHTCURSORLINE = "PREF_HIGHLIGHTCURSORLINE";
public static final String PREF_EDITOR_FONT = "PREF_EDITOR_FONT";
public static final String PREF_EDITOR_FONT_SIZE = "PREF_EDITOR_FONT_SIZE";
public static final String PREF_EDITOR_FOLDING = "PREF_EDITOR_FOLDING";
public static final String PREF_ACTIONS_ANCHORS_FOLDING = "PREF_ACTIONS_ANCHORS_FOLDING";
public static final String PREF_AUTO_IDENT_COLON_RULE = "PREF_AUTO_IDENT_COLON_RULE";
public static final String PREF_LINE_NUMBER = "PREF_LINE_NUMBER";
public static final String PREF_VSTYLE_AUTOCOMPLETION = "PREF_VSTYLE_AUTOCOMPLETION";
public static final String PREF_PARSER_DELAY = "PREF_PARSER_DELAY";
public static final String PREF_SMOOTH_SCROLLING = "PREF_SMOOTH_SCROLLING";
public static final int DEFAULT_TAB_WIDTH = 8;
public static String DEFAULT_EDITOR_FONT;
public static final int DEFAULT_EDITOR_FONT_SIZE = 12;
public static final boolean DEFAULT_EDITOR_FOLDING = true;
public static final boolean DEFAULT_ACTIONS_ANCHORS_FOLDING = true;
public static final boolean DEFAULT_AUTO_INDENT_COLON_RULE = true;
public static final int DEFAULT_PARSER_DELAY = 250;
public static final boolean DEFAULT_SMOOTH_SCROLLING = true;
// Syntax
public static final String PREF_SYNTAX_PARSER = "PREF_SYNTAX_PARSER";
public static final String PREF_SYNTAX_LEXER = "PREF_SYNTAX_LEXER";
public static final String PREF_SYNTAX_LABEL = "PREF_SYNTAX_LABEL";
public static final String PREF_SYNTAX_REFS = "PREF_SYNTAX_REFS";
public static final String PREF_SYNTAX_BLOCK = "PREF_SYNTAX_BLOCK";
public static final String PREF_SYNTAX_COMMENT = "PREF_SYNTAX_COMMENT";
public static final String PREF_SYNTAX_STRING = "PREF_SYNTAX_STRING";
public static final String PREF_SYNTAX_KEYWORD = "PREF_SYNTAX_KEYWORD";
public static Map<String,Color> color = new HashMap<String, Color>();
public static Map<String,Boolean> bold = new HashMap<String, Boolean>();
public static Map<String,Boolean> italic = new HashMap<String, Boolean>();
public static void addSyntax(String key, Color c, boolean bold, boolean italic) {
color.put(key, c);
AWPrefs.bold.put(key, bold);
AWPrefs.italic.put(key, italic);
}
static {
addSyntax(PREF_SYNTAX_PARSER, new Color(0.42f, 0, 0.42f), true, false);
addSyntax(PREF_SYNTAX_LEXER, new Color(0, 0, 0.5f), true, false);
addSyntax(PREF_SYNTAX_LABEL, Color.black, false, true);
addSyntax(PREF_SYNTAX_REFS, new Color(0, 153, 153), true, false);
addSyntax(PREF_SYNTAX_BLOCK, Color.black, true, false);
addSyntax(PREF_SYNTAX_COMMENT, Color.lightGray, false, true);
addSyntax(PREF_SYNTAX_STRING, new Color(0, 0.5f, 0), true, false);
addSyntax(PREF_SYNTAX_KEYWORD, new Color(0, 0, 0.5f), true, false);
}
public static String getSyntaxColorKey(String identifier) {
return identifier+"_COLOR";
}
public static String getSyntaxBoldKey(String identifier) {
return identifier+"_BOLD";
}
public static String getSyntaxItalicKey(String identifier) {
return identifier+"_ITALIC";
}
public static Color getSyntaxDefaultColor(String identifier) {
return color.get(identifier);
}
public static boolean getSyntaxDefaultBold(String identifier) {
return bold.get(identifier);
}
public static boolean getSyntaxDefaultItalic(String identifier) {
return italic.get(identifier);
}
public static Color getSyntaxColor(String identifier) {
return getPreferences().getColor(getSyntaxColorKey(identifier), getSyntaxDefaultColor(identifier));
}
public static boolean getSyntaxBold(String identifier) {
return getPreferences().getBoolean(getSyntaxBoldKey(identifier), getSyntaxDefaultBold(identifier));
}
public static boolean getSyntaxItalic(String identifier) {
return getPreferences().getBoolean(getSyntaxItalicKey(identifier), getSyntaxDefaultItalic(identifier));
}
// Compiler
public static final String PREF_JAVAC_CUSTOM_PATH = "PREF_JAVAC_CUSTOM_PATH";
public static final String PREF_JAVAC_PATH = "PREF_JAVAC_PATH";
public static final String PREF_JIKES_PATH = "PREF_JIKES_PATH";
public static final String PREF_CUSTOM_CLASS_PATH = "PREF_CUSTOM_CLASS_PATH";
public static final String PREF_COMPILER = "PREF_COMPILER";
public static final String PREF_CLASSPATH_SYSTEM = "PREF_CLASSPATH_SYSTEM";
public static final String PREF_CLASSPATH_CUSTOM = "PREF_CLASSPATH_CUSTOM";
public static final boolean DEFAULT_JAVAC_CUSTOM_PATH = false;
public static final String DEFAULT_JAVAC_PATH = "";
public static final String DEFAULT_JIKES_PATH = "";
public static final String DEFAULT_PREF_CUSTOM_CLASS_PATH = "";
public static final String DEFAULT_COMPILER = "javac";
public static final boolean DEFAULT_CLASSPATH_SYSTEM = true;
public static final boolean DEFAULT_CLASSPATH_CUSTOM = false;
public static final String COMPILER_JAVAC = "javac";
public static final String COMPILER_JIKES = "jikes";
public static final String COMPILER_INTEGRATED = "integrated";
// Updates
public static final String PREF_UPDATE_TYPE = "PREF_UPDATE_TYPE";
public static final String PREF_DOWNLOAD_PATH = "PREF_DOWNLOAD_PATH";
public static final String PREF_UPDATE_NEXT_DATE = "PREF_UPDATE_NEXT_DATE";
public static final int UPDATE_MANUALLY = 0;
public static final int UPDATE_AT_STARTUP = 1;
public static final int UPDATE_DAILY = 2;
public static final int UPDATE_WEEKLY = 3;
public static final int DEFAULT_UPDATE_TYPE = UPDATE_WEEKLY;
public static final String DEFAULT_DOWNLOAD_PATH = System.getProperty("user.home");
// Debugger
public static final String PREF_NONCONSUMED_TOKEN_COLOR = "PREF_NONCONSUMED_TOKEN_COLOR2";
public static final Color DEFAULT_NONCONSUMED_TOKEN_COLOR = Color.lightGray;
public static final String PREF_CONSUMED_TOKEN_COLOR = "PREF_CONSUMED_TOKEN_COLOR2";
public static final Color DEFAULT_CONSUMED_TOKEN_COLOR = Color.black;
public static final String PREF_HIDDEN_TOKEN_COLOR = "PREF_HIDDEN_TOKEN_COLOR2";
public static final Color DEFAULT_HIDDEN_TOKEN_COLOR = Color.lightGray;
public static final String PREF_DEAD_TOKEN_COLOR = "PREF_DEAD_TOKEN_COLOR2";
public static final Color DEFAULT_DEAD_TOKEN_COLOR = Color.red;
public static final String PREF_LOOKAHEAD_TOKEN_COLOR = "PREF_LOOKAHEAD_TOKEN_COLOR2";
public static final Color DEFAULT_LOOKAHEAD_TOKEN_COLOR = Color.blue;
public static final String PREF_DEBUG_LOCALPORT = "PREF_DEBUG_LOCALPORT";
public static final int DEFAULT_DEBUG_LOCALPORT = 49100;
public static final String PREF_DEBUG_LAUNCHTIMEOUT = "PREF_DEBUG_LAUNCHTIMEOUT";
public static final int DEFAULT_DEBUG_LAUNCHTIMEOUT = 5;
public static final String PREF_DETACHABLE_CHILDREN = "PREF_DETACHABLE_CHILDREN";
public static final boolean DEFAULT_DETACHABLE_CHILDREN = true;
public static final String PREF_DEBUGGER_ASK_GEN = "PREF_DEBUGGER_ASK_GEN";
public static final boolean DEFAULT_DEBUGGER_ASK_GEN = false;
// Avanced
public static final String PREF_ALERT_CHECK_GRAMMAR_SUCCESS = "PREF_ALERT_CHECK_GRAMMAR_SUCCESS";
public static final String PREF_ALERT_GENERATE_CODE_SUCCESS = "PREF_ALERT_GENERATE_CODE_SUCCESS";
public static final String PREF_ALERT_FILE_CHANGES_DETECTED = "PREF_ALERT_FILE_CHANGES_DETECTED";
public static final String PREF_ALERT_INTERPRETER_LIMITATION = "PREF_ALERT_INTERPRETER_LIMITATION";
public static final String PREF_CLEAR_CONSOLE_BEFORE_CHECK = "PREF_CLEAR_CONSOLE_BEFORE_CHECK";
// Other
public static final String PREF_USER_REGISTERED = "PREF_USER_REGISTERED";
public static final String PREF_SERVER_ID = "PREF_SERVER_ID";
public static final String PREF_OUTPUT_PATH_CUSTOM = "PREF_OUTPUT_PATH_CUSTOM";
public static final String PREF_OUTPUT_PATH = "PREF_OUTPUT_PATH";
public static final String PREF_DEBUGGER_INPUT_TEXT = "PREF_DEBUGGER_INPUT_TEXT";
public static final String PREF_DEBUGGER_EOL = "PREF_DEBUGGER_EOL";
public static final String PREF_DEBUGGER_INPUT_FILE = "PREF_DEBUGGER_INPUT_FILE";
public static final String PREF_DEBUGGER_INPUT_MODE = "PREF_DEBUGGER_INPUT_MODE";
public static final String PREF_DEBUG_BREAK_ALL = "PREF_DEBUG_BREAK_ALL";
public static final String PREF_DEBUG_BREAK_LOCATION = "PREF_DEBUG_BREAK_LOCATION";
public static final String PREF_DEBUG_BREAK_CONSUME = "PREF_DEBUG_BREAK_CONSUME";
public static final String PREF_DEBUG_BREAK_LT = "PREF_DEBUG_BREAK_LT";
public static final String PREF_DEBUG_BREAK_EXCEPTION = "PREF_DEBUG_BREAK_EXCEPTION";
public static final String PREF_PERSONAL_INFO = "PREF_OUTPUT_DEV_DATE";
public static final String PREF_PRIVATE_MENU = "PREF_PRIVATE_MENU";
public static final String DEFAULT_OUTPUT_PATH = "output";
static {
DEFAULT_EDITOR_FONT = "Courier New";
if(XJSystem.isMacOS()) {
DEFAULT_DOT_TOOL_PATH = "/Applications/Graphviz.app/Contents/MacOS/dot";
if(Font.getFont("Monospaced") != null)
DEFAULT_EDITOR_FONT = "Monospaced";
} else if(XJSystem.isWindows()) {
DEFAULT_DOT_TOOL_PATH = "";
if(Font.getFont("Tahoma") != null)
DEFAULT_EDITOR_FONT = "Tahoma";
} else if(XJSystem.isLinux()) {
DEFAULT_DOT_TOOL_PATH = "/usr/bin/dot";
if(Font.getFont("Monospaced") != null)
DEFAULT_EDITOR_FONT = "Monospaced";
} else {
DEFAULT_DOT_TOOL_PATH = "/usr/bin/dot";
if(Font.getFont("Courier") != null)
DEFAULT_EDITOR_FONT = "Courier";
}
DEFAULT_DESKTOP_MODE = !XJSystem.isMacOS();
}
public static boolean getDebugVerbose() {
return getPreferences().getBoolean(PREF_DEBUG_VERBOSE, false);
}
public static boolean getDebugDontOptimizeNFA() {
return getPreferences().getBoolean(PREF_DEBUG_DONT_OPTIMIZE_NFA, false);
}
public static int getDebugDefaultLocalPort() {
return getPreferences().getInt(PREF_DEBUG_LOCALPORT, DEFAULT_DEBUG_LOCALPORT);
}
public static int getDebugLaunchTimeout() {
return getPreferences().getInt(PREF_DEBUG_LAUNCHTIMEOUT, DEFAULT_DEBUG_LAUNCHTIMEOUT);
}
public static void setOutputPath(String path) {
getPreferences().setString(PREF_OUTPUT_PATH, path);
}
public static String getOutputPath() {
return getPreferences().getString(PREF_OUTPUT_PATH, DEFAULT_OUTPUT_PATH);
}
public static void setDebuggerInputText(String inputText) {
getPreferences().setString(PREF_DEBUGGER_INPUT_TEXT, inputText);
}
public static String getDebuggerInputText() {
return getPreferences().getString(PREF_DEBUGGER_INPUT_TEXT, "");
}
public static int getStartupAction() {
return getPreferences().getInt(PREF_STARTUP_ACTION, STARTUP_OPEN_LAST_OPENED_DOC);
}
public static boolean getRestoreWindows() {
return getPreferences().getBoolean(PREF_RESTORE_WINDOWS, DEFAULT_RESTORE_WINDOWS);
}
public static boolean getAutoSaveEnabled() {
return getPreferences().getBoolean(PREF_AUTOSAVE_ENABLED, false);
}
public static int getAutoSaveDelay() {
return getPreferences().getInt(PREF_AUTOSAVE_DELAY, 5);
}
public static boolean getBackupFileEnabled() {
return getPreferences().getBoolean(PREF_BACKUP_FILE_ENABLED, false);
}
public static boolean getHighlightCursorEnabled() {
return getPreferences().getBoolean(PREF_HIGHLIGHTCURSORLINE, true);
}
public static int getEditorTabSize() {
return getPreferences().getInt(PREF_TAB_WIDTH, DEFAULT_TAB_WIDTH);
}
public static String getEditorFont() {
return getPreferences().getString(PREF_EDITOR_FONT, DEFAULT_EDITOR_FONT);
}
public static int getEditorFontSize() {
return getPreferences().getInt(PREF_EDITOR_FONT_SIZE, DEFAULT_EDITOR_FONT_SIZE);
}
public static boolean getSmoothScrolling() {
return getPreferences().getBoolean(PREF_SMOOTH_SCROLLING, DEFAULT_SMOOTH_SCROLLING);
}
public static boolean getFoldingEnabled() {
return getPreferences().getBoolean(PREF_EDITOR_FOLDING, DEFAULT_EDITOR_FOLDING);
}
public static boolean getDisplayActionsAnchorsFolding() {
return getPreferences().getBoolean(PREF_ACTIONS_ANCHORS_FOLDING, DEFAULT_ACTIONS_ANCHORS_FOLDING);
}
public static boolean autoIndentColonInRule() {
return getPreferences().getBoolean(PREF_AUTO_IDENT_COLON_RULE, true);
}
public static boolean getLineNumberEnabled() {
return getPreferences().getBoolean(PREF_LINE_NUMBER, false);
}
public static boolean isVStyleAutoCompletion() {
return getPreferences().getBoolean(PREF_VSTYLE_AUTOCOMPLETION, false);
}
public static int getParserDelay() {
return getPreferences().getInt(PREF_PARSER_DELAY, DEFAULT_PARSER_DELAY);
}
public static void setLookAndFeel(String name) {
getPreferences().setString(PREF_LOOK_AND_FEEL, name);
}
public static String getLookAndFeel() {
return getPreferences().getString(PREF_LOOK_AND_FEEL, null);
}
public static boolean getUseDesktopMode() {
return getPreferences().getBoolean(PREF_DESKTOP_MODE, DEFAULT_DESKTOP_MODE);
}
public static void setDOTToolPath(String path) {
getPreferences().setString(PREF_DOT_TOOL_PATH, path);
}
public static String getDOTToolPath() {
return getPreferences().getString(PREF_DOT_TOOL_PATH, DEFAULT_DOT_TOOL_PATH);
}
public static String[] getANTLR3Options() {
String options = getPreferences().getString(PREF_ANTLR3_OPTIONS, DEFAULT_ANTLR3_OPTIONS);
if(options != null && options.trim().length() > 0) {
- return options.split(" ");
+ return options.trim().split(" ");
} else {
return new String[0];
}
}
public static boolean getJavaCCustomPath() {
return getPreferences().getBoolean(PREF_JAVAC_CUSTOM_PATH, DEFAULT_JAVAC_CUSTOM_PATH);
}
public static void setJavaCPath(String path) {
getPreferences().setString(PREF_JAVAC_PATH, path);
}
public static String getJavaCPath() {
return getPreferences().getString(PREF_JAVAC_PATH, DEFAULT_JAVAC_PATH);
}
public static void setJikesPath(String path) {
getPreferences().setString(PREF_JIKES_PATH, path);
}
public static String getJikesPath() {
return getPreferences().getString(PREF_JIKES_PATH, DEFAULT_JIKES_PATH);
}
public static void setCustomClassPath(String path) {
getPreferences().setString(PREF_CUSTOM_CLASS_PATH, path);
}
public static String getCustomClassPath() {
return getPreferences().getString(PREF_CUSTOM_CLASS_PATH, DEFAULT_PREF_CUSTOM_CLASS_PATH);
}
public static String getCompiler() {
return getPreferences().getString(PREF_COMPILER, DEFAULT_COMPILER);
}
public static boolean getUseSystemClassPath() {
return getPreferences().getBoolean(PREF_CLASSPATH_SYSTEM, DEFAULT_CLASSPATH_SYSTEM);
}
public static boolean getUseCustomClassPath() {
return getPreferences().getBoolean(PREF_CLASSPATH_CUSTOM, DEFAULT_CLASSPATH_CUSTOM);
}
public static int getUpdateType() {
return getPreferences().getInt(PREF_UPDATE_TYPE, DEFAULT_UPDATE_TYPE);
}
public static void setUpdateNextDate(Calendar date) {
getPreferences().setObject(PREF_UPDATE_NEXT_DATE, date);
}
public static Calendar getUpdateNextDate() {
return (Calendar)getPreferences().getObject(PREF_UPDATE_NEXT_DATE, null);
}
public static void setDownloadPath(String path) {
getPreferences().setString(PREF_DOWNLOAD_PATH, path);
}
public static String getDownloadPath() {
return getPreferences().getString(PREF_DOWNLOAD_PATH, DEFAULT_DOWNLOAD_PATH);
}
public static void setUserRegistered(boolean flag) {
getPreferences().setBoolean(PREF_USER_REGISTERED, flag);
}
public static boolean isUserRegistered() {
return getPreferences().getBoolean(PREF_USER_REGISTERED, false);
}
public static void removeUserRegistration() {
getPreferences().remove(PREF_USER_REGISTERED);
}
public static void setServerID(String id) {
getPreferences().setString(PREF_SERVER_ID, id);
}
public static String getServerID() {
return getPreferences().getString(PREF_SERVER_ID, null);
}
public static void setPersonalInfo(Map<String,Object> info) {
getPreferences().setObject(PREF_PERSONAL_INFO, info);
}
public static Map getPersonalInfo() {
return (Map)getPreferences().getObject(PREF_PERSONAL_INFO, null);
}
public static boolean getPrivateMenu() {
return getPreferences().getBoolean(PREF_PRIVATE_MENU, false);
}
public static Color getNonConsumedTokenColor() {
return getPreferences().getColor(PREF_NONCONSUMED_TOKEN_COLOR, DEFAULT_NONCONSUMED_TOKEN_COLOR);
}
public static Color getConsumedTokenColor() {
return getPreferences().getColor(PREF_CONSUMED_TOKEN_COLOR, DEFAULT_CONSUMED_TOKEN_COLOR);
}
public static Color getHiddenTokenColor() {
return getPreferences().getColor(PREF_HIDDEN_TOKEN_COLOR, DEFAULT_HIDDEN_TOKEN_COLOR);
}
public static Color getDeadTokenColor() {
return getPreferences().getColor(PREF_DEAD_TOKEN_COLOR, DEFAULT_DEAD_TOKEN_COLOR);
}
public static Color getLookaheadTokenColor() {
return getPreferences().getColor(PREF_LOOKAHEAD_TOKEN_COLOR, DEFAULT_LOOKAHEAD_TOKEN_COLOR);
}
public static boolean getDetachableChildren() {
return getPreferences().getBoolean(PREF_DETACHABLE_CHILDREN, DEFAULT_DETACHABLE_CHILDREN);
}
public static boolean getDebuggerAskGen() {
return getPreferences().getBoolean(PREF_DEBUGGER_ASK_GEN, DEFAULT_DEBUGGER_ASK_GEN);
}
public static XJPreferences getPreferences() {
return XJApplication.shared().getPreferences();
}
public static void setLastSavedDocument(String filePath) {
if(filePath != null)
getPreferences().setString(PREF_LAST_SAVED_DOCUMENT, filePath);
}
public static String getLastSavedDocument() {
return getPreferences().getString(PREF_LAST_SAVED_DOCUMENT, null);
}
public static void setAllOpenedDocuments(List<String> documents) {
if(documents != null)
getPreferences().setObject(PREF_ALL_OPENED_DOCUMENTS, documents);
}
public static List<String> getAllOpenedDocuments() {
return (List<String>) getPreferences().getObject(PREF_ALL_OPENED_DOCUMENTS, null);
}
public static void setDebuggerEOL(int index) {
getPreferences().setInt(PREF_DEBUGGER_EOL, index);
}
public static int getDebuggerEOL() {
return getPreferences().getInt(PREF_DEBUGGER_EOL, 0);
}
public static void setDebuggerInputMode(int mode) {
getPreferences().setInt(PREF_DEBUGGER_INPUT_MODE, mode);
}
public static int getDebuggerInputMode() {
return getPreferences().getInt(PREF_DEBUGGER_INPUT_MODE, 0);
}
public static void setDebuggerInputFile(String file) {
getPreferences().setString(PREF_DEBUGGER_INPUT_FILE, file);
}
public static String getDebuggerInputFile() {
return getPreferences().getString(PREF_DEBUGGER_INPUT_FILE, "");
}
public static void setAlertGenerateCodeSuccess(boolean flag) {
getPreferences().setBoolean(PREF_ALERT_GENERATE_CODE_SUCCESS, flag);
}
public static boolean isAlertGenerateCodeSuccess() {
return getPreferences().getBoolean(PREF_ALERT_GENERATE_CODE_SUCCESS, true);
}
public static void setAlertCheckGrammarSuccess(boolean flag) {
getPreferences().setBoolean(PREF_ALERT_CHECK_GRAMMAR_SUCCESS, flag);
}
public static boolean isAlertCheckGrammarSuccess() {
return getPreferences().getBoolean(PREF_ALERT_CHECK_GRAMMAR_SUCCESS, true);
}
public static void setAlertFileChangesDetected(boolean flag) {
getPreferences().setBoolean(PREF_ALERT_FILE_CHANGES_DETECTED, flag);
}
public static boolean isAlertFileChangesDetected() {
return getPreferences().getBoolean(PREF_ALERT_FILE_CHANGES_DETECTED, true);
}
public static void setAlertInterpreterLimitation(boolean flag) {
getPreferences().setBoolean(PREF_ALERT_INTERPRETER_LIMITATION, flag);
}
public static boolean isAlertInterpreterLimitation() {
return getPreferences().getBoolean(PREF_ALERT_INTERPRETER_LIMITATION, true);
}
public static boolean isClearConsoleBeforeCheckGrammar() {
return getPreferences().getBoolean(PREF_CLEAR_CONSOLE_BEFORE_CHECK, false);
}
}
| true | true | public static String[] getANTLR3Options() {
String options = getPreferences().getString(PREF_ANTLR3_OPTIONS, DEFAULT_ANTLR3_OPTIONS);
if(options != null && options.trim().length() > 0) {
return options.split(" ");
} else {
return new String[0];
}
}
| public static String[] getANTLR3Options() {
String options = getPreferences().getString(PREF_ANTLR3_OPTIONS, DEFAULT_ANTLR3_OPTIONS);
if(options != null && options.trim().length() > 0) {
return options.trim().split(" ");
} else {
return new String[0];
}
}
|
diff --git a/org.dawnsci.slicing.api/src/org/dawnsci/slicing/api/util/SliceUtils.java b/org.dawnsci.slicing.api/src/org/dawnsci/slicing/api/util/SliceUtils.java
index 2c9dff435..25241b7fe 100644
--- a/org.dawnsci.slicing.api/src/org/dawnsci/slicing/api/util/SliceUtils.java
+++ b/org.dawnsci.slicing.api/src/org/dawnsci/slicing/api/util/SliceUtils.java
@@ -1,596 +1,597 @@
/*
* Copyright (c) 2012 European Synchrotron Radiation Facility,
* Diamond Light Source Ltd.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.dawnsci.slicing.api.util;
import java.io.File;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import ncsa.hdf.object.Group;
import org.dawb.common.services.ILoaderService;
import org.dawb.common.services.ServiceManager;
import org.dawb.hdf5.HierarchicalDataFactory;
import org.dawb.hdf5.IHierarchicalDataFile;
import org.dawnsci.doe.DOEUtils;
import org.dawnsci.plotting.api.IPlottingSystem;
import org.dawnsci.plotting.api.PlotType;
import org.dawnsci.plotting.api.trace.IImageTrace;
import org.dawnsci.plotting.api.trace.ITrace;
import org.dawnsci.slicing.api.system.DimsData;
import org.dawnsci.slicing.api.system.DimsDataList;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.diamond.scisoft.analysis.IAnalysisService;
import uk.ac.diamond.scisoft.analysis.dataset.IDataset;
import uk.ac.diamond.scisoft.analysis.dataset.ILazyDataset;
import uk.ac.diamond.scisoft.analysis.io.IDataHolder;
import uk.ac.diamond.scisoft.analysis.io.SliceObject;
public class SliceUtils {
private static Logger logger = LoggerFactory.getLogger(SliceUtils.class);
private static NumberFormat format = DecimalFormat.getNumberInstance();
/**
* Generates a list of slice information for a given set of dimensional data.
*
* The data may have fields which use DOE annotations and hence can be expanded.
* This allows slices to be ranges in one or more dimensions which is a simple
* form of summing sub-sets of data.
*
* @param dimsDataHolder
* @param dataShape
* @param sliceObject
* @return a list of slices
* @throws Exception
*/
public static SliceObject createSliceObject(final DimsDataList dimsDataHolder,
final int[] dataShape,
final SliceObject sliceObject) throws Exception {
if (dimsDataHolder.size()!=dataShape.length) throw new RuntimeException("The dims data and the data shape are not equal!");
final SliceObject currentSlice = sliceObject!=null ? sliceObject.clone() : new SliceObject();
// This ugly code results from the ugly API to the slicing.
final int[] start = new int[dimsDataHolder.size()];
final int[] stop = new int[dimsDataHolder.size()];
final int[] step = new int[dimsDataHolder.size()];
IDataset x = null;
IDataset y = null;
final StringBuilder buf = new StringBuilder();
//buf.append("\n"); // New graphing can deal with long titles.
for (int i = 0; i < dimsDataHolder.size(); i++) {
final DimsData dimsData = dimsDataHolder.getDimsData(i);
start[i] = getStart(dimsData);
stop[i] = getStop(dimsData,dataShape[i]);
step[i] = getStep(dimsData);
if (dimsData.getPlotAxis()<0) {
String nexusAxisName = getNexusAxisName(currentSlice, dimsData, " (Dim "+(dimsData.getDimension()+1));
String formatValue = String.valueOf(dimsData.getSlice());
try {
formatValue = format.format(getNexusAxisValue(sliceObject, dimsData, dimsData.getSlice(), null));
} catch (Throwable ne) {
formatValue = String.valueOf(dimsData.getSlice());
}
buf.append("("+nexusAxisName+" = "+(dimsData.getSliceRange()!=null?dimsData.getSliceRange():formatValue)+")");
}
final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class);
if (dimsData.getPlotAxis()==0) {
x = service.arange(dataShape[i], IAnalysisService.INT);
x.setName("Dimension "+(dimsData.getDimension()+1));
currentSlice.setX(dimsData.getDimension());
}
if (dimsData.getPlotAxis()==1) {
y = service.arange(dataShape[i], IAnalysisService.INT);
y.setName("Dimension "+(dimsData.getDimension()+1));
currentSlice.setY(dimsData.getDimension());
}
if (dimsData.getSliceRange()!=null&&dimsData.getPlotAxis()<0) {
currentSlice.setRange(true);
}
}
if (x==null || x.getSize()<2) { // Nothing to plot
logger.debug("Cannot slice into an image because one of the dimensions is size of 1");
return null;
}
if (y!=null) {
currentSlice.setSlicedShape(new int[]{x.getSize(),y.getSize()});
currentSlice.setAxes(Arrays.asList(new IDataset[]{x,y}));
} else {
currentSlice.setSlicedShape(new int[]{x.getSize()});
currentSlice.setAxes(Arrays.asList(new IDataset[]{x}));
}
currentSlice.setSliceStart(start);
currentSlice.setSliceStop(stop);
currentSlice.setSliceStep(step);
currentSlice.setShapeMessage(buf.toString());
return currentSlice;
}
/**
*
* @param sliceObject
* @param data
* @return
* @throws Exception
*/
public static String getNexusAxisName(SliceObject sliceObject, DimsData data) {
return getNexusAxisName(sliceObject, data, "indices");
}
/**
*
* @param sliceObject
* @param data
* @return
* @throws Exception
*/
public static String getNexusAxisName(SliceObject sliceObject, DimsData data, String alternateName) {
try {
Map<Integer,String> dims = sliceObject.getNexusAxes();
String axisName = dims.get(data.getDimension()+1); // The data used for this axis
if (axisName==null || "".equals(axisName)) return alternateName;
return axisName;
} catch (Throwable ne) {
return alternateName;
}
}
/**
*
* @param sliceObject
* @param data
* @param value
* @param monitor
* @return the nexus axis value or the index if no nexus axis can be found.
* @throws Throwable
*/
public static Number getNexusAxisValue(SliceObject sliceObject, DimsData data, int value, IProgressMonitor monitor) throws Throwable {
IDataset axis = null;
try {
final String axisName = getNexusAxisName(sliceObject, data);
axis = SliceUtils.getNexusAxis(sliceObject, axisName, false, monitor);
} catch (Exception ne) {
axis = null;
}
try {
return axis!=null ? axis.getDouble(value) : value;
} catch (Throwable ne) {
return value;
}
}
private static int getStart(DimsData dimsData) {
if (dimsData.getPlotAxis()>-1) {
return 0;
} else if (dimsData.getSliceRange()!=null) {
final double[] exp = DOEUtils.getRange(dimsData.getSliceRange(), null);
return (int)exp[0];
}
return dimsData.getSlice();
}
private static int getStop(DimsData dimsData, final int size) {
if (dimsData.getPlotAxis()>-1) {
return size;
} else if (dimsData.getSliceRange()!=null) {
final double[] exp = DOEUtils.getRange(dimsData.getSliceRange(), null);
return (int)exp[1];
}
return dimsData.getSlice()+1;
}
private static int getStep(DimsData dimsData) {
if (dimsData.getPlotAxis()>-1) {
return 1;
} else if (dimsData.getSliceRange()!=null) {
final double[] exp = DOEUtils.getRange(dimsData.getSliceRange(), null);
return (int)exp[2];
}
return 1;
}
/**
* Thread safe and time consuming part of the slice.
* @param currentSlice
* @param dataShape
* @param type
* @param plottingSystem - may be null, but if so no plotting will happen.
* @param monitor
* @throws Exception
*/
public static void plotSlice(final ILazyDataset lazySet,
final SliceObject currentSlice,
final int[] dataShape,
final PlotType type,
final IPlottingSystem plottingSystem,
final IProgressMonitor monitor) throws Exception {
if (plottingSystem==null) return;
if (monitor!=null) monitor.worked(1);
if (monitor!=null&&monitor.isCanceled()) return;
currentSlice.setFullShape(dataShape);
final IDataset slice;
- if (lazySet instanceof IDataset && Arrays.equals(dataShape, lazySet.getShape())) {
+ final int[] slicedShape = currentSlice.getSlicedShape();
+ if (lazySet instanceof IDataset && Arrays.equals(slicedShape, lazySet.getShape())) {
slice = (IDataset)lazySet;
} else {
slice = getSlice(lazySet, currentSlice,monitor);
}
if (slice==null) return;
// DO NOT CANCEL the monitor now, we have done the hard part the slice.
// We may as well plot it or the plot will look very slow.
if (monitor!=null) monitor.worked(1);
boolean requireScale = plottingSystem.isRescale()
|| type!=plottingSystem.getPlotType();
if (type==PlotType.XY) {
plottingSystem.clear();
final IDataset x = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor);
plottingSystem.setXFirst(true);
plottingSystem.setPlotType(type);
plottingSystem.createPlot1D(x, Arrays.asList((IDataset)slice), slice.getName(), monitor);
Display.getDefault().syncExec(new Runnable() {
public void run() {
plottingSystem.getSelectedXAxis().setTitle(x.getName());
plottingSystem.getSelectedYAxis().setTitle("");
}
});
} else if (type==PlotType.XY_STACKED || type==PlotType.XY_STACKED_3D) {
final IDataset xAxis = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor);
plottingSystem.clear();
// We separate the 2D image into several 1d plots
final int[] shape = slice.getShape();
final List<double[]> sets = new ArrayList<double[]>(shape[1]);
for (int x = 0; x < shape[0]; x++) {
for (int y = 0; y < shape[1]; y++) {
if (y > (sets.size()-1)) sets.add(new double[shape[0]]);
double[] data = sets.get(y);
data[x] = slice.getDouble(x,y);
}
}
final List<IDataset> ys = new ArrayList<IDataset>(shape[1]);
int index = 0;
final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class);
for (double[] da : sets) {
final IDataset dds = service.createDoubleDataset(da, da.length);
dds.setName(String.valueOf(index));
ys.add(dds);
++index;
}
plottingSystem.setXFirst(true);
plottingSystem.setPlotType(type);
plottingSystem.createPlot1D(xAxis, ys, monitor);
Display.getDefault().syncExec(new Runnable() {
public void run() {
plottingSystem.getSelectedXAxis().setTitle(xAxis.getName());
plottingSystem.getSelectedYAxis().setTitle("");
}
});
} else if (type==PlotType.IMAGE || type==PlotType.SURFACE){
plottingSystem.setPlotType(type);
IDataset y = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor);
IDataset x = getNexusAxis(currentSlice, slice.getShape()[1], currentSlice.getY()+1, true, monitor);
// Nullify user objects because the ImageHistoryTool uses
// user objects to know if the image came from it. Since we
// use update here, we update (as its faster) but we also
// nullify the user object.
final IImageTrace trace = getImageTrace(plottingSystem);
if (trace!=null) trace.setUserObject(null);
plottingSystem.updatePlot2D(slice, Arrays.asList(x,y), monitor);
}
plottingSystem.repaint(requireScale);
}
/**
* this method gives access to the image trace plotted in the
* main plotter or null if one is not plotted.
* @return
*/
private static IImageTrace getImageTrace(IPlottingSystem plotting) {
if (plotting == null) return null;
final Collection<ITrace> traces = plotting.getTraces(IImageTrace.class);
if (traces==null || traces.size()==0) return null;
final ITrace trace = traces.iterator().next();
return trace instanceof IImageTrace ? (IImageTrace)trace : null;
}
/**
*
* @param currentSlice
* @param length of axis
* @param inexusAxis nexus dimension (starting with 1)
* @param requireIndicesOnError
* @param monitor
* @return
* @throws Exception
*/
public static IDataset getNexusAxis(SliceObject currentSlice, int length, int inexusAxis, boolean requireIndicesOnError, final IProgressMonitor monitor) throws Exception {
String axisName = currentSlice.getNexusAxis(inexusAxis);
final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class);
if ("indices".equals(axisName) || axisName==null) {
IDataset indices = service.arange(length, IAnalysisService.INT); // Save time
indices.setName("");
return indices;
}
if (axisName.endsWith("[Expression]")) {
final IDataset set = currentSlice.getExpressionAxis(axisName);
return service.convertToAbstractDataset(set);
}
try {
return getNexusAxis(currentSlice, axisName, true, monitor);
} catch (Throwable ne) {
logger.error("Cannot get nexus axis during slice!", ne);
if (requireIndicesOnError) {
IDataset indices = service.arange(length, IAnalysisService.INT); // Save time
indices.setName("");
return indices;
} else {
return null;
}
}
}
/**
*
* @param currentSlice
* @param axisName, full path and then optionally a : and the dimension which the axis is for.
* @param requireUnit - if true will get unit but will be slower.
* @param requireIndicesOnError
* @param monitor
* @return
*/
public static IDataset getNexusAxis(final SliceObject currentSlice,
String origName,
final boolean requireUnit,
final IProgressMonitor monitor) throws Throwable {
int dimension = -1;
String axisName = origName;
if (axisName.contains(":")) {
final String[] sa = axisName.split(":");
axisName = sa[0];
dimension = Integer.parseInt(sa[1])-1;
}
IDataset axis = null;
if (axisName.endsWith("[Expression]")) {
final IDataset set = currentSlice.getExpressionAxis(axisName);
final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class);
return service.convertToAbstractDataset(set);
}
if (requireUnit) { // Slower
IHierarchicalDataFile file = null;
try {
file = HierarchicalDataFactory.getReader(currentSlice.getPath());
final Group group = file.getParent(currentSlice.getName());
final String fullName = group.getFullName()+"/"+axisName;
final ILoaderService service = (ILoaderService)ServiceManager.getService(ILoaderService.class);
axis = service.getDataset(currentSlice.getPath(), fullName, monitor);
if (axis == null) return null;
axis = axis.squeeze();
final String unit = file.getAttributeValue(fullName+"@unit");
if (unit!=null) origName = origName+" "+unit;
} finally {
if (file!=null) file.close();
}
} else { // Faster
final String dataPath = currentSlice.getName();
final File file = new File(dataPath);
final String fullName = file.getParent().replace('\\','/')+"/"+axisName;
final ILoaderService service = (ILoaderService)ServiceManager.getService(ILoaderService.class);
axis = service.getDataset(currentSlice.getPath(), fullName, monitor);
if (axis == null) return null;
axis = axis.squeeze();
}
// TODO Should really be averaging not using first index.
if (dimension>-1) {
final int[] shape = axis.getShape();
final int[] start = new int[shape.length];
final int[] stop = new int[shape.length];
final int[] step = new int[shape.length];
for (int i = 0; i < shape.length; i++) {
start[i] = 0;
step[i] = 1;
if (i==dimension) {
stop[i] = shape[i];
} else {
stop[i] = 1;
}
}
axis = axis.getSlice(start, stop, step);
if (axis == null) return null;
axis = axis.squeeze();
}
axis.setName(origName);
return axis;
}
public static IDataset getSlice(final ILazyDataset ld,
final SliceObject currentSlice,
final IProgressMonitor monitor) throws Exception {
final int[] dataShape = currentSlice.getFullShape();
if (monitor!=null&&monitor.isCanceled()) return null;
// This is the bit that takes the time.
// *DO NOT CANCEL MONITOR* if we get this far
IDataset slice = (IDataset)ld.getSlice(currentSlice.getSliceStart(), currentSlice.getSliceStop(), currentSlice.getSliceStep());
slice.setName("Slice of "+currentSlice.getName()+" "+currentSlice.getShapeMessage());
final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class);
if (currentSlice.isRange()) {
// We sum the data in the dimensions that are not axes
IDataset sum = slice;
final int len = dataShape.length;
for (int i = len-1; i >= 0; i--) {
if (!currentSlice.isAxis(i) && dataShape[i]>1) sum = service.sum(sum, i);
}
if (currentSlice.getX() > currentSlice.getY()) sum = service.transpose(sum);
sum.setName(slice.getName());
sum = sum.squeeze();
slice = sum;
} else {
slice = slice.squeeze();
if (currentSlice.getX() > currentSlice.getY() && slice.getShape().length==2) {
// transpose clobbers name
final String name = slice.getName();
slice = service.transpose(slice);
if (name!=null) slice.setName(name);
}
}
return slice;
}
/**
* Transforms a SliceComponent defined slice into an expanded set
* of slice objects so that the data can be sliced out of the h5 file.
*
* @param fullShape
* @param dimsDataList
* @return
* @throws Exception
*/
public static List<SliceObject> getExpandedSlices(final int[] fullShape,
final Object dimsDataList) throws Exception {
final DimsDataList ddl = (DimsDataList)dimsDataList;
final List<SliceObject> obs = new ArrayList<SliceObject>(89);
createExpandedSlices(fullShape, ddl, 0, new ArrayList<DimsData>(ddl.size()), obs);
return obs;
}
private static void createExpandedSlices(final int[] fullShape,
final DimsDataList ddl,
final int index,
final List<DimsData> chunk,
final List<SliceObject> obs) throws Exception {
final DimsData dat = ddl.getDimsData(index);
final List<DimsData> exp = dat.expand(fullShape[index]);
for (DimsData d : exp) {
chunk.add(d);
if (index==ddl.size()-1) { // Reached end
SliceObject ob = new SliceObject();
ob.setFullShape(fullShape);
ob = SliceUtils.createSliceObject(new DimsDataList(chunk), fullShape, ob);
obs.add(ob);
chunk.clear();
} else {
createExpandedSlices(fullShape, ddl, index+1, chunk, obs);
}
}
}
/**
* Deals with loaders which provide data names of size 1
*
*
* @param meta
* @return
*/
public static final Collection<String> getSlicableNames(IDataHolder holder) {
Collection<String> names = Arrays.asList(holder.getNames());
if (names==null||names.isEmpty()) return null;
Collection<String> ret = new ArrayList<String>(names.size());
for (String name : names) {
ILazyDataset ls = holder.getLazyDataset(name);
int[] shape = ls!=null ? ls.getShape() : null;
if (shape==null) continue;
boolean foundDims = false;
for (int i = 0; i < shape.length; i++) {
if (shape[i]>1) {
foundDims = true;
break;
}
}
if (!foundDims) continue;
ret.add(name);
}
return ret;
}
}
| true | true | public static void plotSlice(final ILazyDataset lazySet,
final SliceObject currentSlice,
final int[] dataShape,
final PlotType type,
final IPlottingSystem plottingSystem,
final IProgressMonitor monitor) throws Exception {
if (plottingSystem==null) return;
if (monitor!=null) monitor.worked(1);
if (monitor!=null&&monitor.isCanceled()) return;
currentSlice.setFullShape(dataShape);
final IDataset slice;
if (lazySet instanceof IDataset && Arrays.equals(dataShape, lazySet.getShape())) {
slice = (IDataset)lazySet;
} else {
slice = getSlice(lazySet, currentSlice,monitor);
}
if (slice==null) return;
// DO NOT CANCEL the monitor now, we have done the hard part the slice.
// We may as well plot it or the plot will look very slow.
if (monitor!=null) monitor.worked(1);
boolean requireScale = plottingSystem.isRescale()
|| type!=plottingSystem.getPlotType();
if (type==PlotType.XY) {
plottingSystem.clear();
final IDataset x = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor);
plottingSystem.setXFirst(true);
plottingSystem.setPlotType(type);
plottingSystem.createPlot1D(x, Arrays.asList((IDataset)slice), slice.getName(), monitor);
Display.getDefault().syncExec(new Runnable() {
public void run() {
plottingSystem.getSelectedXAxis().setTitle(x.getName());
plottingSystem.getSelectedYAxis().setTitle("");
}
});
} else if (type==PlotType.XY_STACKED || type==PlotType.XY_STACKED_3D) {
final IDataset xAxis = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor);
plottingSystem.clear();
// We separate the 2D image into several 1d plots
final int[] shape = slice.getShape();
final List<double[]> sets = new ArrayList<double[]>(shape[1]);
for (int x = 0; x < shape[0]; x++) {
for (int y = 0; y < shape[1]; y++) {
if (y > (sets.size()-1)) sets.add(new double[shape[0]]);
double[] data = sets.get(y);
data[x] = slice.getDouble(x,y);
}
}
final List<IDataset> ys = new ArrayList<IDataset>(shape[1]);
int index = 0;
final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class);
for (double[] da : sets) {
final IDataset dds = service.createDoubleDataset(da, da.length);
dds.setName(String.valueOf(index));
ys.add(dds);
++index;
}
plottingSystem.setXFirst(true);
plottingSystem.setPlotType(type);
plottingSystem.createPlot1D(xAxis, ys, monitor);
Display.getDefault().syncExec(new Runnable() {
public void run() {
plottingSystem.getSelectedXAxis().setTitle(xAxis.getName());
plottingSystem.getSelectedYAxis().setTitle("");
}
});
} else if (type==PlotType.IMAGE || type==PlotType.SURFACE){
plottingSystem.setPlotType(type);
IDataset y = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor);
IDataset x = getNexusAxis(currentSlice, slice.getShape()[1], currentSlice.getY()+1, true, monitor);
// Nullify user objects because the ImageHistoryTool uses
// user objects to know if the image came from it. Since we
// use update here, we update (as its faster) but we also
// nullify the user object.
final IImageTrace trace = getImageTrace(plottingSystem);
if (trace!=null) trace.setUserObject(null);
plottingSystem.updatePlot2D(slice, Arrays.asList(x,y), monitor);
}
plottingSystem.repaint(requireScale);
}
| public static void plotSlice(final ILazyDataset lazySet,
final SliceObject currentSlice,
final int[] dataShape,
final PlotType type,
final IPlottingSystem plottingSystem,
final IProgressMonitor monitor) throws Exception {
if (plottingSystem==null) return;
if (monitor!=null) monitor.worked(1);
if (monitor!=null&&monitor.isCanceled()) return;
currentSlice.setFullShape(dataShape);
final IDataset slice;
final int[] slicedShape = currentSlice.getSlicedShape();
if (lazySet instanceof IDataset && Arrays.equals(slicedShape, lazySet.getShape())) {
slice = (IDataset)lazySet;
} else {
slice = getSlice(lazySet, currentSlice,monitor);
}
if (slice==null) return;
// DO NOT CANCEL the monitor now, we have done the hard part the slice.
// We may as well plot it or the plot will look very slow.
if (monitor!=null) monitor.worked(1);
boolean requireScale = plottingSystem.isRescale()
|| type!=plottingSystem.getPlotType();
if (type==PlotType.XY) {
plottingSystem.clear();
final IDataset x = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor);
plottingSystem.setXFirst(true);
plottingSystem.setPlotType(type);
plottingSystem.createPlot1D(x, Arrays.asList((IDataset)slice), slice.getName(), monitor);
Display.getDefault().syncExec(new Runnable() {
public void run() {
plottingSystem.getSelectedXAxis().setTitle(x.getName());
plottingSystem.getSelectedYAxis().setTitle("");
}
});
} else if (type==PlotType.XY_STACKED || type==PlotType.XY_STACKED_3D) {
final IDataset xAxis = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor);
plottingSystem.clear();
// We separate the 2D image into several 1d plots
final int[] shape = slice.getShape();
final List<double[]> sets = new ArrayList<double[]>(shape[1]);
for (int x = 0; x < shape[0]; x++) {
for (int y = 0; y < shape[1]; y++) {
if (y > (sets.size()-1)) sets.add(new double[shape[0]]);
double[] data = sets.get(y);
data[x] = slice.getDouble(x,y);
}
}
final List<IDataset> ys = new ArrayList<IDataset>(shape[1]);
int index = 0;
final IAnalysisService service = (IAnalysisService)ServiceManager.getService(IAnalysisService.class);
for (double[] da : sets) {
final IDataset dds = service.createDoubleDataset(da, da.length);
dds.setName(String.valueOf(index));
ys.add(dds);
++index;
}
plottingSystem.setXFirst(true);
plottingSystem.setPlotType(type);
plottingSystem.createPlot1D(xAxis, ys, monitor);
Display.getDefault().syncExec(new Runnable() {
public void run() {
plottingSystem.getSelectedXAxis().setTitle(xAxis.getName());
plottingSystem.getSelectedYAxis().setTitle("");
}
});
} else if (type==PlotType.IMAGE || type==PlotType.SURFACE){
plottingSystem.setPlotType(type);
IDataset y = getNexusAxis(currentSlice, slice.getShape()[0], currentSlice.getX()+1, true, monitor);
IDataset x = getNexusAxis(currentSlice, slice.getShape()[1], currentSlice.getY()+1, true, monitor);
// Nullify user objects because the ImageHistoryTool uses
// user objects to know if the image came from it. Since we
// use update here, we update (as its faster) but we also
// nullify the user object.
final IImageTrace trace = getImageTrace(plottingSystem);
if (trace!=null) trace.setUserObject(null);
plottingSystem.updatePlot2D(slice, Arrays.asList(x,y), monitor);
}
plottingSystem.repaint(requireScale);
}
|
diff --git a/src/org/flowvisor/message/FVPortMod.java b/src/org/flowvisor/message/FVPortMod.java
index f15ea74..95b968f 100644
--- a/src/org/flowvisor/message/FVPortMod.java
+++ b/src/org/flowvisor/message/FVPortMod.java
@@ -1,48 +1,50 @@
package org.flowvisor.message;
import org.flowvisor.classifier.FVClassifier;
import org.flowvisor.log.FVLog;
import org.flowvisor.log.LogLevel;
import org.flowvisor.slicer.FVSlicer;
import org.openflow.protocol.OFPhysicalPort;
import org.openflow.protocol.OFPortMod;
import org.openflow.protocol.OFError.OFPortModFailedCode;
public class FVPortMod extends OFPortMod implements Classifiable, Slicable {
/**
* Send to all slices with this port
*
* FIXME: decide if port_mod's can come *up* from switch?
*/
@Override
public void classifyFromSwitch(FVClassifier fvClassifier) {
FVLog.log(LogLevel.DEBUG, fvClassifier, "recv from switch: " + this);
for (FVSlicer fvSlicer : fvClassifier.getSlicers())
if (fvSlicer.portInSlice(this.portNumber))
fvSlicer.sendMsg(this, fvClassifier);
}
/**
* First, check to see if this port is available in this slice Second, check
* to see if they're changing the FLOOD bit FIXME: prevent slices from
* administratrively bringing down a port!
*/
@Override
public void sliceFromController(FVClassifier fvClassifier, FVSlicer fvSlicer) {
// First, check if this port is in the slice
if (!fvSlicer.portInSlice(this.portNumber)) {
fvSlicer.sendMsg(FVMessageUtil.makeErrorMsg(
OFPortModFailedCode.OFPPMFC_BAD_PORT, this), fvClassifier);
return;
}
// Second, update the port's flood state
boolean oldValue = fvSlicer.getFloodPortStatus(this.portNumber);
+ FVLog.log(LogLevel.DEBUG, fvSlicer, "Setting port " + this.portNumber + " to " +
+ ((this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD.ordinal()) == 0));
fvSlicer.setFloodPortStatus(this.portNumber,
(this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD
.ordinal()) == 0);
if (oldValue != fvSlicer.getFloodPortStatus(this.portNumber))
FVLog.log(LogLevel.CRIT, fvSlicer,
"FIXME: need to implement FLOODING port changes");
}
}
| true | true | public void sliceFromController(FVClassifier fvClassifier, FVSlicer fvSlicer) {
// First, check if this port is in the slice
if (!fvSlicer.portInSlice(this.portNumber)) {
fvSlicer.sendMsg(FVMessageUtil.makeErrorMsg(
OFPortModFailedCode.OFPPMFC_BAD_PORT, this), fvClassifier);
return;
}
// Second, update the port's flood state
boolean oldValue = fvSlicer.getFloodPortStatus(this.portNumber);
fvSlicer.setFloodPortStatus(this.portNumber,
(this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD
.ordinal()) == 0);
if (oldValue != fvSlicer.getFloodPortStatus(this.portNumber))
FVLog.log(LogLevel.CRIT, fvSlicer,
"FIXME: need to implement FLOODING port changes");
}
| public void sliceFromController(FVClassifier fvClassifier, FVSlicer fvSlicer) {
// First, check if this port is in the slice
if (!fvSlicer.portInSlice(this.portNumber)) {
fvSlicer.sendMsg(FVMessageUtil.makeErrorMsg(
OFPortModFailedCode.OFPPMFC_BAD_PORT, this), fvClassifier);
return;
}
// Second, update the port's flood state
boolean oldValue = fvSlicer.getFloodPortStatus(this.portNumber);
FVLog.log(LogLevel.DEBUG, fvSlicer, "Setting port " + this.portNumber + " to " +
((this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD.ordinal()) == 0));
fvSlicer.setFloodPortStatus(this.portNumber,
(this.mask & OFPhysicalPort.OFPortConfig.OFPPC_NO_FLOOD
.ordinal()) == 0);
if (oldValue != fvSlicer.getFloodPortStatus(this.portNumber))
FVLog.log(LogLevel.CRIT, fvSlicer,
"FIXME: need to implement FLOODING port changes");
}
|
diff --git a/Infocleta-Core/src/main/java/cl/ufro/infocleta/core/conf/Propiedades.java b/Infocleta-Core/src/main/java/cl/ufro/infocleta/core/conf/Propiedades.java
index f72b688..5edd5e0 100644
--- a/Infocleta-Core/src/main/java/cl/ufro/infocleta/core/conf/Propiedades.java
+++ b/Infocleta-Core/src/main/java/cl/ufro/infocleta/core/conf/Propiedades.java
@@ -1,68 +1,68 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cl.ufro.infocleta.core.conf;
import static cl.ufro.infocleta.core.conf.ConfUtils.stringToLaf;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* </p>
*
* @author kristian
*/
public class Propiedades {
private static final String NOMBRE_ARCHIVO = "rc.conf";
private static final String KEY_LAF = "aplicacion.laf";
private Logger LOG = LoggerFactory.getLogger(Propiedades.class);
private Properties prop;
public Propiedades() {
FileInputStream file = null;
URL root = getClass().getProtectionDomain().getCodeSource()
.getLocation();
URL filePath = null;
prop = new Properties();
try {
filePath = new URL(root, NOMBRE_ARCHIVO);
+ file = new FileInputStream(filePath.getPath());
prop.load(file);
- file = new FileInputStream(filePath.getPath());
file.close();
} catch (IOException e) {
LOG.error("# Error al leer el archivo de configuración", e);
}
}
/**
* <p>
* Obtiene el <code>LookAndFeel</code> establecido en las propiedades.
* </p>
* <b>LAF getLookAndFeel()</b>
*
* @return
*/
public Laf getLookAndFeel() {
Laf laf = Laf.SYSTEM;
if (prop == null)
return laf;
String property = prop.getProperty(KEY_LAF);
if (property == null) {
return laf;
}
laf = stringToLaf(property);
return laf;
}
}
| false | true | public Propiedades() {
FileInputStream file = null;
URL root = getClass().getProtectionDomain().getCodeSource()
.getLocation();
URL filePath = null;
prop = new Properties();
try {
filePath = new URL(root, NOMBRE_ARCHIVO);
prop.load(file);
file = new FileInputStream(filePath.getPath());
file.close();
} catch (IOException e) {
LOG.error("# Error al leer el archivo de configuración", e);
}
}
| public Propiedades() {
FileInputStream file = null;
URL root = getClass().getProtectionDomain().getCodeSource()
.getLocation();
URL filePath = null;
prop = new Properties();
try {
filePath = new URL(root, NOMBRE_ARCHIVO);
file = new FileInputStream(filePath.getPath());
prop.load(file);
file.close();
} catch (IOException e) {
LOG.error("# Error al leer el archivo de configuración", e);
}
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/propertypages/BreakpointConditionEditor.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/propertypages/BreakpointConditionEditor.java
index 549c41a05..62c46687e 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/propertypages/BreakpointConditionEditor.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/propertypages/BreakpointConditionEditor.java
@@ -1,211 +1,212 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.ui.propertypages;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.debug.core.IJavaLineBreakpoint;
import org.eclipse.jdt.internal.debug.ui.BreakpointUtils;
import org.eclipse.jdt.internal.debug.ui.JDIDebugUIPlugin;
import org.eclipse.jdt.internal.debug.ui.JDISourceViewer;
import org.eclipse.jdt.internal.debug.ui.contentassist.IJavaDebugContentAssistContext;
import org.eclipse.jdt.internal.debug.ui.contentassist.JavaDebugContentAssistProcessor;
import org.eclipse.jdt.internal.debug.ui.contentassist.TypeContext;
import org.eclipse.jdt.internal.debug.ui.display.DisplayViewerConfiguration;
import org.eclipse.jdt.ui.text.IJavaPartitions;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.TextViewerUndoManager;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.IHandlerActivation;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
/**
* The widget for the conditional editor on the breakpoints properties page
*/
public class BreakpointConditionEditor {
private JDISourceViewer fViewer;
private IContentAssistProcessor fCompletionProcessor;
private String fOldValue;
private String fErrorMessage;
private JavaLineBreakpointPage fPage;
private IJavaLineBreakpoint fBreakpoint;
private IHandlerService fHandlerService;
private IHandler fHandler;
private IHandlerActivation fActivation;
private IDocumentListener fDocumentListener;
/**
* Constructor
* @param parent the parent to add this widget to
* @param page the page that is associated with this widget
*/
public BreakpointConditionEditor(Composite parent, JavaLineBreakpointPage page) {
fPage = page;
fBreakpoint = (IJavaLineBreakpoint) fPage.getBreakpoint();
String condition = new String();
try {
condition = fBreakpoint.getCondition();
fErrorMessage = PropertyPageMessages.BreakpointConditionEditor_1;
fOldValue = ""; //$NON-NLS-1$
fViewer = new JDISourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
fViewer.setInput(parent);
IDocument document = new Document();
JDIDebugUIPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING);
// we can only do code assist if there is an associated type
IJavaDebugContentAssistContext context = null;
IType type = BreakpointUtils.getType(fBreakpoint);
if (type == null) {
context = new TypeContext(null, -1);
}
else {
try {
String source = null;
ICompilationUnit compilationUnit = type.getCompilationUnit();
if (compilationUnit != null && compilationUnit.getJavaProject().getProject().exists()) {
source = compilationUnit.getSource();
}
else {
IClassFile classFile = type.getClassFile();
if (classFile != null) {
source = classFile.getSource();
}
}
int lineNumber = fBreakpoint.getMarker().getAttribute(IMarker.LINE_NUMBER, -1);
int position= -1;
if (source != null && lineNumber != -1) {
try {
position = new Document(source).getLineOffset(lineNumber - 1);
}
catch (BadLocationException e) {JDIDebugUIPlugin.log(e);}
}
context = new TypeContext(type, position);
}
catch (CoreException e) {JDIDebugUIPlugin.log(e);}
}
fCompletionProcessor = new JavaDebugContentAssistProcessor(context);
fViewer.configure(new DisplayViewerConfiguration() {
public IContentAssistProcessor getContentAssistantProcessor() {
return fCompletionProcessor;
}
});
fViewer.setEditable(true);
- document.set(condition);
+ //if we don't check upstream tracing can throw assertion exceptions see bug 181914
+ document.set((condition == null ? "" : condition)); //$NON-NLS-1$
fViewer.setDocument(document);
fViewer.setUndoManager(new TextViewerUndoManager(10));
fViewer.getUndoManager().connect(fViewer);
fDocumentListener = new IDocumentListener() {
public void documentAboutToBeChanged(DocumentEvent event) {
}
public void documentChanged(DocumentEvent event) {
valueChanged();
}
};
fViewer.getDocument().addDocumentListener(fDocumentListener);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.heightHint = fPage.convertHeightInCharsToPixels(10);
gd.widthHint = fPage.convertWidthInCharsToPixels(40);
fViewer.getControl().setLayoutData(gd);
fHandler = new AbstractHandler() {
public Object execute(ExecutionEvent event) throws org.eclipse.core.commands.ExecutionException {
fViewer.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
return null;
}
};
fHandlerService = (IHandlerService) PlatformUI.getWorkbench().getAdapter(IHandlerService.class);
}
catch (CoreException exception) {JDIDebugUIPlugin.log(exception);}
}
/**
* Returns the condition defined in the source viewer.
* @return the contents of this condition editor
*/
public String getCondition() {
return fViewer.getDocument().get();
}
/**
* @see org.eclipse.jface.preference.FieldEditor#refreshValidState()
*/
protected void refreshValidState() {
if (!fViewer.isEditable()) {
fPage.removeErrorMessage(fErrorMessage);
} else {
String text = fViewer.getDocument().get();
if (!(text != null && text.trim().length() > 0)) {
fPage.addErrorMessage(fErrorMessage);
} else {
fPage.removeErrorMessage(fErrorMessage);
}
}
}
/**
* @see org.eclipse.jface.preference.FieldEditor#setEnabled(boolean, org.eclipse.swt.widgets.Composite)
*/
public void setEnabled(boolean enabled) {
fViewer.setEditable(enabled);
fViewer.getTextWidget().setEnabled(enabled);
if (enabled) {
fViewer.updateViewerColors();
fViewer.getTextWidget().setFocus();
fActivation = fHandlerService.activateHandler(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS, fHandler);
} else {
Color color = fViewer.getControl().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
fViewer.getTextWidget().setBackground(color);
if(fActivation != null) {
fHandlerService.deactivateHandler(fActivation);
}
}
valueChanged();
}
/**
* Handle that the value changed
*/
protected void valueChanged() {
String newValue = fViewer.getDocument().get();
if (!newValue.equals(fOldValue)) {
fOldValue = newValue;
}
refreshValidState();
}
/**
* Dispose of the handlers, etc
*/
public void dispose() {
if (fViewer.isEditable()) {
fHandlerService.deactivateHandler(fActivation);
}
fViewer.getDocument().removeDocumentListener(fDocumentListener);
fViewer.dispose();
}
}
| true | true | public BreakpointConditionEditor(Composite parent, JavaLineBreakpointPage page) {
fPage = page;
fBreakpoint = (IJavaLineBreakpoint) fPage.getBreakpoint();
String condition = new String();
try {
condition = fBreakpoint.getCondition();
fErrorMessage = PropertyPageMessages.BreakpointConditionEditor_1;
fOldValue = ""; //$NON-NLS-1$
fViewer = new JDISourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
fViewer.setInput(parent);
IDocument document = new Document();
JDIDebugUIPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING);
// we can only do code assist if there is an associated type
IJavaDebugContentAssistContext context = null;
IType type = BreakpointUtils.getType(fBreakpoint);
if (type == null) {
context = new TypeContext(null, -1);
}
else {
try {
String source = null;
ICompilationUnit compilationUnit = type.getCompilationUnit();
if (compilationUnit != null && compilationUnit.getJavaProject().getProject().exists()) {
source = compilationUnit.getSource();
}
else {
IClassFile classFile = type.getClassFile();
if (classFile != null) {
source = classFile.getSource();
}
}
int lineNumber = fBreakpoint.getMarker().getAttribute(IMarker.LINE_NUMBER, -1);
int position= -1;
if (source != null && lineNumber != -1) {
try {
position = new Document(source).getLineOffset(lineNumber - 1);
}
catch (BadLocationException e) {JDIDebugUIPlugin.log(e);}
}
context = new TypeContext(type, position);
}
catch (CoreException e) {JDIDebugUIPlugin.log(e);}
}
fCompletionProcessor = new JavaDebugContentAssistProcessor(context);
fViewer.configure(new DisplayViewerConfiguration() {
public IContentAssistProcessor getContentAssistantProcessor() {
return fCompletionProcessor;
}
});
fViewer.setEditable(true);
document.set(condition);
fViewer.setDocument(document);
fViewer.setUndoManager(new TextViewerUndoManager(10));
fViewer.getUndoManager().connect(fViewer);
fDocumentListener = new IDocumentListener() {
public void documentAboutToBeChanged(DocumentEvent event) {
}
public void documentChanged(DocumentEvent event) {
valueChanged();
}
};
fViewer.getDocument().addDocumentListener(fDocumentListener);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.heightHint = fPage.convertHeightInCharsToPixels(10);
gd.widthHint = fPage.convertWidthInCharsToPixels(40);
fViewer.getControl().setLayoutData(gd);
fHandler = new AbstractHandler() {
public Object execute(ExecutionEvent event) throws org.eclipse.core.commands.ExecutionException {
fViewer.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
return null;
}
};
fHandlerService = (IHandlerService) PlatformUI.getWorkbench().getAdapter(IHandlerService.class);
}
catch (CoreException exception) {JDIDebugUIPlugin.log(exception);}
}
| public BreakpointConditionEditor(Composite parent, JavaLineBreakpointPage page) {
fPage = page;
fBreakpoint = (IJavaLineBreakpoint) fPage.getBreakpoint();
String condition = new String();
try {
condition = fBreakpoint.getCondition();
fErrorMessage = PropertyPageMessages.BreakpointConditionEditor_1;
fOldValue = ""; //$NON-NLS-1$
fViewer = new JDISourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
fViewer.setInput(parent);
IDocument document = new Document();
JDIDebugUIPlugin.getDefault().getJavaTextTools().setupJavaDocumentPartitioner(document, IJavaPartitions.JAVA_PARTITIONING);
// we can only do code assist if there is an associated type
IJavaDebugContentAssistContext context = null;
IType type = BreakpointUtils.getType(fBreakpoint);
if (type == null) {
context = new TypeContext(null, -1);
}
else {
try {
String source = null;
ICompilationUnit compilationUnit = type.getCompilationUnit();
if (compilationUnit != null && compilationUnit.getJavaProject().getProject().exists()) {
source = compilationUnit.getSource();
}
else {
IClassFile classFile = type.getClassFile();
if (classFile != null) {
source = classFile.getSource();
}
}
int lineNumber = fBreakpoint.getMarker().getAttribute(IMarker.LINE_NUMBER, -1);
int position= -1;
if (source != null && lineNumber != -1) {
try {
position = new Document(source).getLineOffset(lineNumber - 1);
}
catch (BadLocationException e) {JDIDebugUIPlugin.log(e);}
}
context = new TypeContext(type, position);
}
catch (CoreException e) {JDIDebugUIPlugin.log(e);}
}
fCompletionProcessor = new JavaDebugContentAssistProcessor(context);
fViewer.configure(new DisplayViewerConfiguration() {
public IContentAssistProcessor getContentAssistantProcessor() {
return fCompletionProcessor;
}
});
fViewer.setEditable(true);
//if we don't check upstream tracing can throw assertion exceptions see bug 181914
document.set((condition == null ? "" : condition)); //$NON-NLS-1$
fViewer.setDocument(document);
fViewer.setUndoManager(new TextViewerUndoManager(10));
fViewer.getUndoManager().connect(fViewer);
fDocumentListener = new IDocumentListener() {
public void documentAboutToBeChanged(DocumentEvent event) {
}
public void documentChanged(DocumentEvent event) {
valueChanged();
}
};
fViewer.getDocument().addDocumentListener(fDocumentListener);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.heightHint = fPage.convertHeightInCharsToPixels(10);
gd.widthHint = fPage.convertWidthInCharsToPixels(40);
fViewer.getControl().setLayoutData(gd);
fHandler = new AbstractHandler() {
public Object execute(ExecutionEvent event) throws org.eclipse.core.commands.ExecutionException {
fViewer.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
return null;
}
};
fHandlerService = (IHandlerService) PlatformUI.getWorkbench().getAdapter(IHandlerService.class);
}
catch (CoreException exception) {JDIDebugUIPlugin.log(exception);}
}
|
diff --git a/src/main/java/org/cweili/wray/util/Captcha.java b/src/main/java/org/cweili/wray/util/Captcha.java
index 1705ae8..7957cd4 100644
--- a/src/main/java/org/cweili/wray/util/Captcha.java
+++ b/src/main/java/org/cweili/wray/util/Captcha.java
@@ -1,98 +1,98 @@
/**
*
*/
package org.cweili.wray.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
/**
* 生成验证码
*
* @author Cweili
* @version 2013-4-16 下午5:35:20
*
*/
public class Captcha {
private static Random random = new Random();
public static String getRandomString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; ++i) {
sb.append((char) (random.nextInt(26) + 65));
}
return sb.toString();
}
public static Color getRandomColor() {
return getRandomColor(0, 255);
}
public static Color getRandomColor(boolean dark) {
return dark ? getRandomColor(0, 127) : getRandomColor(128, 255);
}
public static Color getRandomColor(int begin, int end) {
return new Color(random.nextInt(end - begin) + begin, random.nextInt(end - begin) + begin,
random.nextInt(end - begin) + begin);
}
public static BufferedImage out(String str, int width, int height) throws IOException {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bi.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 填充背景
g.setColor(getRandomColor(false));
g.fillRect(0, 0, width, height);
// 画随机线
- for (int i = 0; i < 250; ++i) {
+ for (int i = 0; i < 50; ++i) {
g.setColor(getRandomColor());
int x = random.nextInt(width - 2) + 1;
int y = random.nextInt(height - 2) + 1;
int x2 = x + random.nextInt(20) + 1;
int y2 = random.nextInt(20) + 1;
y2 = random.nextInt(2) == 1 ? y - y2 : y + y2;
g.drawLine(x, y, x2, y2);
}
Font f = new Font("Tahoma", Font.BOLD, height * 3 / 4);
g.setFont(f);
// 画字符
for (int i = 0; i < str.length(); ++i) {
int x = width / (str.length() + 1) * i + width / 10;
int y = height * 4 / 5 - height * 1 / 6 + random.nextInt(height * 1 / 3);
// 旋转
AffineTransform at = new AffineTransform();
at.rotate(random.nextDouble() * 30 * Math.PI / (double) 180, x, 0);
// 缩放
float sc = random.nextFloat() + 0.8f;
sc = sc > 1f ? 1f : sc;
at.scale(1f, sc);
g.setTransform(at);
// 画阴影
g.setColor(Color.black);
g.drawString(str.charAt(i) + "", x + 1, y + 1);
// 画字符
g.setColor(getRandomColor());
g.drawString(str.charAt(i) + "", x, y);
}
g.dispose();
return bi;
}
}
| true | true | public static BufferedImage out(String str, int width, int height) throws IOException {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bi.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 填充背景
g.setColor(getRandomColor(false));
g.fillRect(0, 0, width, height);
// 画随机线
for (int i = 0; i < 250; ++i) {
g.setColor(getRandomColor());
int x = random.nextInt(width - 2) + 1;
int y = random.nextInt(height - 2) + 1;
int x2 = x + random.nextInt(20) + 1;
int y2 = random.nextInt(20) + 1;
y2 = random.nextInt(2) == 1 ? y - y2 : y + y2;
g.drawLine(x, y, x2, y2);
}
Font f = new Font("Tahoma", Font.BOLD, height * 3 / 4);
g.setFont(f);
// 画字符
for (int i = 0; i < str.length(); ++i) {
int x = width / (str.length() + 1) * i + width / 10;
int y = height * 4 / 5 - height * 1 / 6 + random.nextInt(height * 1 / 3);
// 旋转
AffineTransform at = new AffineTransform();
at.rotate(random.nextDouble() * 30 * Math.PI / (double) 180, x, 0);
// 缩放
float sc = random.nextFloat() + 0.8f;
sc = sc > 1f ? 1f : sc;
at.scale(1f, sc);
g.setTransform(at);
// 画阴影
g.setColor(Color.black);
g.drawString(str.charAt(i) + "", x + 1, y + 1);
// 画字符
g.setColor(getRandomColor());
g.drawString(str.charAt(i) + "", x, y);
}
g.dispose();
return bi;
}
| public static BufferedImage out(String str, int width, int height) throws IOException {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bi.getGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 填充背景
g.setColor(getRandomColor(false));
g.fillRect(0, 0, width, height);
// 画随机线
for (int i = 0; i < 50; ++i) {
g.setColor(getRandomColor());
int x = random.nextInt(width - 2) + 1;
int y = random.nextInt(height - 2) + 1;
int x2 = x + random.nextInt(20) + 1;
int y2 = random.nextInt(20) + 1;
y2 = random.nextInt(2) == 1 ? y - y2 : y + y2;
g.drawLine(x, y, x2, y2);
}
Font f = new Font("Tahoma", Font.BOLD, height * 3 / 4);
g.setFont(f);
// 画字符
for (int i = 0; i < str.length(); ++i) {
int x = width / (str.length() + 1) * i + width / 10;
int y = height * 4 / 5 - height * 1 / 6 + random.nextInt(height * 1 / 3);
// 旋转
AffineTransform at = new AffineTransform();
at.rotate(random.nextDouble() * 30 * Math.PI / (double) 180, x, 0);
// 缩放
float sc = random.nextFloat() + 0.8f;
sc = sc > 1f ? 1f : sc;
at.scale(1f, sc);
g.setTransform(at);
// 画阴影
g.setColor(Color.black);
g.drawString(str.charAt(i) + "", x + 1, y + 1);
// 画字符
g.setColor(getRandomColor());
g.drawString(str.charAt(i) + "", x, y);
}
g.dispose();
return bi;
}
|
diff --git a/src/ca/strangebrew/DilutedRecipe.java b/src/ca/strangebrew/DilutedRecipe.java
index 591643c..4d163e9 100644
--- a/src/ca/strangebrew/DilutedRecipe.java
+++ b/src/ca/strangebrew/DilutedRecipe.java
@@ -1,117 +1,118 @@
package ca.strangebrew;
public class DilutedRecipe extends Recipe {
private Quantity addVol;
// A diluted recipe can only be created from an undiluted recipe
private DilutedRecipe() {
}
// Create a new Diluted Recipe with 0 added water
public DilutedRecipe(Recipe r) {
super(r);
this.addVol = new Quantity(super.getVolUnits(), 0);
}
// Create a diluted recipe from a recipe and an amount of dilution volumn
public DilutedRecipe(Recipe r, Quantity dil) {
super(r);
this.addVol = new Quantity(dil);
}
// Specialized Functions
public double getAddVol(final String u) {
return this.addVol.getValueAs(u);
}
public void setAddVol(final Quantity a) {
addVol = a;
}
private double calcDilutionFactor() {
return (this.getAddVol(super.getVolUnits()) + super.getFinalWortVol(super.getVolUnits())) / super.getFinalWortVol(super.getVolUnits());
}
// Overrides
public void setVolUnits(final String v) {
super.setVolUnits(v);
this.addVol.setUnits(v);
}
public double getFinalWortVol(final String s) {
return this.getAddVol(s) + super.getFinalWortVol(s);
}
public double getColour() {
return getColour(getColourMethod());
}
public double getColour(final String method) {
return BrewCalcs.calcColour(getMcu() / this.calcDilutionFactor(), method);
}
public double getIbu() {
return super.getIbu() / this.calcDilutionFactor();
}
public double getEstOg() {
return ((super.getEstOg() - 1) / this.calcDilutionFactor()) + 1;
}
public double getAlcohol() {
return super.getAlcohol() / this.calcDilutionFactor();
}
public String toXML(final String printOptions) {
StringBuffer unDil = new StringBuffer(super.toXML(printOptions));
String dil = "";
// This is UGGLY! :)
dil += " <ADDED_VOLUME>" + SBStringUtils.format(addVol.getValue(), 2) + "</ADDED_VOLUME>\n";
+ dil += " <UNITS>" + addVol.getUnits() + "</UNITS>\n";
int offset = unDil.indexOf("</DETAILS>\n");
unDil.insert(offset, dil);
return unDil.toString();
}
public String toText() {
String unDil = super.toText();
unDil += "Dilute With: " + SBStringUtils.format(addVol.getValue(), 2) + addVol.getUnits() + "\n";
return unDil;
}
// public double getBUGU() {
// double bugu = 0.0;
// if ( estOg != 1.0 ) {
// bugu = ibu / ((estOg - 1) * 1000);
// }
// return bugu;
// }
// Accessors to original numbers for DilPanel
public double getOrigFinalWortVol(final String s) {
return super.getFinalWortVol(s);
}
public double getOrigColour() {
return super.getColour();
}
public double getOrigColour(final String method) {
return super.getColour(method);
}
public double getOrigIbu() {
return super.getIbu();
}
public double getOrigEstOg() {
return super.getEstOg();
}
public double getOrigAlcohol() {
return super.getAlcohol();
}
}
| true | true | public String toXML(final String printOptions) {
StringBuffer unDil = new StringBuffer(super.toXML(printOptions));
String dil = "";
// This is UGGLY! :)
dil += " <ADDED_VOLUME>" + SBStringUtils.format(addVol.getValue(), 2) + "</ADDED_VOLUME>\n";
int offset = unDil.indexOf("</DETAILS>\n");
unDil.insert(offset, dil);
return unDil.toString();
}
| public String toXML(final String printOptions) {
StringBuffer unDil = new StringBuffer(super.toXML(printOptions));
String dil = "";
// This is UGGLY! :)
dil += " <ADDED_VOLUME>" + SBStringUtils.format(addVol.getValue(), 2) + "</ADDED_VOLUME>\n";
dil += " <UNITS>" + addVol.getUnits() + "</UNITS>\n";
int offset = unDil.indexOf("</DETAILS>\n");
unDil.insert(offset, dil);
return unDil.toString();
}
|
diff --git a/src/net/zekjur/davsync/UploadService.java b/src/net/zekjur/davsync/UploadService.java
index 9658ba0..bf8f712 100644
--- a/src/net/zekjur/davsync/UploadService.java
+++ b/src/net/zekjur/davsync/UploadService.java
@@ -1,153 +1,153 @@
package net.zekjur.davsync;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import net.zekjur.davsync.CountingInputStreamEntity.UploadListener;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthenticationException;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.IntentService;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.app.Notification;
import android.app.Notification.Builder;
import android.util.Log;
public class UploadService extends IntentService {
public UploadService() {
super("UploadService");
}
/*
* Resolve a Uri like “content://media/external/images/media/9210” to an
* actual filename, like “IMG_20130304_181119.jpg”
*/
private String filenameFromUri(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor == null)
return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
Uri filePathUri = Uri.parse(cursor.getString(column_index));
return filePathUri.getLastPathSegment().toString();
}
@Override
protected void onHandleIntent(Intent intent) {
final Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
Log.d("davsyncs", "Uploading " + uri.toString());
SharedPreferences preferences = getSharedPreferences("net.zekjur.davsync_preferences", Context.MODE_PRIVATE);
String webdavUrl = preferences.getString("webdav_url", null);
String webdavUser = preferences.getString("webdav_user", null);
String webdavPassword = preferences.getString("webdav_password", null);
if (webdavUrl == null) {
Log.d("davsyncs", "No WebDAV URL set up.");
return;
}
ContentResolver cr = getContentResolver();
String filename = this.filenameFromUri(uri);
if (filename == null) {
Log.d("davsyncs", "filenameFromUri returned null");
return;
}
final Builder mBuilder = new Notification.Builder(this);
mBuilder.setContentTitle("Uploading to WebDAV server");
mBuilder.setContentText(filename);
mBuilder.setSmallIcon(android.R.drawable.ic_menu_upload);
mBuilder.setOngoing(true);
mBuilder.setProgress(100, 30, false);
final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(uri.toString(), 0, mBuilder.build());
HttpPut httpPut = new HttpPut(webdavUrl + filename);
ParcelFileDescriptor fd;
InputStream stream;
try {
fd = cr.openFileDescriptor(uri, "r");
stream = cr.openInputStream(uri);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
CountingInputStreamEntity entity = new CountingInputStreamEntity(stream, fd.getStatSize());
entity.setUploadListener(new UploadListener() {
@Override
public void onChange(int percent) {
mBuilder.setProgress(100, percent, false);
mNotificationManager.notify(uri.toString(), 0, mBuilder.build());
}
});
httpPut.setEntity(entity);
DefaultHttpClient httpClient = new DefaultHttpClient();
if (webdavUser != null && webdavPassword != null) {
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(webdavUser, webdavPassword);
httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
try {
httpPut.addHeader(new BasicScheme().authenticate(credentials, httpPut));
} catch (AuthenticationException e1) {
e1.printStackTrace();
return;
}
}
try {
HttpResponse response = httpClient.execute(httpPut);
int status = response.getStatusLine().getStatusCode();
- // 201 means the file was created, 200 means it was stored but
- // already existed.
- if (status == 201 || status == 200) {
+ // 201 means the file was created.
+ // 200 and 204 mean it was stored but already existed.
+ if (status == 201 || status == 200 || status == 204) {
// The file was uploaded, so we remove the ongoing notification,
// remove it from the queue and that’s it.
mNotificationManager.cancel(uri.toString(), 0);
DavSyncOpenHelper helper = new DavSyncOpenHelper(this);
helper.removeUriFromQueue(uri.toString());
return;
}
Log.d("davsyncs", "" + response.getStatusLine());
mBuilder.setContentText(filename + ": " + response.getStatusLine());
} catch (ClientProtocolException e) {
e.printStackTrace();
mBuilder.setContentText(filename + ": " + e.getLocalizedMessage());
} catch (IOException e) {
e.printStackTrace();
mBuilder.setContentText(filename + ": " + e.getLocalizedMessage());
}
// XXX: It would be good to provide an option to try again.
// (or try it again automatically?)
// XXX: possibly we should re-queue the images in the database
mBuilder.setContentTitle("Error uploading to WebDAV server");
mBuilder.setProgress(0, 0, false);
mBuilder.setOngoing(false);
mNotificationManager.notify(uri.toString(), 0, mBuilder.build());
}
}
| true | true | protected void onHandleIntent(Intent intent) {
final Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
Log.d("davsyncs", "Uploading " + uri.toString());
SharedPreferences preferences = getSharedPreferences("net.zekjur.davsync_preferences", Context.MODE_PRIVATE);
String webdavUrl = preferences.getString("webdav_url", null);
String webdavUser = preferences.getString("webdav_user", null);
String webdavPassword = preferences.getString("webdav_password", null);
if (webdavUrl == null) {
Log.d("davsyncs", "No WebDAV URL set up.");
return;
}
ContentResolver cr = getContentResolver();
String filename = this.filenameFromUri(uri);
if (filename == null) {
Log.d("davsyncs", "filenameFromUri returned null");
return;
}
final Builder mBuilder = new Notification.Builder(this);
mBuilder.setContentTitle("Uploading to WebDAV server");
mBuilder.setContentText(filename);
mBuilder.setSmallIcon(android.R.drawable.ic_menu_upload);
mBuilder.setOngoing(true);
mBuilder.setProgress(100, 30, false);
final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(uri.toString(), 0, mBuilder.build());
HttpPut httpPut = new HttpPut(webdavUrl + filename);
ParcelFileDescriptor fd;
InputStream stream;
try {
fd = cr.openFileDescriptor(uri, "r");
stream = cr.openInputStream(uri);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
CountingInputStreamEntity entity = new CountingInputStreamEntity(stream, fd.getStatSize());
entity.setUploadListener(new UploadListener() {
@Override
public void onChange(int percent) {
mBuilder.setProgress(100, percent, false);
mNotificationManager.notify(uri.toString(), 0, mBuilder.build());
}
});
httpPut.setEntity(entity);
DefaultHttpClient httpClient = new DefaultHttpClient();
if (webdavUser != null && webdavPassword != null) {
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(webdavUser, webdavPassword);
httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
try {
httpPut.addHeader(new BasicScheme().authenticate(credentials, httpPut));
} catch (AuthenticationException e1) {
e1.printStackTrace();
return;
}
}
try {
HttpResponse response = httpClient.execute(httpPut);
int status = response.getStatusLine().getStatusCode();
// 201 means the file was created, 200 means it was stored but
// already existed.
if (status == 201 || status == 200) {
// The file was uploaded, so we remove the ongoing notification,
// remove it from the queue and that’s it.
mNotificationManager.cancel(uri.toString(), 0);
DavSyncOpenHelper helper = new DavSyncOpenHelper(this);
helper.removeUriFromQueue(uri.toString());
return;
}
Log.d("davsyncs", "" + response.getStatusLine());
mBuilder.setContentText(filename + ": " + response.getStatusLine());
} catch (ClientProtocolException e) {
e.printStackTrace();
mBuilder.setContentText(filename + ": " + e.getLocalizedMessage());
} catch (IOException e) {
e.printStackTrace();
mBuilder.setContentText(filename + ": " + e.getLocalizedMessage());
}
// XXX: It would be good to provide an option to try again.
// (or try it again automatically?)
// XXX: possibly we should re-queue the images in the database
mBuilder.setContentTitle("Error uploading to WebDAV server");
mBuilder.setProgress(0, 0, false);
mBuilder.setOngoing(false);
mNotificationManager.notify(uri.toString(), 0, mBuilder.build());
}
| protected void onHandleIntent(Intent intent) {
final Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
Log.d("davsyncs", "Uploading " + uri.toString());
SharedPreferences preferences = getSharedPreferences("net.zekjur.davsync_preferences", Context.MODE_PRIVATE);
String webdavUrl = preferences.getString("webdav_url", null);
String webdavUser = preferences.getString("webdav_user", null);
String webdavPassword = preferences.getString("webdav_password", null);
if (webdavUrl == null) {
Log.d("davsyncs", "No WebDAV URL set up.");
return;
}
ContentResolver cr = getContentResolver();
String filename = this.filenameFromUri(uri);
if (filename == null) {
Log.d("davsyncs", "filenameFromUri returned null");
return;
}
final Builder mBuilder = new Notification.Builder(this);
mBuilder.setContentTitle("Uploading to WebDAV server");
mBuilder.setContentText(filename);
mBuilder.setSmallIcon(android.R.drawable.ic_menu_upload);
mBuilder.setOngoing(true);
mBuilder.setProgress(100, 30, false);
final NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(uri.toString(), 0, mBuilder.build());
HttpPut httpPut = new HttpPut(webdavUrl + filename);
ParcelFileDescriptor fd;
InputStream stream;
try {
fd = cr.openFileDescriptor(uri, "r");
stream = cr.openInputStream(uri);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
CountingInputStreamEntity entity = new CountingInputStreamEntity(stream, fd.getStatSize());
entity.setUploadListener(new UploadListener() {
@Override
public void onChange(int percent) {
mBuilder.setProgress(100, percent, false);
mNotificationManager.notify(uri.toString(), 0, mBuilder.build());
}
});
httpPut.setEntity(entity);
DefaultHttpClient httpClient = new DefaultHttpClient();
if (webdavUser != null && webdavPassword != null) {
AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(webdavUser, webdavPassword);
httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
try {
httpPut.addHeader(new BasicScheme().authenticate(credentials, httpPut));
} catch (AuthenticationException e1) {
e1.printStackTrace();
return;
}
}
try {
HttpResponse response = httpClient.execute(httpPut);
int status = response.getStatusLine().getStatusCode();
// 201 means the file was created.
// 200 and 204 mean it was stored but already existed.
if (status == 201 || status == 200 || status == 204) {
// The file was uploaded, so we remove the ongoing notification,
// remove it from the queue and that’s it.
mNotificationManager.cancel(uri.toString(), 0);
DavSyncOpenHelper helper = new DavSyncOpenHelper(this);
helper.removeUriFromQueue(uri.toString());
return;
}
Log.d("davsyncs", "" + response.getStatusLine());
mBuilder.setContentText(filename + ": " + response.getStatusLine());
} catch (ClientProtocolException e) {
e.printStackTrace();
mBuilder.setContentText(filename + ": " + e.getLocalizedMessage());
} catch (IOException e) {
e.printStackTrace();
mBuilder.setContentText(filename + ": " + e.getLocalizedMessage());
}
// XXX: It would be good to provide an option to try again.
// (or try it again automatically?)
// XXX: possibly we should re-queue the images in the database
mBuilder.setContentTitle("Error uploading to WebDAV server");
mBuilder.setProgress(0, 0, false);
mBuilder.setOngoing(false);
mNotificationManager.notify(uri.toString(), 0, mBuilder.build());
}
|
diff --git a/src/org/ebookdroid/core/curl/AbstractPageAnimator.java b/src/org/ebookdroid/core/curl/AbstractPageAnimator.java
index 503d1c5c..d6e2d8df 100644
--- a/src/org/ebookdroid/core/curl/AbstractPageAnimator.java
+++ b/src/org/ebookdroid/core/curl/AbstractPageAnimator.java
@@ -1,366 +1,366 @@
package org.ebookdroid.core.curl;
import org.ebookdroid.R;
import org.ebookdroid.core.Page;
import org.ebookdroid.core.SinglePageDocumentView;
import org.ebookdroid.core.ViewState;
import org.ebookdroid.core.bitmaps.BitmapManager;
import org.ebookdroid.core.bitmaps.BitmapRef;
import org.ebookdroid.core.models.DocumentModel;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public abstract class AbstractPageAnimator extends SinglePageView implements PageAnimator {
/** Fixed update time used to create a smooth curl animation */
protected int mUpdateRate;
/** Handler used to auto flip time based */
protected FlipAnimationHandler mAnimationHandler;
/** Point used to move */
protected Vector2D mMovement;
/** Defines the flip direction that is currently considered */
protected boolean bFlipRight;
/** If TRUE we are currently auto-flipping */
protected boolean bFlipping;
/** Used to control touch input blocking */
protected boolean bBlockTouchInput = false;
/** Enable input after the next draw event */
protected boolean bEnableInputAfterDraw = false;
protected Vector2D mA = new Vector2D(0, 0);
/** The initial offset for x and y axis movements */
protected int mInitialEdgeOffset;
/** The finger position */
protected Vector2D mFinger;
/** Movement point form the last frame */
protected Vector2D mOldMovement;
/** TRUE if the user moves the pages */
protected boolean bUserMoves;
protected BitmapRef foreBitmap;
protected int foreBitmapIndex = -1;
protected BitmapRef backBitmap;
protected int backBitmapIndex = -1;
protected Bitmap arrowsBitmap;
protected final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
public AbstractPageAnimator(final PageAnimationType type, final SinglePageDocumentView singlePageDocumentView) {
super(type, singlePageDocumentView);
}
@Override
public void init() {
super.init();
arrowsBitmap = BitmapFactory.decodeResource(view.getBase().getContext().getResources(), R.drawable.arrows);
mMovement = new Vector2D(0, 0);
mFinger = new Vector2D(0, 0);
mOldMovement = new Vector2D(0, 0);
// Create our curl animation handler
mAnimationHandler = new FlipAnimationHandler(this);
// Set the default props
mUpdateRate = 5;
}
@Override
public final boolean isPageVisible(final Page page, final ViewState viewState) {
final int pageIndex = page.index.viewIndex;
return pageIndex == this.foreIndex || pageIndex == this.backIndex;
}
/**
* Swap to next view
*/
protected ViewState nextView(final ViewState viewState) {
final DocumentModel dm = view.getBase().getDocumentModel();
foreIndex = viewState.currentIndex;
if (foreIndex >= dm.getPageCount()) {
foreIndex = 0;
}
backIndex = foreIndex + 1;
if (backIndex >= dm.getPageCount()) {
backIndex = 0;
}
return view.invalidatePages(viewState, dm.getPageObject(foreIndex), dm.getPageObject(backIndex));
}
/**
* Swap to previous view
*/
protected ViewState previousView(final ViewState viewState) {
final DocumentModel dm = view.getBase().getDocumentModel();
backIndex = viewState.currentIndex;
foreIndex = backIndex - 1;
if (foreIndex < 0) {
foreIndex = dm.getPageCount() - 1;
}
return view.invalidatePages(viewState, dm.getPageObject(foreIndex), dm.getPageObject(backIndex));
}
/**
* Execute a step of the flip animation
*/
@Override
public synchronized void FlipAnimationStep() {
if (!bFlipping) {
return;
}
final int width = view.getWidth();
// No input when flipping
bBlockTouchInput = true;
// Handle speed
float curlSpeed = width / 5;
if (!bFlipRight) {
curlSpeed *= -1;
}
// Move us
mMovement.x += curlSpeed;
mMovement = fixMovement(mMovement, false);
// Create values
lock.writeLock().lock();
try {
updateValues();
if (mA.x < getLeftBound()) {
mA.x = getLeftBound() - 1;
}
if (mA.x > width - 1) {
mA.x = width;
}
} finally {
lock.writeLock().unlock();
}
// Check for endings :D
if (mA.x <= getLeftBound() || mA.x >= width - 1) {
bFlipping = false;
if (bFlipRight) {
view.goToPageImpl(backIndex);
foreIndex = backIndex;
} else {
view.goToPageImpl(foreIndex);
}
// Create values
lock.writeLock().lock();
try {
resetClipEdge();
updateValues();
} finally {
lock.writeLock().unlock();
}
// Enable touch input after the next draw event
bEnableInputAfterDraw = true;
} else {
mAnimationHandler.sleep(mUpdateRate);
}
// Force a new draw call
view.redrawView();
}
protected float getLeftBound() {
return 1;
}
protected abstract void resetClipEdge();
protected abstract Vector2D fixMovement(Vector2D point, final boolean bMaintainMoveDir);
protected abstract void drawBackground(final Canvas canvas, final ViewState viewState);
protected abstract void drawForeground(final Canvas canvas, final ViewState viewState);
protected abstract void drawExtraObjects(final Canvas canvas, final ViewState viewState);
/**
* Update points values values.
*/
protected abstract void updateValues();
/**
* @see org.ebookdroid.core.curl.PageAnimator#onDraw(android.graphics.Canvas)
*/
@Override
public final synchronized void draw(final Canvas canvas, final ViewState viewState) {
if (!enabled()) {
BitmapManager.release(foreBitmap);
BitmapManager.release(backBitmap);
foreBitmap = null;
backBitmap = null;
super.draw(canvas, viewState);
return;
}
// We need to initialize all size data when we first draw the view
if (!isViewDrawn()) {
setViewDrawn(true);
onFirstDrawEvent(canvas, viewState);
}
canvas.drawColor(Color.BLACK);
// Draw our elements
lock.readLock().lock();
try {
drawInternal(canvas, viewState);
drawExtraObjects(canvas, viewState);
} finally {
lock.readLock().unlock();
}
// Check if we can re-enable input
if (bEnableInputAfterDraw) {
bBlockTouchInput = false;
bEnableInputAfterDraw = false;
}
}
protected void drawInternal(Canvas canvas, ViewState viewState) {
drawForeground(canvas, viewState);
if (foreIndex != backIndex) {
drawBackground(canvas, viewState);
}
}
protected abstract void onFirstDrawEvent(Canvas canvas, final ViewState viewState);
@Override
public boolean enabled() {
return view.getScrollLimits().width() <= 0;
}
@Override
- public boolean onTouchEvent(final MotionEvent event) {
+ public final boolean onTouchEvent(final MotionEvent event) {
if (!bBlockTouchInput) {
// Get our finger position
mFinger.x = event.getX();
mFinger.y = event.getY();
final int width = view.getWidth();
ViewState viewState = new ViewState(view);
// Depending on the action do what we need to
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mOldMovement.x = mFinger.x;
mOldMovement.y = mFinger.y;
bUserMoves = false;
return false;
case MotionEvent.ACTION_UP:
if (bUserMoves) {
bUserMoves = false;
bFlipping = true;
FlipAnimationStep();
} else {
return false;
}
break;
case MotionEvent.ACTION_MOVE:
if ((mFinger.distanceSquared(mOldMovement) > 625)) {
if (!bUserMoves) {
// If we moved over the half of the display flip to next
if (mOldMovement.x > (width >> 1)) {
mMovement.x = mInitialEdgeOffset;
mMovement.y = mInitialEdgeOffset;
// Set the right movement flag
bFlipRight = true;
viewState = nextView(viewState);
} else {
// Set the left movement flag
bFlipRight = false;
// go to next previous page
viewState = previousView(viewState);
// Set new movement
mMovement.x = getInitialXForBackFlip(width);
mMovement.y = mInitialEdgeOffset;
}
}
bUserMoves = true;
} else {
if (!bUserMoves) {
break;
}
}
// Get movement
mMovement.x -= mFinger.x - mOldMovement.x;
mMovement.y -= mFinger.y - mOldMovement.y;
mMovement = fixMovement(mMovement, true);
// Make sure the y value get's locked at a nice level
if (mMovement.y <= 1) {
mMovement.y = 1;
}
// Get movement direction
if (mFinger.x < mOldMovement.x) {
bFlipRight = true;
} else {
bFlipRight = false;
}
// Save old movement values
mOldMovement.x = mFinger.x;
mOldMovement.y = mFinger.y;
// Force a new draw call
lock.writeLock().lock();
try {
updateValues();
} finally {
lock.writeLock().unlock();
}
view.redrawView(viewState);
- break;
+ return !bUserMoves;
}
}
// TODO: Only consume event if we need to.
return true;
}
protected int getInitialXForBackFlip(final int width) {
return width;
}
@Override
public void pageUpdated(int viewIndex) {
if (foreBitmapIndex == viewIndex) {
foreBitmapIndex = -1;
}
if (backBitmapIndex == viewIndex) {
backBitmapIndex = -1;
}
}
}
| false | true | public boolean onTouchEvent(final MotionEvent event) {
if (!bBlockTouchInput) {
// Get our finger position
mFinger.x = event.getX();
mFinger.y = event.getY();
final int width = view.getWidth();
ViewState viewState = new ViewState(view);
// Depending on the action do what we need to
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mOldMovement.x = mFinger.x;
mOldMovement.y = mFinger.y;
bUserMoves = false;
return false;
case MotionEvent.ACTION_UP:
if (bUserMoves) {
bUserMoves = false;
bFlipping = true;
FlipAnimationStep();
} else {
return false;
}
break;
case MotionEvent.ACTION_MOVE:
if ((mFinger.distanceSquared(mOldMovement) > 625)) {
if (!bUserMoves) {
// If we moved over the half of the display flip to next
if (mOldMovement.x > (width >> 1)) {
mMovement.x = mInitialEdgeOffset;
mMovement.y = mInitialEdgeOffset;
// Set the right movement flag
bFlipRight = true;
viewState = nextView(viewState);
} else {
// Set the left movement flag
bFlipRight = false;
// go to next previous page
viewState = previousView(viewState);
// Set new movement
mMovement.x = getInitialXForBackFlip(width);
mMovement.y = mInitialEdgeOffset;
}
}
bUserMoves = true;
} else {
if (!bUserMoves) {
break;
}
}
// Get movement
mMovement.x -= mFinger.x - mOldMovement.x;
mMovement.y -= mFinger.y - mOldMovement.y;
mMovement = fixMovement(mMovement, true);
// Make sure the y value get's locked at a nice level
if (mMovement.y <= 1) {
mMovement.y = 1;
}
// Get movement direction
if (mFinger.x < mOldMovement.x) {
bFlipRight = true;
} else {
bFlipRight = false;
}
// Save old movement values
mOldMovement.x = mFinger.x;
mOldMovement.y = mFinger.y;
// Force a new draw call
lock.writeLock().lock();
try {
updateValues();
} finally {
lock.writeLock().unlock();
}
view.redrawView(viewState);
break;
}
}
// TODO: Only consume event if we need to.
return true;
}
| public final boolean onTouchEvent(final MotionEvent event) {
if (!bBlockTouchInput) {
// Get our finger position
mFinger.x = event.getX();
mFinger.y = event.getY();
final int width = view.getWidth();
ViewState viewState = new ViewState(view);
// Depending on the action do what we need to
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mOldMovement.x = mFinger.x;
mOldMovement.y = mFinger.y;
bUserMoves = false;
return false;
case MotionEvent.ACTION_UP:
if (bUserMoves) {
bUserMoves = false;
bFlipping = true;
FlipAnimationStep();
} else {
return false;
}
break;
case MotionEvent.ACTION_MOVE:
if ((mFinger.distanceSquared(mOldMovement) > 625)) {
if (!bUserMoves) {
// If we moved over the half of the display flip to next
if (mOldMovement.x > (width >> 1)) {
mMovement.x = mInitialEdgeOffset;
mMovement.y = mInitialEdgeOffset;
// Set the right movement flag
bFlipRight = true;
viewState = nextView(viewState);
} else {
// Set the left movement flag
bFlipRight = false;
// go to next previous page
viewState = previousView(viewState);
// Set new movement
mMovement.x = getInitialXForBackFlip(width);
mMovement.y = mInitialEdgeOffset;
}
}
bUserMoves = true;
} else {
if (!bUserMoves) {
break;
}
}
// Get movement
mMovement.x -= mFinger.x - mOldMovement.x;
mMovement.y -= mFinger.y - mOldMovement.y;
mMovement = fixMovement(mMovement, true);
// Make sure the y value get's locked at a nice level
if (mMovement.y <= 1) {
mMovement.y = 1;
}
// Get movement direction
if (mFinger.x < mOldMovement.x) {
bFlipRight = true;
} else {
bFlipRight = false;
}
// Save old movement values
mOldMovement.x = mFinger.x;
mOldMovement.y = mFinger.y;
// Force a new draw call
lock.writeLock().lock();
try {
updateValues();
} finally {
lock.writeLock().unlock();
}
view.redrawView(viewState);
return !bUserMoves;
}
}
// TODO: Only consume event if we need to.
return true;
}
|
diff --git a/watersmart-ui/src/main/java/gov/usgs/cida/watersmart/util/UpdateRun.java b/watersmart-ui/src/main/java/gov/usgs/cida/watersmart/util/UpdateRun.java
index e9a8039..b8e9245 100644
--- a/watersmart-ui/src/main/java/gov/usgs/cida/watersmart/util/UpdateRun.java
+++ b/watersmart-ui/src/main/java/gov/usgs/cida/watersmart/util/UpdateRun.java
@@ -1,185 +1,197 @@
package gov.usgs.cida.watersmart.util;
import gov.usgs.cida.config.DynamicReadOnlyProperties;
import gov.usgs.cida.watersmart.common.JNDISingleton;
import gov.usgs.cida.watersmart.common.ModelType;
import gov.usgs.cida.watersmart.common.RunMetadata;
import gov.usgs.cida.watersmart.csw.CSWTransactionHelper;
import java.io.IOException;
import java.io.Writer;
import java.net.URISyntaxException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author isuftin
*/
public class UpdateRun extends HttpServlet {
private static final Logger LOG = LoggerFactory.getLogger(UpdateRun.class);
private static final DynamicReadOnlyProperties props = JNDISingleton.getInstance();
private static final long serialVersionUID = 1L;
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LOG.debug("Received new update request");
String modelerName = request.getParameter("name");
String originalModelerName = request.getParameter("originalName");
String modelId = request.getParameter("modelId");
String modelType = request.getParameter("modeltype");
// Currently not being used since we don't update the modelVersion
// String modelVersion = request.getParameter("version");
String originalModelVersion = request.getParameter("originalModelVersion");
String runIdent = request.getParameter("runIdent");
String originalRunIdent = request.getParameter("originalRunIdent");
String runDate = request.getParameter("creationDate");
String originalRunDate = request.getParameter("originalCreationDate");
String scenario = request.getParameter("scenario");
String originalScenario = request.getParameter("originalScenario");
String comments = request.getParameter("comments");
String originalComments = request.getParameter("originalComments");
String email = request.getParameter("email");
String wfsUrl = request.getParameter("wfsUrl");
String layer = request.getParameter("layer");
String commonAttr = request.getParameter("commonAttr");
Boolean updateAsBest = "on".equalsIgnoreCase(request.getParameter("markAsBest")) ? Boolean.TRUE : Boolean.FALSE;
Boolean rerun = Boolean.parseBoolean(request.getParameter("rerun")); // If this is true, we only re-run the R processing
String responseText;
RunMetadata newRunMetadata;
ModelType modelTypeEnum = null;
if ("prms".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.PRMS;
}
- if ("afinch".equals(modelType.toLowerCase())) {
+ else if ("afinch".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.AFINCH;
}
- if ("waters".equals(modelType.toLowerCase())) {
+ else if ("waters".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.WATERS;
}
- if ("sye".equals(modelType.toLowerCase())) {
+ else if ("sye".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.SYE;
}
+ else if ("stats".equals(modelType.toLowerCase())) {
+ modelTypeEnum = ModelType.STATS;
+ }
+ else if ("prms2".equals(modelType.toLowerCase())) {
+ modelTypeEnum = ModelType.PRMS2;
+ }
+ else if ("waterfall".equals(modelType.toLowerCase())) {
+ modelTypeEnum = ModelType.WATERFALL;
+ }
+ else {
+ throw new IllegalArgumentException("Model Type does not exist!!");
+ }
RunMetadata originalRunMetadata = new RunMetadata(
modelTypeEnum,
modelId,
originalModelerName,
originalModelVersion,
originalRunIdent,
originalRunDate,
originalScenario,
originalComments,
email,
wfsUrl,
layer,
commonAttr,
updateAsBest);
if (rerun) {
- String sosEndpoint = props.getProperty("watersmart.sos.model.repo") + originalRunMetadata.getTypeString() + "/" + originalRunMetadata.getFileName();
+ String sosEndpoint = props.getProperty("watersmart.sos.model.repo") + originalRunMetadata.getTypeString() + "/" + originalRunMetadata.getFileName() + ".nc";
WPSImpl impl = new WPSImpl();
String implResponse = impl.executeProcess(sosEndpoint, originalRunMetadata);
Boolean processStarted = implResponse.toLowerCase().equals("ok");
responseText = "{success: "+processStarted.toString()+", message: '" + implResponse + "'}";
} else {
newRunMetadata = new RunMetadata(
modelTypeEnum,
modelId,
modelerName,
originalModelVersion,
runIdent,
runDate,
scenario,
comments,
email,
wfsUrl,
layer,
commonAttr,
updateAsBest);
CSWTransactionHelper helper = new CSWTransactionHelper(newRunMetadata, null, new HashMap<String, String>());
try {
String results = helper.updateRunMetadata(originalRunMetadata);
// TODO- parse xml, make sure stuff happened alright, if so don't say success
responseText = "{success: true, msg: 'The record has been updated'}";
} catch (IOException ex) {
responseText = "{success: false, msg: '" + ex.getMessage() + "'}";
} catch (URISyntaxException ex) {
responseText = "{success: false, msg: '" + ex.getMessage() + "'}";
}
}
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
try {
Writer writer = response.getWriter();
writer.write(responseText);
writer.close();
} catch (IOException ex) {
LOG.warn("An error occurred while trying to send response to client. ", ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| false | true | protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LOG.debug("Received new update request");
String modelerName = request.getParameter("name");
String originalModelerName = request.getParameter("originalName");
String modelId = request.getParameter("modelId");
String modelType = request.getParameter("modeltype");
// Currently not being used since we don't update the modelVersion
// String modelVersion = request.getParameter("version");
String originalModelVersion = request.getParameter("originalModelVersion");
String runIdent = request.getParameter("runIdent");
String originalRunIdent = request.getParameter("originalRunIdent");
String runDate = request.getParameter("creationDate");
String originalRunDate = request.getParameter("originalCreationDate");
String scenario = request.getParameter("scenario");
String originalScenario = request.getParameter("originalScenario");
String comments = request.getParameter("comments");
String originalComments = request.getParameter("originalComments");
String email = request.getParameter("email");
String wfsUrl = request.getParameter("wfsUrl");
String layer = request.getParameter("layer");
String commonAttr = request.getParameter("commonAttr");
Boolean updateAsBest = "on".equalsIgnoreCase(request.getParameter("markAsBest")) ? Boolean.TRUE : Boolean.FALSE;
Boolean rerun = Boolean.parseBoolean(request.getParameter("rerun")); // If this is true, we only re-run the R processing
String responseText;
RunMetadata newRunMetadata;
ModelType modelTypeEnum = null;
if ("prms".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.PRMS;
}
if ("afinch".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.AFINCH;
}
if ("waters".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.WATERS;
}
if ("sye".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.SYE;
}
RunMetadata originalRunMetadata = new RunMetadata(
modelTypeEnum,
modelId,
originalModelerName,
originalModelVersion,
originalRunIdent,
originalRunDate,
originalScenario,
originalComments,
email,
wfsUrl,
layer,
commonAttr,
updateAsBest);
if (rerun) {
String sosEndpoint = props.getProperty("watersmart.sos.model.repo") + originalRunMetadata.getTypeString() + "/" + originalRunMetadata.getFileName();
WPSImpl impl = new WPSImpl();
String implResponse = impl.executeProcess(sosEndpoint, originalRunMetadata);
Boolean processStarted = implResponse.toLowerCase().equals("ok");
responseText = "{success: "+processStarted.toString()+", message: '" + implResponse + "'}";
} else {
newRunMetadata = new RunMetadata(
modelTypeEnum,
modelId,
modelerName,
originalModelVersion,
runIdent,
runDate,
scenario,
comments,
email,
wfsUrl,
layer,
commonAttr,
updateAsBest);
CSWTransactionHelper helper = new CSWTransactionHelper(newRunMetadata, null, new HashMap<String, String>());
try {
String results = helper.updateRunMetadata(originalRunMetadata);
// TODO- parse xml, make sure stuff happened alright, if so don't say success
responseText = "{success: true, msg: 'The record has been updated'}";
} catch (IOException ex) {
responseText = "{success: false, msg: '" + ex.getMessage() + "'}";
} catch (URISyntaxException ex) {
responseText = "{success: false, msg: '" + ex.getMessage() + "'}";
}
}
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
try {
Writer writer = response.getWriter();
writer.write(responseText);
writer.close();
} catch (IOException ex) {
LOG.warn("An error occurred while trying to send response to client. ", ex);
}
}
| protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
LOG.debug("Received new update request");
String modelerName = request.getParameter("name");
String originalModelerName = request.getParameter("originalName");
String modelId = request.getParameter("modelId");
String modelType = request.getParameter("modeltype");
// Currently not being used since we don't update the modelVersion
// String modelVersion = request.getParameter("version");
String originalModelVersion = request.getParameter("originalModelVersion");
String runIdent = request.getParameter("runIdent");
String originalRunIdent = request.getParameter("originalRunIdent");
String runDate = request.getParameter("creationDate");
String originalRunDate = request.getParameter("originalCreationDate");
String scenario = request.getParameter("scenario");
String originalScenario = request.getParameter("originalScenario");
String comments = request.getParameter("comments");
String originalComments = request.getParameter("originalComments");
String email = request.getParameter("email");
String wfsUrl = request.getParameter("wfsUrl");
String layer = request.getParameter("layer");
String commonAttr = request.getParameter("commonAttr");
Boolean updateAsBest = "on".equalsIgnoreCase(request.getParameter("markAsBest")) ? Boolean.TRUE : Boolean.FALSE;
Boolean rerun = Boolean.parseBoolean(request.getParameter("rerun")); // If this is true, we only re-run the R processing
String responseText;
RunMetadata newRunMetadata;
ModelType modelTypeEnum = null;
if ("prms".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.PRMS;
}
else if ("afinch".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.AFINCH;
}
else if ("waters".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.WATERS;
}
else if ("sye".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.SYE;
}
else if ("stats".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.STATS;
}
else if ("prms2".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.PRMS2;
}
else if ("waterfall".equals(modelType.toLowerCase())) {
modelTypeEnum = ModelType.WATERFALL;
}
else {
throw new IllegalArgumentException("Model Type does not exist!!");
}
RunMetadata originalRunMetadata = new RunMetadata(
modelTypeEnum,
modelId,
originalModelerName,
originalModelVersion,
originalRunIdent,
originalRunDate,
originalScenario,
originalComments,
email,
wfsUrl,
layer,
commonAttr,
updateAsBest);
if (rerun) {
String sosEndpoint = props.getProperty("watersmart.sos.model.repo") + originalRunMetadata.getTypeString() + "/" + originalRunMetadata.getFileName() + ".nc";
WPSImpl impl = new WPSImpl();
String implResponse = impl.executeProcess(sosEndpoint, originalRunMetadata);
Boolean processStarted = implResponse.toLowerCase().equals("ok");
responseText = "{success: "+processStarted.toString()+", message: '" + implResponse + "'}";
} else {
newRunMetadata = new RunMetadata(
modelTypeEnum,
modelId,
modelerName,
originalModelVersion,
runIdent,
runDate,
scenario,
comments,
email,
wfsUrl,
layer,
commonAttr,
updateAsBest);
CSWTransactionHelper helper = new CSWTransactionHelper(newRunMetadata, null, new HashMap<String, String>());
try {
String results = helper.updateRunMetadata(originalRunMetadata);
// TODO- parse xml, make sure stuff happened alright, if so don't say success
responseText = "{success: true, msg: 'The record has been updated'}";
} catch (IOException ex) {
responseText = "{success: false, msg: '" + ex.getMessage() + "'}";
} catch (URISyntaxException ex) {
responseText = "{success: false, msg: '" + ex.getMessage() + "'}";
}
}
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
try {
Writer writer = response.getWriter();
writer.write(responseText);
writer.close();
} catch (IOException ex) {
LOG.warn("An error occurred while trying to send response to client. ", ex);
}
}
|
diff --git a/src/tv/nilsson/dnsync/Downloader.java b/src/tv/nilsson/dnsync/Downloader.java
index d15028b..3259ead 100644
--- a/src/tv/nilsson/dnsync/Downloader.java
+++ b/src/tv/nilsson/dnsync/Downloader.java
@@ -1,179 +1,179 @@
package tv.nilsson.dnsync;
import android.net.Uri;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URI;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Downloader {
private static String SERVICE_ENDPOINT = "http://kund.dn.se/service/pdf/";
private static String LOGIN_ENDPOINT = "http://kund.dn.se/";
public static final int TIMEOUT_MS = 30000;
private String customerNr;
private String firstName;
private String lastName;
private HttpContext httpContext;
private final BasicCookieStore cookieStore;
public static class DownloadInfo {
public Uri uri;
public String filename;
public DownloadInfo(Uri uri, String filename) {
this.uri = uri;
this.filename = filename;
}
}
public Downloader(String customerNr, String firstName, String lastName) {
this.customerNr = customerNr;
this.firstName = firstName;
this.lastName = lastName;
this.httpContext = new BasicHttpContext();
this.cookieStore = new BasicCookieStore();
this.httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
}
public DownloadInfo obtainDownloadInfo() throws DownloadException {
try {
doLogin();
HttpClient httpClient = newHttpClient();
HttpGet request = new HttpGet(SERVICE_ENDPOINT);
HttpResponse response = httpClient.execute(request, httpContext);
if (response.getStatusLine().getStatusCode() != 200) throw new DownloadUnexpectedResponseException();
String s = extractEntity(response);
- Pattern pattern = Pattern.compile("Alla delar.*?(\\d+)-(\\d+)-(\\d+)");
+ Pattern pattern = Pattern.compile("day/(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)/DN.pdf");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
String filename = MessageFormat.format("{0}{1}{2}_DN.pdf", matcher.group(1), matcher.group(2), matcher.group(3));
- Uri downloadUri = Uri.parse(SERVICE_ENDPOINT).buildUpon().appendQueryParameter("del", "DN").build();
+ Uri downloadUri = Uri.parse(SERVICE_ENDPOINT).buildUpon().appendPath(matcher.group(0)).appendQueryParameter("del", "DN").build();
return new DownloadInfo(downloadUri, filename);
}
else {
throw new DownloadUnexpectedResponseException();
}
}
catch (IOException e) {
throw new DownloadIOException();
}
catch(RuntimeException e) {
throw new DownloadInternalErrorException(e);
}
}
private boolean isLoggedIn() {
for (Cookie cookie : cookieStore.getCookies()) {
if (cookie.getName().equals("sessionid")) return true;
}
return false;
}
private String fetchCsrfToken() throws IOException, DownloadException {
HttpClient httpClient = newHttpClient();
HttpResponse response = httpClient.execute(new HttpGet(LOGIN_ENDPOINT), httpContext);
if (response.getStatusLine().getStatusCode() != 200) throw new DownloadUnexpectedResponseException();
String responseString = extractEntity(response);
Pattern pattern = Pattern.compile("name='csrfmiddlewaretoken' value='(.*?)'");
Matcher matcher = pattern.matcher(responseString);
boolean found = matcher.find();
if (!found) throw new DownloadUnexpectedResponseException();
return matcher.group(1);
}
private void doLogin() throws IOException, DownloadException {
HttpClient httpClient = newHttpClient();
String csrfToken = fetchCsrfToken();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("csrfmiddlewaretoken", csrfToken));
params.add(new BasicNameValuePair("plugin_template", "first_page"));
params.add(new BasicNameValuePair("redirect_to", ""));
params.add(new BasicNameValuePair("customer_number", customerNr));
params.add(new BasicNameValuePair("first_name", firstName));
params.add(new BasicNameValuePair("last_name", lastName));
HttpPost request = new HttpPost(LOGIN_ENDPOINT);
request.addHeader("Referer", LOGIN_ENDPOINT);
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = httpClient.execute(request, httpContext);
int status = response.getStatusLine().getStatusCode();
if (status != 200) {
throw new AuthenticationFailedException();
}
if (!isLoggedIn()) throw new AuthenticationFailedException();
}
private String extractEntity(HttpResponse response) throws DownloadException {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
response.getEntity().writeTo(byteArrayOutputStream);
return new String(byteArrayOutputStream.toByteArray());
}
catch(IOException e) {
throw new DownloadUnexpectedResponseException();
}
}
public static HttpClient newHttpClient() {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_MS);
HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_MS);
return new DefaultHttpClient(httpParameters);
}
/**
* Open a URI using the context of the downloader (auth, cookies etc)
*
* @param uri
* @return Entity of response
* @throws IOException
*/
public HttpEntity openUri(Uri uri) throws IOException {
HttpClient httpClient = Downloader.newHttpClient();
HttpResponse response = httpClient.execute(new HttpGet(URI.create(uri.toString())), httpContext);
return response.getEntity();
}
}
| false | true | public DownloadInfo obtainDownloadInfo() throws DownloadException {
try {
doLogin();
HttpClient httpClient = newHttpClient();
HttpGet request = new HttpGet(SERVICE_ENDPOINT);
HttpResponse response = httpClient.execute(request, httpContext);
if (response.getStatusLine().getStatusCode() != 200) throw new DownloadUnexpectedResponseException();
String s = extractEntity(response);
Pattern pattern = Pattern.compile("Alla delar.*?(\\d+)-(\\d+)-(\\d+)");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
String filename = MessageFormat.format("{0}{1}{2}_DN.pdf", matcher.group(1), matcher.group(2), matcher.group(3));
Uri downloadUri = Uri.parse(SERVICE_ENDPOINT).buildUpon().appendQueryParameter("del", "DN").build();
return new DownloadInfo(downloadUri, filename);
}
else {
throw new DownloadUnexpectedResponseException();
}
}
catch (IOException e) {
throw new DownloadIOException();
}
catch(RuntimeException e) {
throw new DownloadInternalErrorException(e);
}
}
| public DownloadInfo obtainDownloadInfo() throws DownloadException {
try {
doLogin();
HttpClient httpClient = newHttpClient();
HttpGet request = new HttpGet(SERVICE_ENDPOINT);
HttpResponse response = httpClient.execute(request, httpContext);
if (response.getStatusLine().getStatusCode() != 200) throw new DownloadUnexpectedResponseException();
String s = extractEntity(response);
Pattern pattern = Pattern.compile("day/(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)/DN.pdf");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
String filename = MessageFormat.format("{0}{1}{2}_DN.pdf", matcher.group(1), matcher.group(2), matcher.group(3));
Uri downloadUri = Uri.parse(SERVICE_ENDPOINT).buildUpon().appendPath(matcher.group(0)).appendQueryParameter("del", "DN").build();
return new DownloadInfo(downloadUri, filename);
}
else {
throw new DownloadUnexpectedResponseException();
}
}
catch (IOException e) {
throw new DownloadIOException();
}
catch(RuntimeException e) {
throw new DownloadInternalErrorException(e);
}
}
|
diff --git a/src/jp/muo/smsproxy/RingingReceiver.java b/src/jp/muo/smsproxy/RingingReceiver.java
index 744ad35..b177d62 100644
--- a/src/jp/muo/smsproxy/RingingReceiver.java
+++ b/src/jp/muo/smsproxy/RingingReceiver.java
@@ -1,29 +1,31 @@
package jp.muo.smsproxy;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class RingingReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
final TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener ringingListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String number) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
SmsProxyManager mgr = new SmsProxyManager(context);
if (mgr.isEnabled()) {
- String msgText = String.format(context.getString(R.string.sms_on_call), (number != null && number != "") ? number : "unknown");
+ String msgText = String.format(
+ context.getString(R.string.sms_on_call),
+ (number != null && number != "") ? number : context.getString(R.string.subscriber_unknown));
mgr.send(SmsProxyManager.Mode.CALL, msgText);
}
}
telephony.listen(this, PhoneStateListener.LISTEN_NONE);
}
};
telephony.listen(ringingListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
| true | true | public void onReceive(final Context context, Intent intent) {
final TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener ringingListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String number) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
SmsProxyManager mgr = new SmsProxyManager(context);
if (mgr.isEnabled()) {
String msgText = String.format(context.getString(R.string.sms_on_call), (number != null && number != "") ? number : "unknown");
mgr.send(SmsProxyManager.Mode.CALL, msgText);
}
}
telephony.listen(this, PhoneStateListener.LISTEN_NONE);
}
};
telephony.listen(ringingListener, PhoneStateListener.LISTEN_CALL_STATE);
}
| public void onReceive(final Context context, Intent intent) {
final TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
PhoneStateListener ringingListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String number) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
SmsProxyManager mgr = new SmsProxyManager(context);
if (mgr.isEnabled()) {
String msgText = String.format(
context.getString(R.string.sms_on_call),
(number != null && number != "") ? number : context.getString(R.string.subscriber_unknown));
mgr.send(SmsProxyManager.Mode.CALL, msgText);
}
}
telephony.listen(this, PhoneStateListener.LISTEN_NONE);
}
};
telephony.listen(ringingListener, PhoneStateListener.LISTEN_CALL_STATE);
}
|
diff --git a/plugins/devices/test/src/main/java/it/freedomotic/plugins/PluginRemoteController.java b/plugins/devices/test/src/main/java/it/freedomotic/plugins/PluginRemoteController.java
index 88247622..8558d37a 100644
--- a/plugins/devices/test/src/main/java/it/freedomotic/plugins/PluginRemoteController.java
+++ b/plugins/devices/test/src/main/java/it/freedomotic/plugins/PluginRemoteController.java
@@ -1,83 +1,88 @@
/**
*
* Copyright (c) 2009-2013 Freedomotic team http://freedomotic.com
*
* This file is part of Freedomotic
*
* This Program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2, 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
* Freedomotic; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*/
package it.freedomotic.plugins;
import it.freedomotic.api.Actuator;
import it.freedomotic.api.Client;
import it.freedomotic.exceptions.UnableToExecuteException;
import it.freedomotic.reactions.Command;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Enrico
*/
public class PluginRemoteController
extends Actuator {
private static final Logger LOG = Logger.getLogger(PluginRemoteController.class.getName());
public PluginRemoteController() {
super("Plugins Remote Controller", "/test/plugins-remote-controller.xml");
}
@Override
protected void onCommand(Command c)
throws IOException, UnableToExecuteException {
Client plugin = getApi().getClientStorage().get(c.getProperty("plugin"));
String action = c.getProperty("action");
if (plugin != null) {
if (action.equalsIgnoreCase("SHOW")) {
plugin.showGui();
}
if (action.equalsIgnoreCase("HIDE")) {
plugin.hideGui();
}
if (action.equalsIgnoreCase("STOP")) {
if (plugin != this && getApi().getAuth().isPermitted("sys:plugins:stop")) {
plugin.stop();
}
}
if (action.equalsIgnoreCase("START")) {
if (plugin != this && getApi().getAuth().isPermitted("sys:plugins:start")) {
plugin.start();
}
}
if (action.equalsIgnoreCase("RESTART")) {
- if (plugin != this && getApi().getAuth().isPermitted("sys:plugins:stop,sys:plugins:start")) {
+ if (plugin != this && getApi().getAuth().isPermitted("sys:plugins:stop") && getApi().getAuth().isPermitted("sys:plugins:start")) {
plugin.stop();
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException ex) {
+ Logger.getLogger(PluginRemoteController.class.getName()).log(Level.SEVERE, null, ex);
+ }
plugin.start();
}
}
} else {
LOG.log(Level.WARNING, "Impossible to act on plugin {0}", c.getProperty("plugin"));
}
}
@Override
protected boolean canExecute(Command c) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
| false | true | protected void onCommand(Command c)
throws IOException, UnableToExecuteException {
Client plugin = getApi().getClientStorage().get(c.getProperty("plugin"));
String action = c.getProperty("action");
if (plugin != null) {
if (action.equalsIgnoreCase("SHOW")) {
plugin.showGui();
}
if (action.equalsIgnoreCase("HIDE")) {
plugin.hideGui();
}
if (action.equalsIgnoreCase("STOP")) {
if (plugin != this && getApi().getAuth().isPermitted("sys:plugins:stop")) {
plugin.stop();
}
}
if (action.equalsIgnoreCase("START")) {
if (plugin != this && getApi().getAuth().isPermitted("sys:plugins:start")) {
plugin.start();
}
}
if (action.equalsIgnoreCase("RESTART")) {
if (plugin != this && getApi().getAuth().isPermitted("sys:plugins:stop,sys:plugins:start")) {
plugin.stop();
plugin.start();
}
}
} else {
LOG.log(Level.WARNING, "Impossible to act on plugin {0}", c.getProperty("plugin"));
}
}
| protected void onCommand(Command c)
throws IOException, UnableToExecuteException {
Client plugin = getApi().getClientStorage().get(c.getProperty("plugin"));
String action = c.getProperty("action");
if (plugin != null) {
if (action.equalsIgnoreCase("SHOW")) {
plugin.showGui();
}
if (action.equalsIgnoreCase("HIDE")) {
plugin.hideGui();
}
if (action.equalsIgnoreCase("STOP")) {
if (plugin != this && getApi().getAuth().isPermitted("sys:plugins:stop")) {
plugin.stop();
}
}
if (action.equalsIgnoreCase("START")) {
if (plugin != this && getApi().getAuth().isPermitted("sys:plugins:start")) {
plugin.start();
}
}
if (action.equalsIgnoreCase("RESTART")) {
if (plugin != this && getApi().getAuth().isPermitted("sys:plugins:stop") && getApi().getAuth().isPermitted("sys:plugins:start")) {
plugin.stop();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(PluginRemoteController.class.getName()).log(Level.SEVERE, null, ex);
}
plugin.start();
}
}
} else {
LOG.log(Level.WARNING, "Impossible to act on plugin {0}", c.getProperty("plugin"));
}
}
|
diff --git a/frost-wot/source/frost/threads/MessageDownloadThread.java b/frost-wot/source/frost/threads/MessageDownloadThread.java
index b33ca31d..b3bc75b1 100644
--- a/frost-wot/source/frost/threads/MessageDownloadThread.java
+++ b/frost-wot/source/frost/threads/MessageDownloadThread.java
@@ -1,585 +1,587 @@
/*
MessageDownloadThread.java / Frost
Copyright (C) 2001 Jan-Thomas Czornack <[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 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.threads;
import java.io.File;
import java.util.*;
import frost.*;
import frost.crypt.*;
import frost.gui.objects.*;
import frost.messages.*;
import frost.FcpTools.*;
import frost.identities.*;
/**
* Downloads messages
*/
public class MessageDownloadThread
extends BoardUpdateThreadObject
implements BoardUpdateThread
{
public FrostBoardObject board;
private int downloadHtl;
private String keypool;
private int maxMessageDownload;
private String destination;
private boolean secure;
private String publicKey;
private boolean flagNew;
public int getThreadType()
{
if (flagNew)
{
return BoardUpdateThread.MSG_DNLOAD_TODAY;
}
else
{
return BoardUpdateThread.MSG_DNLOAD_BACK;
}
}
public void run()
{
notifyThreadStarted(this);
try
{
String tofType;
if (flagNew)
tofType = "TOF Download";
else
tofType = "TOF Download Back";
// Wait some random time to speed up the update of the TOF table
// ... and to not to flood the node
int waitTime = (int) (Math.random() * 5000);
// wait a max. of 5 seconds between start of threads
mixed.wait(waitTime);
Core.getOut().println(
"TOFDN: "
+ tofType
+ " Thread started for board "
+ board.toString());
if (isInterrupted())
{
notifyThreadFinished(this);
return;
}
// switch public / secure board
if (board.isPublicBoard() == false)
{
publicKey = board.getPublicKey();
secure = true;
}
else // public board
{
secure = false;
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
if (this.flagNew)
{
// download only actual date
downloadDate(cal);
}
else
{
// download up to maxMessages days to the past
GregorianCalendar firstDate = new GregorianCalendar();
firstDate.setTimeZone(TimeZone.getTimeZone("GMT"));
firstDate.set(Calendar.YEAR, 2001);
firstDate.set(Calendar.MONTH, 5);
firstDate.set(Calendar.DATE, 11);
int counter = 0;
while (!isInterrupted()
&& cal.after(firstDate)
&& counter < maxMessageDownload)
{
counter++;
cal.add(Calendar.DATE, -1); // Yesterday
downloadDate(cal);
}
}
Core.getOut().println(
"TOFDN: "
+ tofType
+ " Thread stopped for board "
+ board.toString());
}
catch (Throwable t)
{
Core.getOut().println(
Thread.currentThread().getName()
+ ": Oo. Exception in MessageDownloadThread:");
t.printStackTrace(Core.getOut());
}
notifyThreadFinished(this);
}
/**Returns true if message is duplicate*/
private boolean exists(File file)
{
File[] fileList = (file.getParentFile()).listFiles();
String one = null;
if (fileList != null)
{
for (int i = 0; i < fileList.length; i++)
{
if (!fileList[i].equals(file)
&& fileList[i].getName().endsWith(".sig") == false
&& // dont check .sig files
fileList[i].getName().indexOf(
board.getBoardFilename())
!= -1
&& file.getName().indexOf(board.getBoardFilename()) != -1)
{
if (one == null) // load new file only 1 time
{
one = FileAccess.readFile(file);
}
String two = FileAccess.readFile(fileList[i]);
if (one.equals(two))
{
return true;
}
}
}
}
return false;
}
protected void downloadDate(GregorianCalendar calDL)
{
VerifyableMessageObject currentMsg = null;
String dirdate = DateFun.getDateOfCalendar(calDL);
String fileSeparator = System.getProperty("file.separator");
destination =
new StringBuffer()
.append(keypool)
.append(board.getBoardFilename())
.append(fileSeparator)
.append(dirdate)
.append(fileSeparator)
.toString();
File makedir = new File(destination);
if (!makedir.exists())
{
makedir.mkdirs();
}
File checkLockfile = new File(destination + "locked.lck");
int index = 0;
int failures = 0;
int maxFailures;
if (flagNew)
{
maxFailures = 3; // skip a maximum of 2 empty slots for today
}
else
{
maxFailures = 2; // skip a maximum of 1 empty slot for backload
}
while (failures < maxFailures && (flagNew || !checkLockfile.exists()))
{
byte[] metadata = null;
try
{ //make a wide net so that evil messages don't kill us
String val =
new StringBuffer()
.append(destination)
.append(System.currentTimeMillis())
.append(".xml.msg")
.toString();
File testMe = new File(val);
val =
new StringBuffer()
.append(destination)
.append(dirdate)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".xml")
.toString();
File testMe2 = new File(val);
if (testMe2.length() > 0) // already downloaded
{
index++;
failures = 0;
}
else
{
String downKey = null;
if (secure)
{
downKey =
new StringBuffer()
.append(publicKey)
.append("/")
.append(board.getBoardFilename())
.append("/")
.append(dirdate)
.append("-")
.append(index)
.append(".xml")
.toString();
}
else
{
downKey =
new StringBuffer()
.append("KSK@frost/message/")
.append(
frame1.frostSettings.getValue(
"messageBase"))
.append("/")
.append(dirdate)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".xml")
.toString();
}
try
{
boolean fastDownload = !flagNew;
// for backload use fast download, deep for today
FcpResults res =
FcpRequest.getFile(
downKey,
null,
testMe,
downloadHtl,
false,
fastDownload);
if (res == null)
metadata = null;
else
metadata = res.getRawMetadata();
// TODO: if metadata==null, not signed message
mixed.wait(111);
// wait some time to not to hurt the node on next retry
}
catch (Throwable t)
{
Core.getOut().println(
Thread.currentThread().getName()
+ " :TOFDN - Error in run()/FcpRequest.getFile:");
t.printStackTrace(Core.getOut());
}
// Download successful?
if (testMe.length() > 0)
{
testMe.renameTo(testMe2);
testMe = testMe2;
//check if it is a duplicate
String messageId = Core.getCrypto().digest(testMe);
// Does a duplicate message exist?
if (!exists(testMe)
&& !Core.getMessageSet().contains(messageId))
{
Core.getMessageSet().add(messageId);
//if no metadata, message wasn't signed
if (metadata == null)
{
//unzip
byte[] unzippedXml =
FileAccess.readZipFileBinary(testMe);
+ System.out.println("flen="+testMe.length());
+ System.out.println("DBG='"+new String(FileAccess.readByteArray(testMe))+"'");
FileAccess.writeByteArray(unzippedXml, testMe);
try
{
currentMsg =
new VerifyableMessageObject(testMe);
}
catch (Exception ex)
{
ex.printStackTrace(Core.getOut());
// TODO: file could not be read, mark it invalid not to confuse gui
index++;
continue;
}
//set to unsigned
currentMsg.setStatus(
VerifyableMessageObject.OLD);
// check and maybe add msg to gui
addMessageToGui(currentMsg, testMe, true);
index++;
continue;
} //end of if no metadata part
//verify the zipped message
byte[] plaintext = FileAccess.readByteArray(testMe);
MetaData metaData = null;
try
{
metaData = new MetaData(plaintext, metadata);
}
catch (Throwable t)
{
//TODO: metadata failed, do something
t.printStackTrace(Core.getOut());
Core.getOut().println(
"metadata couldn't be read. "
+ "offending file saved as badmetadata.xml - send to a dev for analysis");
File badmetadata = new File("badmetadata.xml");
FileAccess.writeByteArray(
metadata,
badmetadata);
index++;
failures = 0;
continue;
}
//check if we have the owner already on the lists
String _owner =
metaData.getSharer().getUniqueName();
Identity owner;
//check friends
owner = Core.getFriends().Get(_owner);
//if not, check neutral
if (owner == null)
owner = Core.getNeutral().Get(_owner);
//if not, check enemies
if (owner == null)
owner = Core.getEnemies().Get(_owner);
//if still not, use the parsed id
if (owner == null)
{
owner = metaData.getSharer();
owner.noFiles = 0;
owner.noMessages = 1;
Core.getNeutral().Add(owner);
}
//verify! :)
boolean valid =
Core.getCrypto().detachedVerify(
plaintext,
owner.getKey(),
metaData.getSig());
//unzip
byte[] unzippedXml =
FileAccess.readZipFileBinary(testMe);
FileAccess.writeByteArray(unzippedXml, testMe);
//create object
try
{
currentMsg =
new VerifyableMessageObject(testMe);
}
catch (Exception ex)
{
ex.printStackTrace();
// TODO: file could not be read, mark it invalid not to confuse gui
index++;
continue;
}
//then check if the signature was ok
if (!valid)
{
currentMsg.setStatus(
VerifyableMessageObject.TAMPERED);
Core.getOut().println(
"TOFDN: message failed verification");
addMessageToGui(currentMsg, testMe, false);
index++;
continue;
}
//make sure the pubkey and from fields in the xml file are the same
//as those in the metadata
String metaDataHash =
mixed.makeFilename(
Core.getCrypto().digest(
metaData.getSharer().getKey()));
String messageHash =
mixed.makeFilename(
currentMsg.getFrom().substring(
currentMsg.getFrom().indexOf("@") + 1,
currentMsg.getFrom().length()));
if (!metaDataHash.equals(messageHash))
{
Core.getOut().println(
"hash in metadata doesn't match hash in message!");
Core.getOut().println(
"metadata : "
+ metaDataHash
+ " , message: "
+ messageHash);
currentMsg.setStatus(
VerifyableMessageObject.TAMPERED);
addMessageToGui(currentMsg, testMe, false);
index++;
continue;
}
//if it is, we have the user either on the good, bad or neutral lists
if (Core.getFriends().containsKey(_owner))
currentMsg.setStatus(
VerifyableMessageObject.VERIFIED);
else if (Core.getEnemies().containsKey(_owner))
currentMsg.setStatus(
VerifyableMessageObject.FAILED);
else
currentMsg.setStatus(
VerifyableMessageObject.PENDING);
/* Encryption will be done+handled using private boards
*/
// verify the message date and time
if (currentMsg.isValidFormat(calDL) == false)
{
// TODO: file contains invalid data or time, skip and
// mark it to not try it again(?)
}
//File sig = new File(testMe.getPath() + ".sig");
// Is this a valid message?
addMessageToGui(currentMsg, testMe, true);
}
else
{
Core.getOut().println(
Thread.currentThread().getName()
+ ": TOFDN: ****** Duplicate Message : "
+ testMe.getName()
+ " *****");
FileAccess.writeFile("Empty", testMe);
}
index++;
failures = 0;
}
else
{
/* if( !flagNew )
{
Core.getOut().println("TOFDN: *** Increased TOF index for board '"+board.toString()+"' ***");
}*/
failures++;
index++;
}
}
if (isInterrupted())
return;
}
catch (Throwable t)
{
t.printStackTrace(Core.getOut());
index++;
}
} // end-of: while
}
private void addMessageToGui(
VerifyableMessageObject currentMsg,
File testMe,
boolean markAsNew)
{
if (currentMsg.isValid())
{
if (TOF.blocked(currentMsg, board) && testMe.length() > 0)
{
board.incBlocked();
Core.getOut().println(
"\nTOFDN: ########### blocked message for board '"
+ board.toString()
+ "' #########\n");
}
else
{
frame1.displayNewMessageIcon(true);
// write the NEW message indicator file
if( markAsNew )
{
FileAccess.writeFile(
"This message is new!",
testMe.getPath() + ".lck");
}
// add new message or notify of arrival
TOF.addNewMessageToTable(testMe, board, markAsNew);
//add all files indexed files
Iterator it =
currentMsg
.getAttachmentList()
.getAllOfType(Attachment.FILE)
.iterator();
while (it.hasNext())
{
SharedFileObject current = ((FileAttachment)it.next()).getFileObj();
if (current.getOwner() != null)
Index.add(current, board);
}
}
}
else
{
FileAccess.writeFile("Empty", testMe);
}
}
/**Constructor*/ //
public MessageDownloadThread(
boolean fn,
FrostBoardObject boa,
int dlHtl,
String kpool,
String maxmsg)
{
super(boa);
this.flagNew = fn;
this.board = boa;
this.downloadHtl = dlHtl;
this.keypool = kpool;
this.maxMessageDownload = Integer.parseInt(maxmsg);
}
}
| true | true | protected void downloadDate(GregorianCalendar calDL)
{
VerifyableMessageObject currentMsg = null;
String dirdate = DateFun.getDateOfCalendar(calDL);
String fileSeparator = System.getProperty("file.separator");
destination =
new StringBuffer()
.append(keypool)
.append(board.getBoardFilename())
.append(fileSeparator)
.append(dirdate)
.append(fileSeparator)
.toString();
File makedir = new File(destination);
if (!makedir.exists())
{
makedir.mkdirs();
}
File checkLockfile = new File(destination + "locked.lck");
int index = 0;
int failures = 0;
int maxFailures;
if (flagNew)
{
maxFailures = 3; // skip a maximum of 2 empty slots for today
}
else
{
maxFailures = 2; // skip a maximum of 1 empty slot for backload
}
while (failures < maxFailures && (flagNew || !checkLockfile.exists()))
{
byte[] metadata = null;
try
{ //make a wide net so that evil messages don't kill us
String val =
new StringBuffer()
.append(destination)
.append(System.currentTimeMillis())
.append(".xml.msg")
.toString();
File testMe = new File(val);
val =
new StringBuffer()
.append(destination)
.append(dirdate)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".xml")
.toString();
File testMe2 = new File(val);
if (testMe2.length() > 0) // already downloaded
{
index++;
failures = 0;
}
else
{
String downKey = null;
if (secure)
{
downKey =
new StringBuffer()
.append(publicKey)
.append("/")
.append(board.getBoardFilename())
.append("/")
.append(dirdate)
.append("-")
.append(index)
.append(".xml")
.toString();
}
else
{
downKey =
new StringBuffer()
.append("KSK@frost/message/")
.append(
frame1.frostSettings.getValue(
"messageBase"))
.append("/")
.append(dirdate)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".xml")
.toString();
}
try
{
boolean fastDownload = !flagNew;
// for backload use fast download, deep for today
FcpResults res =
FcpRequest.getFile(
downKey,
null,
testMe,
downloadHtl,
false,
fastDownload);
if (res == null)
metadata = null;
else
metadata = res.getRawMetadata();
// TODO: if metadata==null, not signed message
mixed.wait(111);
// wait some time to not to hurt the node on next retry
}
catch (Throwable t)
{
Core.getOut().println(
Thread.currentThread().getName()
+ " :TOFDN - Error in run()/FcpRequest.getFile:");
t.printStackTrace(Core.getOut());
}
// Download successful?
if (testMe.length() > 0)
{
testMe.renameTo(testMe2);
testMe = testMe2;
//check if it is a duplicate
String messageId = Core.getCrypto().digest(testMe);
// Does a duplicate message exist?
if (!exists(testMe)
&& !Core.getMessageSet().contains(messageId))
{
Core.getMessageSet().add(messageId);
//if no metadata, message wasn't signed
if (metadata == null)
{
//unzip
byte[] unzippedXml =
FileAccess.readZipFileBinary(testMe);
FileAccess.writeByteArray(unzippedXml, testMe);
try
{
currentMsg =
new VerifyableMessageObject(testMe);
}
catch (Exception ex)
{
ex.printStackTrace(Core.getOut());
// TODO: file could not be read, mark it invalid not to confuse gui
index++;
continue;
}
//set to unsigned
currentMsg.setStatus(
VerifyableMessageObject.OLD);
// check and maybe add msg to gui
addMessageToGui(currentMsg, testMe, true);
index++;
continue;
} //end of if no metadata part
//verify the zipped message
byte[] plaintext = FileAccess.readByteArray(testMe);
MetaData metaData = null;
try
{
metaData = new MetaData(plaintext, metadata);
}
catch (Throwable t)
{
//TODO: metadata failed, do something
t.printStackTrace(Core.getOut());
Core.getOut().println(
"metadata couldn't be read. "
+ "offending file saved as badmetadata.xml - send to a dev for analysis");
File badmetadata = new File("badmetadata.xml");
FileAccess.writeByteArray(
metadata,
badmetadata);
index++;
failures = 0;
continue;
}
//check if we have the owner already on the lists
String _owner =
metaData.getSharer().getUniqueName();
Identity owner;
//check friends
owner = Core.getFriends().Get(_owner);
//if not, check neutral
if (owner == null)
owner = Core.getNeutral().Get(_owner);
//if not, check enemies
if (owner == null)
owner = Core.getEnemies().Get(_owner);
//if still not, use the parsed id
if (owner == null)
{
owner = metaData.getSharer();
owner.noFiles = 0;
owner.noMessages = 1;
Core.getNeutral().Add(owner);
}
//verify! :)
boolean valid =
Core.getCrypto().detachedVerify(
plaintext,
owner.getKey(),
metaData.getSig());
//unzip
byte[] unzippedXml =
FileAccess.readZipFileBinary(testMe);
FileAccess.writeByteArray(unzippedXml, testMe);
//create object
try
{
currentMsg =
new VerifyableMessageObject(testMe);
}
catch (Exception ex)
{
ex.printStackTrace();
// TODO: file could not be read, mark it invalid not to confuse gui
index++;
continue;
}
//then check if the signature was ok
if (!valid)
{
currentMsg.setStatus(
VerifyableMessageObject.TAMPERED);
Core.getOut().println(
"TOFDN: message failed verification");
addMessageToGui(currentMsg, testMe, false);
index++;
continue;
}
//make sure the pubkey and from fields in the xml file are the same
//as those in the metadata
String metaDataHash =
mixed.makeFilename(
Core.getCrypto().digest(
metaData.getSharer().getKey()));
String messageHash =
mixed.makeFilename(
currentMsg.getFrom().substring(
currentMsg.getFrom().indexOf("@") + 1,
currentMsg.getFrom().length()));
if (!metaDataHash.equals(messageHash))
{
Core.getOut().println(
"hash in metadata doesn't match hash in message!");
Core.getOut().println(
"metadata : "
+ metaDataHash
+ " , message: "
+ messageHash);
currentMsg.setStatus(
VerifyableMessageObject.TAMPERED);
addMessageToGui(currentMsg, testMe, false);
index++;
continue;
}
//if it is, we have the user either on the good, bad or neutral lists
if (Core.getFriends().containsKey(_owner))
currentMsg.setStatus(
VerifyableMessageObject.VERIFIED);
else if (Core.getEnemies().containsKey(_owner))
currentMsg.setStatus(
VerifyableMessageObject.FAILED);
else
currentMsg.setStatus(
VerifyableMessageObject.PENDING);
/* Encryption will be done+handled using private boards
*/
// verify the message date and time
if (currentMsg.isValidFormat(calDL) == false)
{
// TODO: file contains invalid data or time, skip and
// mark it to not try it again(?)
}
//File sig = new File(testMe.getPath() + ".sig");
// Is this a valid message?
addMessageToGui(currentMsg, testMe, true);
}
else
{
Core.getOut().println(
Thread.currentThread().getName()
+ ": TOFDN: ****** Duplicate Message : "
+ testMe.getName()
+ " *****");
FileAccess.writeFile("Empty", testMe);
}
index++;
failures = 0;
}
else
{
/* if( !flagNew )
{
Core.getOut().println("TOFDN: *** Increased TOF index for board '"+board.toString()+"' ***");
}*/
failures++;
index++;
}
}
if (isInterrupted())
return;
}
catch (Throwable t)
{
t.printStackTrace(Core.getOut());
index++;
}
} // end-of: while
}
| protected void downloadDate(GregorianCalendar calDL)
{
VerifyableMessageObject currentMsg = null;
String dirdate = DateFun.getDateOfCalendar(calDL);
String fileSeparator = System.getProperty("file.separator");
destination =
new StringBuffer()
.append(keypool)
.append(board.getBoardFilename())
.append(fileSeparator)
.append(dirdate)
.append(fileSeparator)
.toString();
File makedir = new File(destination);
if (!makedir.exists())
{
makedir.mkdirs();
}
File checkLockfile = new File(destination + "locked.lck");
int index = 0;
int failures = 0;
int maxFailures;
if (flagNew)
{
maxFailures = 3; // skip a maximum of 2 empty slots for today
}
else
{
maxFailures = 2; // skip a maximum of 1 empty slot for backload
}
while (failures < maxFailures && (flagNew || !checkLockfile.exists()))
{
byte[] metadata = null;
try
{ //make a wide net so that evil messages don't kill us
String val =
new StringBuffer()
.append(destination)
.append(System.currentTimeMillis())
.append(".xml.msg")
.toString();
File testMe = new File(val);
val =
new StringBuffer()
.append(destination)
.append(dirdate)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".xml")
.toString();
File testMe2 = new File(val);
if (testMe2.length() > 0) // already downloaded
{
index++;
failures = 0;
}
else
{
String downKey = null;
if (secure)
{
downKey =
new StringBuffer()
.append(publicKey)
.append("/")
.append(board.getBoardFilename())
.append("/")
.append(dirdate)
.append("-")
.append(index)
.append(".xml")
.toString();
}
else
{
downKey =
new StringBuffer()
.append("KSK@frost/message/")
.append(
frame1.frostSettings.getValue(
"messageBase"))
.append("/")
.append(dirdate)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".xml")
.toString();
}
try
{
boolean fastDownload = !flagNew;
// for backload use fast download, deep for today
FcpResults res =
FcpRequest.getFile(
downKey,
null,
testMe,
downloadHtl,
false,
fastDownload);
if (res == null)
metadata = null;
else
metadata = res.getRawMetadata();
// TODO: if metadata==null, not signed message
mixed.wait(111);
// wait some time to not to hurt the node on next retry
}
catch (Throwable t)
{
Core.getOut().println(
Thread.currentThread().getName()
+ " :TOFDN - Error in run()/FcpRequest.getFile:");
t.printStackTrace(Core.getOut());
}
// Download successful?
if (testMe.length() > 0)
{
testMe.renameTo(testMe2);
testMe = testMe2;
//check if it is a duplicate
String messageId = Core.getCrypto().digest(testMe);
// Does a duplicate message exist?
if (!exists(testMe)
&& !Core.getMessageSet().contains(messageId))
{
Core.getMessageSet().add(messageId);
//if no metadata, message wasn't signed
if (metadata == null)
{
//unzip
byte[] unzippedXml =
FileAccess.readZipFileBinary(testMe);
System.out.println("flen="+testMe.length());
System.out.println("DBG='"+new String(FileAccess.readByteArray(testMe))+"'");
FileAccess.writeByteArray(unzippedXml, testMe);
try
{
currentMsg =
new VerifyableMessageObject(testMe);
}
catch (Exception ex)
{
ex.printStackTrace(Core.getOut());
// TODO: file could not be read, mark it invalid not to confuse gui
index++;
continue;
}
//set to unsigned
currentMsg.setStatus(
VerifyableMessageObject.OLD);
// check and maybe add msg to gui
addMessageToGui(currentMsg, testMe, true);
index++;
continue;
} //end of if no metadata part
//verify the zipped message
byte[] plaintext = FileAccess.readByteArray(testMe);
MetaData metaData = null;
try
{
metaData = new MetaData(plaintext, metadata);
}
catch (Throwable t)
{
//TODO: metadata failed, do something
t.printStackTrace(Core.getOut());
Core.getOut().println(
"metadata couldn't be read. "
+ "offending file saved as badmetadata.xml - send to a dev for analysis");
File badmetadata = new File("badmetadata.xml");
FileAccess.writeByteArray(
metadata,
badmetadata);
index++;
failures = 0;
continue;
}
//check if we have the owner already on the lists
String _owner =
metaData.getSharer().getUniqueName();
Identity owner;
//check friends
owner = Core.getFriends().Get(_owner);
//if not, check neutral
if (owner == null)
owner = Core.getNeutral().Get(_owner);
//if not, check enemies
if (owner == null)
owner = Core.getEnemies().Get(_owner);
//if still not, use the parsed id
if (owner == null)
{
owner = metaData.getSharer();
owner.noFiles = 0;
owner.noMessages = 1;
Core.getNeutral().Add(owner);
}
//verify! :)
boolean valid =
Core.getCrypto().detachedVerify(
plaintext,
owner.getKey(),
metaData.getSig());
//unzip
byte[] unzippedXml =
FileAccess.readZipFileBinary(testMe);
FileAccess.writeByteArray(unzippedXml, testMe);
//create object
try
{
currentMsg =
new VerifyableMessageObject(testMe);
}
catch (Exception ex)
{
ex.printStackTrace();
// TODO: file could not be read, mark it invalid not to confuse gui
index++;
continue;
}
//then check if the signature was ok
if (!valid)
{
currentMsg.setStatus(
VerifyableMessageObject.TAMPERED);
Core.getOut().println(
"TOFDN: message failed verification");
addMessageToGui(currentMsg, testMe, false);
index++;
continue;
}
//make sure the pubkey and from fields in the xml file are the same
//as those in the metadata
String metaDataHash =
mixed.makeFilename(
Core.getCrypto().digest(
metaData.getSharer().getKey()));
String messageHash =
mixed.makeFilename(
currentMsg.getFrom().substring(
currentMsg.getFrom().indexOf("@") + 1,
currentMsg.getFrom().length()));
if (!metaDataHash.equals(messageHash))
{
Core.getOut().println(
"hash in metadata doesn't match hash in message!");
Core.getOut().println(
"metadata : "
+ metaDataHash
+ " , message: "
+ messageHash);
currentMsg.setStatus(
VerifyableMessageObject.TAMPERED);
addMessageToGui(currentMsg, testMe, false);
index++;
continue;
}
//if it is, we have the user either on the good, bad or neutral lists
if (Core.getFriends().containsKey(_owner))
currentMsg.setStatus(
VerifyableMessageObject.VERIFIED);
else if (Core.getEnemies().containsKey(_owner))
currentMsg.setStatus(
VerifyableMessageObject.FAILED);
else
currentMsg.setStatus(
VerifyableMessageObject.PENDING);
/* Encryption will be done+handled using private boards
*/
// verify the message date and time
if (currentMsg.isValidFormat(calDL) == false)
{
// TODO: file contains invalid data or time, skip and
// mark it to not try it again(?)
}
//File sig = new File(testMe.getPath() + ".sig");
// Is this a valid message?
addMessageToGui(currentMsg, testMe, true);
}
else
{
Core.getOut().println(
Thread.currentThread().getName()
+ ": TOFDN: ****** Duplicate Message : "
+ testMe.getName()
+ " *****");
FileAccess.writeFile("Empty", testMe);
}
index++;
failures = 0;
}
else
{
/* if( !flagNew )
{
Core.getOut().println("TOFDN: *** Increased TOF index for board '"+board.toString()+"' ***");
}*/
failures++;
index++;
}
}
if (isInterrupted())
return;
}
catch (Throwable t)
{
t.printStackTrace(Core.getOut());
index++;
}
} // end-of: while
}
|
diff --git a/monitor/RRProf/DataStore.java b/monitor/RRProf/DataStore.java
index f937fbc..fc4054f 100644
--- a/monitor/RRProf/DataStore.java
+++ b/monitor/RRProf/DataStore.java
@@ -1,792 +1,791 @@
package RRProf;
import java.util.*;
import javax.swing.event.TreeModelListener;
public class DataStore {
public interface EventListener{
void addCallName(CallNameRecordSet call_name);
void addThread(ThreadStore threadStore);
}
public interface RecordEventListener {
void addRecordChild(AbstractRecord rec);
void updateRecordData(AbstractRecord rec);
void updateParentRecordData(AbstractRecord rec);
void addRecordMember(AbstractRecord rec);
}
public abstract class AbstractRecord {
Set<RecordEventListener> listeners;
abstract public long getAllTime();
abstract public long getAllTimeSent();
abstract public long getChildrenTime();
abstract public long getCallCount();
abstract public String getRecordName();
AbstractRecord() {
listeners = new HashSet<RecordEventListener>();
}
public void addRecordEventListener(RecordEventListener listener) {
listeners.add(listener);
}
public void removeRecordEventListener(RecordEventListener listener) {
listeners.remove(listener);
}
public boolean isRunning() {
return false;
}
public String getTargetClass(){
return "NO-CLASS";
}
public String getTargetMethodName(){
return "NO-METHOD";
}
public int numRecords(){
return 1;
}
public ChildrenRecord childrenRecord() {
return new ChildrenRecord(this);
}
abstract public int getChildCount();
abstract public Iterable<AbstractRecord> allChild();
public long getSelfTime() {
if(isRunning())
return -1;
else
return getAllTimeSent() - getChildrenTime();
}
}
public class Record extends AbstractRecord{
public int ID;
public ThreadStore threadStore;
public Record parent;
public long allTime;
public long childrenTime;
public int callCount;
public long runningTime;
public CallName callName;
List<AbstractRecord> children;
public long getAllTime(){return allTime + runningTime;}
public long getAllTimeSent(){return allTime;}
public long getChildrenTime(){return childrenTime;}
public long getCallCount(){return callCount;}
public Record()
{
children = new ArrayList<AbstractRecord>();
ID = 0;
threadStore = null;
parent = null;
callName = null;
allTime = 0;
childrenTime = 0;
callCount = 0;
runningTime = 0;
}
public ThreadStore getThreadStore() {return threadStore;}
public CallName getCallName(){return callName;}
public String getTargetClassName(){
return getCallName().getClassName();
}
public String getTargetMethodName(){
return getCallName().getMethodName();
}
public boolean equals(Object obj)
{
Record rec = (Record)obj;
if(rec == null)
return false;
return (this.ID == rec.ID);
}
public int hashCode()
{
return this.ID;
}
public int getChildCount()
{
return children.size();
}
public Record getChild(int idx)
{
return (Record)children.get(idx);
}
public Iterable<AbstractRecord> allChild()
{
return children;
}
public int getIndexOfChild(Record child)
{
return children.indexOf(child);
}
public void addChild(Record rec)
{
children.add(rec);
for(RecordEventListener l : listeners) {
l.addRecordChild(rec);
}
}
public void callUpdateDataEvent()
{
for(RecordEventListener l : listeners) {
l.updateRecordData(this);
}
for(AbstractRecord rec: this.children)
{
((Record)rec).callUpdateParentDataEvent();
}
}
public void callUpdateParentDataEvent()
{
for(RecordEventListener l : listeners) {
l.updateParentRecordData(this);
}
}
public String toString() {return "Record";}
public String getLabelString(String qlabel, int division) {
if(callName == null)
return "Null Record";
else
{
int p = getPercentage();
if(p == -1)
return String.format(
"%s::%s %d" + qlabel,
getCallName().getClassName(),
getCallName().getMethodName(),
getAllTime() / division
);
else
return String.format(
"%s::%s %d"+qlabel+"(%d%%)",
getCallName().getClassName(),
getCallName().getMethodName(),
getAllTime() / division,
getPercentage()
);
}
}
public String getRecordName()
{
return String.format("%s::%s)", Long.toString(callName.classID), getTargetMethodName());
}
public Record getParent()
{
return parent;
}
public int childIndex(Record child)
{
return children.indexOf(child);
}
public int getPercentage()
{
if(parent == null)
return 100;
if(parent.getAllTime() == 0)
return -1;
return (int)(100*getAllTime() / parent.getAllTime());
}
public void addRunningTime(long n){runningTime += n;}
public void subRunningTime(long n){runningTime -= n;}
public long getRunningTime(){return runningTime;}
public boolean isRunning()
{
return runningTime != 0;
}
public int numRecords(){
return 1;
}
}
public class RecordSet extends AbstractRecord implements RecordEventListener, Iterable<AbstractRecord>{
Set<AbstractRecord> record_set;
String name = "";
public RecordSet()
{
record_set = new HashSet<AbstractRecord>();
}
public Iterator<AbstractRecord> iterator()
{
return record_set.iterator();
}
public boolean isRunning() {
synchronized(record_set)
{
for(AbstractRecord rec: record_set)
{
if(rec.isRunning())
return true;
}
}
return false;
}
@Override
public long getAllTime() {
long result = 0;
synchronized(record_set)
{
for(AbstractRecord rec: record_set)
{
result += rec.getAllTime();
}
}
return result;
}
@Override
public long getAllTimeSent() {
long result = 0;
synchronized(record_set)
{
for(AbstractRecord rec: record_set)
{
result += rec.getAllTimeSent();
}
}
return result;
}
@Override
public long getCallCount() {
long result = 0;
synchronized(record_set)
{
for(AbstractRecord rec: record_set)
{
result += rec.getCallCount();
}
}
return result;
}
@Override
public long getChildrenTime() {
long result = 0;
synchronized(record_set)
{
for(AbstractRecord rec: record_set)
{
result += rec.getChildrenTime();
}
}
return result;
}
@Override
public String getRecordName() {
return this.name;
}
public void setRecordName(String name)
{
this.name = name;
}
public void add(AbstractRecord rec) {
boolean flag;
synchronized(record_set)
{
flag = record_set.add(rec);
}
if(flag)
{
rec.addRecordEventListener(this);
callAddRecordMember(rec);
for(AbstractRecord child: rec.allChild()) {
addRecordChild(child);
}
}
}
public void remove(AbstractRecord rec) {
synchronized(record_set)
{
record_set.remove(rec);
rec.removeRecordEventListener(this);
}
}
public void callAddRecordMember(AbstractRecord newmember) {
for(RecordEventListener l : listeners) {
l.addRecordMember(newmember);
}
}
@Override
public void addRecordChild(AbstractRecord rec) {
for(RecordEventListener l : listeners) {
l.addRecordChild(rec);
}
}
@Override
public void updateParentRecordData(AbstractRecord rec) {
}
@Override
public void updateRecordData(AbstractRecord rec) {
for(RecordEventListener l : listeners) {
l.updateRecordData(this);
}
}
public int numRecords() {
synchronized(record_set)
{
return record_set.size();
}
}
@Override
public void addRecordMember(AbstractRecord rec) {
}
class ChildIterator implements Iterable<AbstractRecord>, Iterator<AbstractRecord> {
Iterator<AbstractRecord> record_set_iter;
Iterator<AbstractRecord> parent_iter;
AbstractRecord nextStock;
@Override
public Iterator<AbstractRecord> iterator() {
record_set_iter = record_set.iterator();
if(record_set_iter.hasNext())
parent_iter = record_set_iter.next().allChild().iterator();
else
parent_iter = null;
getStock();
return this;
}
@Override
public boolean hasNext() {
return nextStock != null;
}
@Override
public AbstractRecord next() {
AbstractRecord result = nextStock;
getStock();
return result;
}
private void getStock() {
while(parent_iter == null || !parent_iter.hasNext())
{
if(!record_set_iter.hasNext())
{
nextStock = null;
return;
}
parent_iter = record_set_iter.next().allChild().iterator();
}
nextStock = parent_iter.next();
}
@Override
public void remove() {
}
}
public Iterable<AbstractRecord> allChild() {
return new ChildIterator();
}
@Override
public int getChildCount() {
int result = 0;
synchronized(record_set)
{
for(AbstractRecord rec: record_set)
{
result += rec.getChildCount();
}
}
return result;
}
}
public class CallNameRecordSet extends RecordSet{
CallName callName;
public CallNameRecordSet(CallName callName)
{
super();
this.callName = callName;
}
public CallName getCallName(){return callName;}
@Override
public boolean equals(Object obj){
if(! (obj instanceof CallNameRecordSet))
return false;
CallNameRecordSet recset = (CallNameRecordSet)obj;
return getCallName().equals(recset.getCallName());
}
@Override
public int hashCode(){
return getCallName().hashCode();
}
public String getTargetClass(){
return getCallName().getClassName();
}
public String getTargetMethodName(){
return getCallName().getMethodName();
}
}
public class ChildrenRecord extends RecordSet {
String name = "";
AbstractRecord parent;
public class ParentListener implements RecordEventListener {
@Override
public void addRecordChild(AbstractRecord rec) {
add(rec);
}
@Override
public void addRecordMember(AbstractRecord rec) {
}
@Override
public void updateParentRecordData(AbstractRecord rec) {
}
@Override
public void updateRecordData(AbstractRecord rec) {
}
}
public ChildrenRecord(AbstractRecord p)
{
parent = p;
for(AbstractRecord child: p.allChild())
{
add(child);
}
parent.addRecordEventListener(new ParentListener());
}
@Override
public String getRecordName() {
return "Children of " + parent.getRecordName();
}
@Override
public void addRecordChild(AbstractRecord rec) {
for(RecordEventListener l : listeners) {
l.addRecordChild(rec);
}
}
}
public class CallName {
public CallName(long classID, long methodID)
{
this.classID = classID;
this.methodID = methodID;
}
public long classID;
public long methodID;
public boolean equals(Object obj)
{
CallName cn = (CallName)obj;
if(cn == null)
return false;
return (this.classID == cn.classID && this.methodID == cn.methodID);
}
public int hashCode()
{
return (int)(this.methodID + this.classID);
}
public String toString()
{
return Long.toString(this.methodID) + "-" + Long.toString(this.methodID);
}
public String getMethodName() {
return method_name_map.get(methodID);
}
public String getClassName() {
return class_name_map.get(classID);
}
}
public class ThreadStore {
List<Record> callNodes;
List<RunningRecordInfo> runningRecords;
long threadID;
ThreadStore(long thread_id){
callNodes = new ArrayList<Record>();
runningRecords = new ArrayList<RunningRecordInfo>();
threadID = thread_id;
}
public Record getNodeRecord(long nodeID_long) {
int nodeID = (int)nodeID_long;
// ほとんどの場合先頭から追加されるからwhileループで追加してok
// 必要であればensureCapacityなど
while(callNodes.size() <= nodeID)
callNodes.add(null);
Record record = callNodes.get(nodeID);
if(record == null) {
record = new Record();
record.ID = nodeID;
record.threadStore = this;
callNodes.set(nodeID, record);
}
return record;
}
public int numNodes() {
return callNodes.size();
}
List<RunningRecordInfo> getRunningRecords() {
return runningRecords;
}
public Record getRootRecord()
{
return getNodeRecord(1);
}
public long getThreadID() {
return threadID;
}
}
Set<EventListener> listeners;
class RunningRecordInfo
{
public Record target;
public long startTime;
public long runningTime;
}
Map<Long, ThreadStore> threadStores;
Map<CallName, CallNameRecordSet > name_to_node;
Map<Long, String> method_name_map;
Map<Long, String> class_name_map;
public DataStore()
{
name_to_node = new HashMap<CallName, CallNameRecordSet>();
listeners = new HashSet<EventListener>();
threadStores = new HashMap<Long, ThreadStore>();
}
public ThreadStore addThreadStore(long thread_id) {
assert !threadStores.containsKey(thread_id);
ThreadStore ts = new ThreadStore(thread_id);
threadStores.put(thread_id, ts);
callAddThreadEvent(ts);
return ts;
}
public ThreadStore getThreadStore(long thread_id, boolean add_new) {
if(add_new && !threadStores.containsKey(thread_id)) {
return addThreadStore(thread_id);
}
return threadStores.get(thread_id);
}
public ThreadStore getThreadStore(long thread_id) {
return getThreadStore(thread_id, false);
}
public long numNodesOfThread(long thread_id) {
return getThreadStore(thread_id).numNodes();
}
public long numAllNodes() {
long result = 0;
for(Map.Entry<Long, ThreadStore> entry: threadStores.entrySet()) {
result += entry.getValue().numNodes();
}
return result;
}
public void addEventListener(EventListener l)
{
listeners.add(l);
}
public void removeEventListener(EventListener l)
{
listeners.remove(l);
}
public int numCallNames()
{
return name_to_node.size();
}
public Record getRootRecord(long thread_id)
{
return getThreadStore(thread_id).getRootRecord();
}
public void setNameMap(Map<Long, String> methods, Map<Long, String> classes)
{
method_name_map = methods;
class_name_map = classes;
}
public Record getNodeRecord(long thread_id, int cnid)
{
return getThreadStore(thread_id).getNodeRecord(cnid);
}
public void recordData(ProfileData data)
{
- if(true) return;
long target_thread = data.getTargetThreadID();
ThreadStore thread_store = getThreadStore(target_thread, true);
List<RunningRecordInfo> running_records = thread_store.runningRecords;
// 実行中補正の記録
StackData sdata = data.getStackData();
long nowTime = sdata.getLong(0, "start_time");
while(sdata.numRecords()-1 < running_records.size())
{
RunningRecordInfo runrec = running_records.get(running_records.size()-1);
running_records.remove(running_records.size()-1);
assert(runrec != null);
assert(runrec.target != null);
if(runrec.target != null)
{
runrec.target.subRunningTime(runrec.runningTime);
runrec.target.callUpdateDataEvent();
}
}
while(sdata.numRecords()-1 > running_records.size())
{
running_records.add(new RunningRecordInfo());
}
assert(running_records.size() == sdata.numRecords()-1);
for(int i = 1; i < sdata.numRecords(); i++)
{
RunningRecordInfo rrec = running_records.get(i-1);
int node_id = sdata.getInt(i, "node_id");
if(node_id != 0)
{
if(rrec.target != null)
{
rrec.target.subRunningTime(rrec.runningTime);
rrec.target.callUpdateDataEvent();
}
rrec.target = thread_store.getNodeRecord(node_id);
rrec.startTime = sdata.getLong(i, "start_time");
rrec.runningTime = 0;
}
if(rrec.target != null)
{
long old_rt = rrec.runningTime;
rrec.runningTime = nowTime - rrec.startTime;
rrec.target.addRunningTime(rrec.runningTime - old_rt);
rrec.target.callUpdateDataEvent();
}
}
// 実行データの記録
for(int i = 0; i < data.numRecords(); i++)
{
CallName cnid = new CallName(data.getLong(i, "class"), data.getLong(i, "mid"));
CallNameRecordSet rec_set;
if(!name_to_node.containsKey(cnid))
{
rec_set = new CallNameRecordSet(cnid);
name_to_node.put(cnid, rec_set);
callAddCallNameEvent(rec_set);
}
else
{
rec_set = name_to_node.get(cnid);
}
int call_node_id = (int)data.getInt(i, "call_node_id");
Record record = thread_store.getNodeRecord(call_node_id);
rec_set.add(record);
if(record.parent == null)
{
record.parent = thread_store.getNodeRecord((int)data.getInt(i, "parent_node_id"));
record.callName = cnid;
record.parent.addChild(record);
}
record.allTime += data.getLong(i, "all_time");
record.childrenTime += data.getLong(i, "children_time");
record.callCount += data.getLong(i, "call_count");
record.callUpdateDataEvent();
}
}
public void callAddCallNameEvent(CallNameRecordSet rset)
{
for(EventListener l: listeners)
{
l.addCallName(rset);
}
}
public void callAddThreadEvent(ThreadStore threadStore)
{
for(EventListener l: listeners)
{
l.addThread(threadStore);
}
}
public CallNameRecordSet getRecordOfCallName(CallName cn)
{
return name_to_node.get(cn);
}
}
| true | true | public void recordData(ProfileData data)
{
if(true) return;
long target_thread = data.getTargetThreadID();
ThreadStore thread_store = getThreadStore(target_thread, true);
List<RunningRecordInfo> running_records = thread_store.runningRecords;
// 実行中補正の記録
StackData sdata = data.getStackData();
long nowTime = sdata.getLong(0, "start_time");
while(sdata.numRecords()-1 < running_records.size())
{
RunningRecordInfo runrec = running_records.get(running_records.size()-1);
running_records.remove(running_records.size()-1);
assert(runrec != null);
assert(runrec.target != null);
if(runrec.target != null)
{
runrec.target.subRunningTime(runrec.runningTime);
runrec.target.callUpdateDataEvent();
}
}
while(sdata.numRecords()-1 > running_records.size())
{
running_records.add(new RunningRecordInfo());
}
assert(running_records.size() == sdata.numRecords()-1);
for(int i = 1; i < sdata.numRecords(); i++)
{
RunningRecordInfo rrec = running_records.get(i-1);
int node_id = sdata.getInt(i, "node_id");
if(node_id != 0)
{
if(rrec.target != null)
{
rrec.target.subRunningTime(rrec.runningTime);
rrec.target.callUpdateDataEvent();
}
rrec.target = thread_store.getNodeRecord(node_id);
rrec.startTime = sdata.getLong(i, "start_time");
rrec.runningTime = 0;
}
if(rrec.target != null)
{
long old_rt = rrec.runningTime;
rrec.runningTime = nowTime - rrec.startTime;
rrec.target.addRunningTime(rrec.runningTime - old_rt);
rrec.target.callUpdateDataEvent();
}
}
// 実行データの記録
for(int i = 0; i < data.numRecords(); i++)
{
CallName cnid = new CallName(data.getLong(i, "class"), data.getLong(i, "mid"));
CallNameRecordSet rec_set;
if(!name_to_node.containsKey(cnid))
{
rec_set = new CallNameRecordSet(cnid);
name_to_node.put(cnid, rec_set);
callAddCallNameEvent(rec_set);
}
else
{
rec_set = name_to_node.get(cnid);
}
int call_node_id = (int)data.getInt(i, "call_node_id");
Record record = thread_store.getNodeRecord(call_node_id);
rec_set.add(record);
if(record.parent == null)
{
record.parent = thread_store.getNodeRecord((int)data.getInt(i, "parent_node_id"));
record.callName = cnid;
record.parent.addChild(record);
}
record.allTime += data.getLong(i, "all_time");
record.childrenTime += data.getLong(i, "children_time");
record.callCount += data.getLong(i, "call_count");
record.callUpdateDataEvent();
}
}
| public void recordData(ProfileData data)
{
long target_thread = data.getTargetThreadID();
ThreadStore thread_store = getThreadStore(target_thread, true);
List<RunningRecordInfo> running_records = thread_store.runningRecords;
// 実行中補正の記録
StackData sdata = data.getStackData();
long nowTime = sdata.getLong(0, "start_time");
while(sdata.numRecords()-1 < running_records.size())
{
RunningRecordInfo runrec = running_records.get(running_records.size()-1);
running_records.remove(running_records.size()-1);
assert(runrec != null);
assert(runrec.target != null);
if(runrec.target != null)
{
runrec.target.subRunningTime(runrec.runningTime);
runrec.target.callUpdateDataEvent();
}
}
while(sdata.numRecords()-1 > running_records.size())
{
running_records.add(new RunningRecordInfo());
}
assert(running_records.size() == sdata.numRecords()-1);
for(int i = 1; i < sdata.numRecords(); i++)
{
RunningRecordInfo rrec = running_records.get(i-1);
int node_id = sdata.getInt(i, "node_id");
if(node_id != 0)
{
if(rrec.target != null)
{
rrec.target.subRunningTime(rrec.runningTime);
rrec.target.callUpdateDataEvent();
}
rrec.target = thread_store.getNodeRecord(node_id);
rrec.startTime = sdata.getLong(i, "start_time");
rrec.runningTime = 0;
}
if(rrec.target != null)
{
long old_rt = rrec.runningTime;
rrec.runningTime = nowTime - rrec.startTime;
rrec.target.addRunningTime(rrec.runningTime - old_rt);
rrec.target.callUpdateDataEvent();
}
}
// 実行データの記録
for(int i = 0; i < data.numRecords(); i++)
{
CallName cnid = new CallName(data.getLong(i, "class"), data.getLong(i, "mid"));
CallNameRecordSet rec_set;
if(!name_to_node.containsKey(cnid))
{
rec_set = new CallNameRecordSet(cnid);
name_to_node.put(cnid, rec_set);
callAddCallNameEvent(rec_set);
}
else
{
rec_set = name_to_node.get(cnid);
}
int call_node_id = (int)data.getInt(i, "call_node_id");
Record record = thread_store.getNodeRecord(call_node_id);
rec_set.add(record);
if(record.parent == null)
{
record.parent = thread_store.getNodeRecord((int)data.getInt(i, "parent_node_id"));
record.callName = cnid;
record.parent.addChild(record);
}
record.allTime += data.getLong(i, "all_time");
record.childrenTime += data.getLong(i, "children_time");
record.callCount += data.getLong(i, "call_count");
record.callUpdateDataEvent();
}
}
|
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/storage/file/PackReverseIndex.java b/org.eclipse.jgit/src/org/eclipse/jgit/storage/file/PackReverseIndex.java
index 990106b93..7eeb02833 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/storage/file/PackReverseIndex.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/storage/file/PackReverseIndex.java
@@ -1,196 +1,196 @@
/*
* Copyright (C) 2008, Marek Zawirski <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.storage.file;
import java.text.MessageFormat;
import java.util.Arrays;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.storage.file.PackIndex.MutableEntry;
/**
* <p>
* Reverse index for forward pack index. Provides operations based on offset
* instead of object id. Such offset-based reverse lookups are performed in
* O(log n) time.
* </p>
*
* @see PackIndex
* @see PackFile
*/
public class PackReverseIndex {
/** Index we were created from, and that has our ObjectId data. */
private final PackIndex index;
/**
* (offset31, truly) Offsets accommodating in 31 bits.
*/
private final int offsets32[];
/**
* Offsets not accommodating in 31 bits.
*/
private final long offsets64[];
/** Position of the corresponding {@link #offsets32} in {@link #index}. */
private final int nth32[];
/** Position of the corresponding {@link #offsets64} in {@link #index}. */
private final int nth64[];
/**
* Create reverse index from straight/forward pack index, by indexing all
* its entries.
*
* @param packIndex
* forward index - entries to (reverse) index.
*/
public PackReverseIndex(final PackIndex packIndex) {
index = packIndex;
final long cnt = index.getObjectCount();
final long n64 = index.getOffset64Count();
final long n32 = cnt - n64;
if (n32 > Integer.MAX_VALUE || n64 > Integer.MAX_VALUE
|| cnt > 0xffffffffL)
throw new IllegalArgumentException(
JGitText.get().hugeIndexesAreNotSupportedByJgitYet);
offsets32 = new int[(int) n32];
offsets64 = new long[(int) n64];
nth32 = new int[offsets32.length];
nth64 = new int[offsets64.length];
int i32 = 0;
int i64 = 0;
for (final MutableEntry me : index) {
final long o = me.getOffset();
- if (o < Integer.MAX_VALUE)
+ if (o <= Integer.MAX_VALUE)
offsets32[i32++] = (int) o;
else
offsets64[i64++] = o;
}
Arrays.sort(offsets32);
Arrays.sort(offsets64);
int nth = 0;
for (final MutableEntry me : index) {
final long o = me.getOffset();
- if (o < Integer.MAX_VALUE)
+ if (o <= Integer.MAX_VALUE)
nth32[Arrays.binarySearch(offsets32, (int) o)] = nth++;
else
nth64[Arrays.binarySearch(offsets64, o)] = nth++;
}
}
/**
* Search for object id with the specified start offset in this pack
* (reverse) index.
*
* @param offset
* start offset of object to find.
* @return object id for this offset, or null if no object was found.
*/
public ObjectId findObject(final long offset) {
if (offset <= Integer.MAX_VALUE) {
final int i32 = Arrays.binarySearch(offsets32, (int) offset);
if (i32 < 0)
return null;
return index.getObjectId(nth32[i32]);
} else {
final int i64 = Arrays.binarySearch(offsets64, offset);
if (i64 < 0)
return null;
return index.getObjectId(nth64[i64]);
}
}
/**
* Search for the next offset to the specified offset in this pack (reverse)
* index.
*
* @param offset
* start offset of previous object (must be valid-existing
* offset).
* @param maxOffset
* maximum offset in a pack (returned when there is no next
* offset).
* @return offset of the next object in a pack or maxOffset if provided
* offset was the last one.
* @throws CorruptObjectException
* when there is no object with the provided offset.
*/
public long findNextOffset(final long offset, final long maxOffset)
throws CorruptObjectException {
if (offset <= Integer.MAX_VALUE) {
final int i32 = Arrays.binarySearch(offsets32, (int) offset);
if (i32 < 0)
throw new CorruptObjectException(
MessageFormat.format(
JGitText.get().cantFindObjectInReversePackIndexForTheSpecifiedOffset,
Long.valueOf(offset)));
if (i32 + 1 == offsets32.length) {
if (offsets64.length > 0)
return offsets64[0];
return maxOffset;
}
return offsets32[i32 + 1];
} else {
final int i64 = Arrays.binarySearch(offsets64, offset);
if (i64 < 0)
throw new CorruptObjectException(
MessageFormat.format(
JGitText.get().cantFindObjectInReversePackIndexForTheSpecifiedOffset,
Long.valueOf(offset)));
if (i64 + 1 == offsets64.length)
return maxOffset;
return offsets64[i64 + 1];
}
}
}
| false | true | public PackReverseIndex(final PackIndex packIndex) {
index = packIndex;
final long cnt = index.getObjectCount();
final long n64 = index.getOffset64Count();
final long n32 = cnt - n64;
if (n32 > Integer.MAX_VALUE || n64 > Integer.MAX_VALUE
|| cnt > 0xffffffffL)
throw new IllegalArgumentException(
JGitText.get().hugeIndexesAreNotSupportedByJgitYet);
offsets32 = new int[(int) n32];
offsets64 = new long[(int) n64];
nth32 = new int[offsets32.length];
nth64 = new int[offsets64.length];
int i32 = 0;
int i64 = 0;
for (final MutableEntry me : index) {
final long o = me.getOffset();
if (o < Integer.MAX_VALUE)
offsets32[i32++] = (int) o;
else
offsets64[i64++] = o;
}
Arrays.sort(offsets32);
Arrays.sort(offsets64);
int nth = 0;
for (final MutableEntry me : index) {
final long o = me.getOffset();
if (o < Integer.MAX_VALUE)
nth32[Arrays.binarySearch(offsets32, (int) o)] = nth++;
else
nth64[Arrays.binarySearch(offsets64, o)] = nth++;
}
}
| public PackReverseIndex(final PackIndex packIndex) {
index = packIndex;
final long cnt = index.getObjectCount();
final long n64 = index.getOffset64Count();
final long n32 = cnt - n64;
if (n32 > Integer.MAX_VALUE || n64 > Integer.MAX_VALUE
|| cnt > 0xffffffffL)
throw new IllegalArgumentException(
JGitText.get().hugeIndexesAreNotSupportedByJgitYet);
offsets32 = new int[(int) n32];
offsets64 = new long[(int) n64];
nth32 = new int[offsets32.length];
nth64 = new int[offsets64.length];
int i32 = 0;
int i64 = 0;
for (final MutableEntry me : index) {
final long o = me.getOffset();
if (o <= Integer.MAX_VALUE)
offsets32[i32++] = (int) o;
else
offsets64[i64++] = o;
}
Arrays.sort(offsets32);
Arrays.sort(offsets64);
int nth = 0;
for (final MutableEntry me : index) {
final long o = me.getOffset();
if (o <= Integer.MAX_VALUE)
nth32[Arrays.binarySearch(offsets32, (int) o)] = nth++;
else
nth64[Arrays.binarySearch(offsets64, o)] = nth++;
}
}
|
diff --git a/src/org/odk/collect/android/tasks/InstanceUploaderTask.java b/src/org/odk/collect/android/tasks/InstanceUploaderTask.java
index 422d632..76a74e1 100644
--- a/src/org/odk/collect/android/tasks/InstanceUploaderTask.java
+++ b/src/org/odk/collect/android/tasks/InstanceUploaderTask.java
@@ -1,486 +1,487 @@
/*
* Copyright (C) 2009 University of Washington
*
* 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.odk.collect.android.tasks;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.protocol.HttpContext;
import org.odk.collect.android.R;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.listeners.InstanceUploaderListener;
import org.odk.collect.android.preferences.PreferencesActivity;
import org.odk.collect.android.provider.InstanceProviderAPI;
import org.odk.collect.android.provider.InstanceProviderAPI.InstanceColumns;
import org.odk.collect.android.utilities.WebUtils;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Background task for uploading completed forms.
*
* @author Carl Hartung ([email protected])
*/
public class InstanceUploaderTask extends AsyncTask<Long, Integer, HashMap<String, String>> {
private static String t = "InstanceUploaderTask";
private InstanceUploaderListener mStateListener;
private static final int CONNECTION_TIMEOUT = 30000;
private static final String fail = "FAILED: ";
private URI mAuthRequestingServer;
HashMap<String, String> mResults;
// TODO: This method is like 350 lines long, down from 400.
// still. ridiculous. make it smaller.
@Override
protected HashMap<String, String> doInBackground(Long... values) {
mResults = new HashMap<String, String>();
String selection = InstanceColumns._ID + "=?";
String[] selectionArgs = new String[values.length];
for (int i = 0; i < values.length; i++) {
if (i != values.length - 1) {
selection += " or " + InstanceColumns._ID + "=?";
}
selectionArgs[i] = values[i].toString();
}
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);
Map<URI, URI> uriRemap = new HashMap<URI, URI>();
Cursor c =
Collect.getInstance().getContentResolver()
.query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
next_submission: while (c.moveToNext()) {
if (isCancelled()) {
return mResults;
}
publishProgress(c.getPosition() + 1, c.getCount());
String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);
String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));
if (urlString == null) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
String submissionUrl =
settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, "/submission");
urlString = urlString + submissionUrl;
}
ContentValues cv = new ContentValues();
URI u = null;
try {
URL url = new URL(urlString);
u = url.toURI();
} catch (MalformedURLException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (URISyntaxException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
boolean openRosaServer = false;
if (uriRemap.containsKey(u)) {
// we already issued a head request and got a response,
// so we know the proper URL to send the submission to
// and the proper scheme. We also know that it was an
// OpenRosa compliant server.
openRosaServer = true;
u = uriRemap.get(u);
} else {
// we need to issue a head request
HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);
// prepare response
HttpResponse response = null;
try {
response = httpclient.execute(httpHead, localContext);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 401) {
// we need authentication, so stop and return what we've
// done so far.
mAuthRequestingServer = u;
+ return null;
} else if (statusCode == 204) {
Header[] locations = response.getHeaders("Location");
if (locations != null && locations.length == 1) {
try {
URL url = new URL(locations[0].getValue());
URI uNew = url.toURI();
if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
openRosaServer = true;
// trust the server to tell us a new location
// ... and possibly to use https instead.
uriRemap.put(u, uNew);
u = uNew;
} else {
// Don't follow a redirection attempt to a different host.
// We can't tell if this is a spoof or not.
mResults.put(
id,
fail
+ "Unexpected redirection attempt to a different host: "
+ uNew.toString());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + urlString + " " + e.getMessage());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} else {
// may be a server that does not handle
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.w(t, "Status code on Head request: " + statusCode);
if (statusCode >= 200 && statusCode <= 299) {
mResults.put(id, fail + "network login? ");
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
mResults.put(id, fail + "client protocol exeption?");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic excpetion. great");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
}
// At this point, we may have updated the uri to use https.
// This occurs only if the Location header keeps the host name
// the same. If it specifies a different host name, we error
// out.
//
// And we may have set authentication cookies in our
// cookiestore (referenced by localContext) that will enable
// authenticated publication to the server.
//
// get instance file
File instanceFile = new File(instance);
if (!instanceFile.exists()) {
mResults.put(id, fail + "instance XML file does not exist!");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
// find all files in parent directory
File[] allFiles = instanceFile.getParentFile().listFiles();
// add media files
List<File> files = new ArrayList<File>();
for (File f : allFiles) {
String fileName = f.getName();
int dotIndex = fileName.lastIndexOf(".");
String extension = "";
if (dotIndex != -1) {
extension = fileName.substring(dotIndex + 1);
}
if (fileName.startsWith(".")) {
// ignore invisible files
continue;
}
if (fileName.equals(instanceFile.getName())) {
continue; // the xml file has already been added
} else if (openRosaServer) {
files.add(f);
} else if (extension.equals("jpg")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gpp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("mp4")) { // legacy 0.9x
files.add(f);
} else {
Log.w(t, "unrecognized file type " + f.getName());
}
}
boolean first = true;
int j = 0;
while (j < files.size() || first) {
first = false;
HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);
MimeTypeMap m = MimeTypeMap.getSingleton();
long byteCount = 0L;
// mime post
MultipartEntity entity = new MultipartEntity();
// add the submission file first...
FileBody fb = new FileBody(instanceFile, "text/xml");
entity.addPart("xml_submission_file", fb);
Log.i(t, "added xml_submission_file: " + instanceFile.getName());
byteCount += instanceFile.length();
for (; j < files.size(); j++) {
File f = files.get(j);
String fileName = f.getName();
int idx = fileName.lastIndexOf(".");
String extension = "";
if (idx != -1) {
extension = fileName.substring(idx + 1);
}
String contentType = m.getMimeTypeFromExtension(extension);
// we will be processing every one of these, so
// we only need to deal with the content type determination...
if (extension.equals("xml")) {
fb = new FileBody(f, "text/xml");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xml file " + f.getName());
} else if (extension.equals("jpg")) {
fb = new FileBody(f, "image/jpeg");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added image file " + f.getName());
} else if (extension.equals("3gpp")) {
fb = new FileBody(f, "audio/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("3gp")) {
fb = new FileBody(f, "video/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("mp4")) {
fb = new FileBody(f, "video/mp4");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("csv")) {
fb = new FileBody(f, "text/csv");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added csv file " + f.getName());
} else if (f.getName().endsWith(".amr")) {
fb = new FileBody(f, "audio/amr");
entity.addPart(f.getName(), fb);
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("xls")) {
fb = new FileBody(f, "application/vnd.ms-excel");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xls file " + f.getName());
} else if (contentType != null) {
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t,
"added recognized filetype (" + contentType + ") " + f.getName());
} else {
contentType = "application/octet-stream";
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
}
// we've added at least one attachment to the request...
if (j + 1 < files.size()) {
if (byteCount + files.get(j + 1).length() > 10000000L) {
// the next file would exceed the 10MB threshold...
Log.i(t, "Extremely long post is being split into multiple posts");
try {
StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
entity.addPart("*isIncomplete*", sb);
} catch (Exception e) {
e.printStackTrace(); // never happens...
}
++j; // advance over the last attachment added...
break;
}
}
}
httppost.setEntity(entity);
// prepare response and return uploaded
HttpResponse response = null;
try {
response = httpclient.execute(httppost, localContext);
int responseCode = response.getStatusLine().getStatusCode();
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.i(t, "Response code:" + responseCode);
// verify that the response was a 201 or 202.
// If it wasn't, the submission has failed.
if (responseCode != 201 && responseCode != 202) {
if (responseCode == 200) {
mResults.put(id, fail + "Network login failure? again?");
} else {
mResults.put(id, fail + urlString + " returned " + responseCode + " " +
response.getStatusLine().getReasonPhrase());
}
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue next_submission;
}
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic exception... " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue next_submission;
}
}
// if it got here, it must have worked
mResults.put(id, Collect.getInstance().getString(R.string.success));
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
}
if (c != null) {
c.close();
}
} // end while
return mResults;
}
@Override
protected void onPostExecute(HashMap<String, String> value) {
synchronized (this) {
if (mStateListener != null) {
if (mAuthRequestingServer != null) {
mStateListener.authRequest(mAuthRequestingServer, mResults);
} else {
mStateListener.uploadingComplete(value);
}
}
}
}
@Override
protected void onProgressUpdate(Integer... values) {
synchronized (this) {
if (mStateListener != null) {
// update progress and total
mStateListener.progressUpdate(values[0].intValue(), values[1].intValue());
}
}
}
public void setUploaderListener(InstanceUploaderListener sl) {
synchronized (this) {
mStateListener = sl;
}
}
}
| true | true | protected HashMap<String, String> doInBackground(Long... values) {
mResults = new HashMap<String, String>();
String selection = InstanceColumns._ID + "=?";
String[] selectionArgs = new String[values.length];
for (int i = 0; i < values.length; i++) {
if (i != values.length - 1) {
selection += " or " + InstanceColumns._ID + "=?";
}
selectionArgs[i] = values[i].toString();
}
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);
Map<URI, URI> uriRemap = new HashMap<URI, URI>();
Cursor c =
Collect.getInstance().getContentResolver()
.query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
next_submission: while (c.moveToNext()) {
if (isCancelled()) {
return mResults;
}
publishProgress(c.getPosition() + 1, c.getCount());
String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);
String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));
if (urlString == null) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
String submissionUrl =
settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, "/submission");
urlString = urlString + submissionUrl;
}
ContentValues cv = new ContentValues();
URI u = null;
try {
URL url = new URL(urlString);
u = url.toURI();
} catch (MalformedURLException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (URISyntaxException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
boolean openRosaServer = false;
if (uriRemap.containsKey(u)) {
// we already issued a head request and got a response,
// so we know the proper URL to send the submission to
// and the proper scheme. We also know that it was an
// OpenRosa compliant server.
openRosaServer = true;
u = uriRemap.get(u);
} else {
// we need to issue a head request
HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);
// prepare response
HttpResponse response = null;
try {
response = httpclient.execute(httpHead, localContext);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 401) {
// we need authentication, so stop and return what we've
// done so far.
mAuthRequestingServer = u;
} else if (statusCode == 204) {
Header[] locations = response.getHeaders("Location");
if (locations != null && locations.length == 1) {
try {
URL url = new URL(locations[0].getValue());
URI uNew = url.toURI();
if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
openRosaServer = true;
// trust the server to tell us a new location
// ... and possibly to use https instead.
uriRemap.put(u, uNew);
u = uNew;
} else {
// Don't follow a redirection attempt to a different host.
// We can't tell if this is a spoof or not.
mResults.put(
id,
fail
+ "Unexpected redirection attempt to a different host: "
+ uNew.toString());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + urlString + " " + e.getMessage());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} else {
// may be a server that does not handle
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.w(t, "Status code on Head request: " + statusCode);
if (statusCode >= 200 && statusCode <= 299) {
mResults.put(id, fail + "network login? ");
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
mResults.put(id, fail + "client protocol exeption?");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic excpetion. great");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
}
// At this point, we may have updated the uri to use https.
// This occurs only if the Location header keeps the host name
// the same. If it specifies a different host name, we error
// out.
//
// And we may have set authentication cookies in our
// cookiestore (referenced by localContext) that will enable
// authenticated publication to the server.
//
// get instance file
File instanceFile = new File(instance);
if (!instanceFile.exists()) {
mResults.put(id, fail + "instance XML file does not exist!");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
// find all files in parent directory
File[] allFiles = instanceFile.getParentFile().listFiles();
// add media files
List<File> files = new ArrayList<File>();
for (File f : allFiles) {
String fileName = f.getName();
int dotIndex = fileName.lastIndexOf(".");
String extension = "";
if (dotIndex != -1) {
extension = fileName.substring(dotIndex + 1);
}
if (fileName.startsWith(".")) {
// ignore invisible files
continue;
}
if (fileName.equals(instanceFile.getName())) {
continue; // the xml file has already been added
} else if (openRosaServer) {
files.add(f);
} else if (extension.equals("jpg")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gpp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("mp4")) { // legacy 0.9x
files.add(f);
} else {
Log.w(t, "unrecognized file type " + f.getName());
}
}
boolean first = true;
int j = 0;
while (j < files.size() || first) {
first = false;
HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);
MimeTypeMap m = MimeTypeMap.getSingleton();
long byteCount = 0L;
// mime post
MultipartEntity entity = new MultipartEntity();
// add the submission file first...
FileBody fb = new FileBody(instanceFile, "text/xml");
entity.addPart("xml_submission_file", fb);
Log.i(t, "added xml_submission_file: " + instanceFile.getName());
byteCount += instanceFile.length();
for (; j < files.size(); j++) {
File f = files.get(j);
String fileName = f.getName();
int idx = fileName.lastIndexOf(".");
String extension = "";
if (idx != -1) {
extension = fileName.substring(idx + 1);
}
String contentType = m.getMimeTypeFromExtension(extension);
// we will be processing every one of these, so
// we only need to deal with the content type determination...
if (extension.equals("xml")) {
fb = new FileBody(f, "text/xml");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xml file " + f.getName());
} else if (extension.equals("jpg")) {
fb = new FileBody(f, "image/jpeg");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added image file " + f.getName());
} else if (extension.equals("3gpp")) {
fb = new FileBody(f, "audio/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("3gp")) {
fb = new FileBody(f, "video/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("mp4")) {
fb = new FileBody(f, "video/mp4");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("csv")) {
fb = new FileBody(f, "text/csv");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added csv file " + f.getName());
} else if (f.getName().endsWith(".amr")) {
fb = new FileBody(f, "audio/amr");
entity.addPart(f.getName(), fb);
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("xls")) {
fb = new FileBody(f, "application/vnd.ms-excel");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xls file " + f.getName());
} else if (contentType != null) {
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t,
"added recognized filetype (" + contentType + ") " + f.getName());
} else {
contentType = "application/octet-stream";
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
}
// we've added at least one attachment to the request...
if (j + 1 < files.size()) {
if (byteCount + files.get(j + 1).length() > 10000000L) {
// the next file would exceed the 10MB threshold...
Log.i(t, "Extremely long post is being split into multiple posts");
try {
StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
entity.addPart("*isIncomplete*", sb);
} catch (Exception e) {
e.printStackTrace(); // never happens...
}
++j; // advance over the last attachment added...
break;
}
}
}
httppost.setEntity(entity);
// prepare response and return uploaded
HttpResponse response = null;
try {
response = httpclient.execute(httppost, localContext);
int responseCode = response.getStatusLine().getStatusCode();
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.i(t, "Response code:" + responseCode);
// verify that the response was a 201 or 202.
// If it wasn't, the submission has failed.
if (responseCode != 201 && responseCode != 202) {
if (responseCode == 200) {
mResults.put(id, fail + "Network login failure? again?");
} else {
mResults.put(id, fail + urlString + " returned " + responseCode + " " +
response.getStatusLine().getReasonPhrase());
}
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue next_submission;
}
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic exception... " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue next_submission;
}
}
// if it got here, it must have worked
mResults.put(id, Collect.getInstance().getString(R.string.success));
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
}
if (c != null) {
c.close();
}
} // end while
return mResults;
}
| protected HashMap<String, String> doInBackground(Long... values) {
mResults = new HashMap<String, String>();
String selection = InstanceColumns._ID + "=?";
String[] selectionArgs = new String[values.length];
for (int i = 0; i < values.length; i++) {
if (i != values.length - 1) {
selection += " or " + InstanceColumns._ID + "=?";
}
selectionArgs[i] = values[i].toString();
}
// get shared HttpContext so that authentication and cookies are retained.
HttpContext localContext = Collect.getInstance().getHttpContext();
HttpClient httpclient = WebUtils.createHttpClient(CONNECTION_TIMEOUT);
Map<URI, URI> uriRemap = new HashMap<URI, URI>();
Cursor c =
Collect.getInstance().getContentResolver()
.query(InstanceColumns.CONTENT_URI, null, selection, selectionArgs, null);
if (c.getCount() > 0) {
c.moveToPosition(-1);
next_submission: while (c.moveToNext()) {
if (isCancelled()) {
return mResults;
}
publishProgress(c.getPosition() + 1, c.getCount());
String instance = c.getString(c.getColumnIndex(InstanceColumns.INSTANCE_FILE_PATH));
String id = c.getString(c.getColumnIndex(InstanceColumns._ID));
Uri toUpdate = Uri.withAppendedPath(InstanceColumns.CONTENT_URI, id);
String urlString = c.getString(c.getColumnIndex(InstanceColumns.SUBMISSION_URI));
if (urlString == null) {
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(Collect.getInstance());
urlString = settings.getString(PreferencesActivity.KEY_SERVER_URL, null);
String submissionUrl =
settings.getString(PreferencesActivity.KEY_SUBMISSION_URL, "/submission");
urlString = urlString + submissionUrl;
}
ContentValues cv = new ContentValues();
URI u = null;
try {
URL url = new URL(urlString);
u = url.toURI();
} catch (MalformedURLException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid url: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (URISyntaxException e) {
e.printStackTrace();
mResults.put(id,
fail + "invalid uri: " + urlString + " :: details: " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
boolean openRosaServer = false;
if (uriRemap.containsKey(u)) {
// we already issued a head request and got a response,
// so we know the proper URL to send the submission to
// and the proper scheme. We also know that it was an
// OpenRosa compliant server.
openRosaServer = true;
u = uriRemap.get(u);
} else {
// we need to issue a head request
HttpHead httpHead = WebUtils.createOpenRosaHttpHead(u);
// prepare response
HttpResponse response = null;
try {
response = httpclient.execute(httpHead, localContext);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 401) {
// we need authentication, so stop and return what we've
// done so far.
mAuthRequestingServer = u;
return null;
} else if (statusCode == 204) {
Header[] locations = response.getHeaders("Location");
if (locations != null && locations.length == 1) {
try {
URL url = new URL(locations[0].getValue());
URI uNew = url.toURI();
if (u.getHost().equalsIgnoreCase(uNew.getHost())) {
openRosaServer = true;
// trust the server to tell us a new location
// ... and possibly to use https instead.
uriRemap.put(u, uNew);
u = uNew;
} else {
// Don't follow a redirection attempt to a different host.
// We can't tell if this is a spoof or not.
mResults.put(
id,
fail
+ "Unexpected redirection attempt to a different host: "
+ uNew.toString());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + urlString + " " + e.getMessage());
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} else {
// may be a server that does not handle
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.w(t, "Status code on Head request: " + statusCode);
if (statusCode >= 200 && statusCode <= 299) {
mResults.put(id, fail + "network login? ");
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
mResults.put(id, fail + "client protocol exeption?");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic excpetion. great");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
}
// At this point, we may have updated the uri to use https.
// This occurs only if the Location header keeps the host name
// the same. If it specifies a different host name, we error
// out.
//
// And we may have set authentication cookies in our
// cookiestore (referenced by localContext) that will enable
// authenticated publication to the server.
//
// get instance file
File instanceFile = new File(instance);
if (!instanceFile.exists()) {
mResults.put(id, fail + "instance XML file does not exist!");
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue;
}
// find all files in parent directory
File[] allFiles = instanceFile.getParentFile().listFiles();
// add media files
List<File> files = new ArrayList<File>();
for (File f : allFiles) {
String fileName = f.getName();
int dotIndex = fileName.lastIndexOf(".");
String extension = "";
if (dotIndex != -1) {
extension = fileName.substring(dotIndex + 1);
}
if (fileName.startsWith(".")) {
// ignore invisible files
continue;
}
if (fileName.equals(instanceFile.getName())) {
continue; // the xml file has already been added
} else if (openRosaServer) {
files.add(f);
} else if (extension.equals("jpg")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gpp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("3gp")) { // legacy 0.9x
files.add(f);
} else if (extension.equals("mp4")) { // legacy 0.9x
files.add(f);
} else {
Log.w(t, "unrecognized file type " + f.getName());
}
}
boolean first = true;
int j = 0;
while (j < files.size() || first) {
first = false;
HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);
MimeTypeMap m = MimeTypeMap.getSingleton();
long byteCount = 0L;
// mime post
MultipartEntity entity = new MultipartEntity();
// add the submission file first...
FileBody fb = new FileBody(instanceFile, "text/xml");
entity.addPart("xml_submission_file", fb);
Log.i(t, "added xml_submission_file: " + instanceFile.getName());
byteCount += instanceFile.length();
for (; j < files.size(); j++) {
File f = files.get(j);
String fileName = f.getName();
int idx = fileName.lastIndexOf(".");
String extension = "";
if (idx != -1) {
extension = fileName.substring(idx + 1);
}
String contentType = m.getMimeTypeFromExtension(extension);
// we will be processing every one of these, so
// we only need to deal with the content type determination...
if (extension.equals("xml")) {
fb = new FileBody(f, "text/xml");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xml file " + f.getName());
} else if (extension.equals("jpg")) {
fb = new FileBody(f, "image/jpeg");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added image file " + f.getName());
} else if (extension.equals("3gpp")) {
fb = new FileBody(f, "audio/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("3gp")) {
fb = new FileBody(f, "video/3gpp");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("mp4")) {
fb = new FileBody(f, "video/mp4");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added video file " + f.getName());
} else if (extension.equals("csv")) {
fb = new FileBody(f, "text/csv");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added csv file " + f.getName());
} else if (f.getName().endsWith(".amr")) {
fb = new FileBody(f, "audio/amr");
entity.addPart(f.getName(), fb);
Log.i(t, "added audio file " + f.getName());
} else if (extension.equals("xls")) {
fb = new FileBody(f, "application/vnd.ms-excel");
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t, "added xls file " + f.getName());
} else if (contentType != null) {
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.i(t,
"added recognized filetype (" + contentType + ") " + f.getName());
} else {
contentType = "application/octet-stream";
fb = new FileBody(f, contentType);
entity.addPart(f.getName(), fb);
byteCount += f.length();
Log.w(t, "added unrecognized file (" + contentType + ") " + f.getName());
}
// we've added at least one attachment to the request...
if (j + 1 < files.size()) {
if (byteCount + files.get(j + 1).length() > 10000000L) {
// the next file would exceed the 10MB threshold...
Log.i(t, "Extremely long post is being split into multiple posts");
try {
StringBody sb = new StringBody("yes", Charset.forName("UTF-8"));
entity.addPart("*isIncomplete*", sb);
} catch (Exception e) {
e.printStackTrace(); // never happens...
}
++j; // advance over the last attachment added...
break;
}
}
}
httppost.setEntity(entity);
// prepare response and return uploaded
HttpResponse response = null;
try {
response = httpclient.execute(httppost, localContext);
int responseCode = response.getStatusLine().getStatusCode();
try {
// have to read the stream in order to reuse the connection
InputStream is = response.getEntity().getContent();
// read to end of stream...
final long count = 1024L;
while (is.skip(count) == count)
;
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.i(t, "Response code:" + responseCode);
// verify that the response was a 201 or 202.
// If it wasn't, the submission has failed.
if (responseCode != 201 && responseCode != 202) {
if (responseCode == 200) {
mResults.put(id, fail + "Network login failure? again?");
} else {
mResults.put(id, fail + urlString + " returned " + responseCode + " " +
response.getStatusLine().getReasonPhrase());
}
cv.put(InstanceColumns.STATUS,
InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver()
.update(toUpdate, cv, null, null);
continue next_submission;
}
} catch (Exception e) {
e.printStackTrace();
mResults.put(id, fail + "generic exception... " + e.getMessage());
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMISSION_FAILED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
continue next_submission;
}
}
// if it got here, it must have worked
mResults.put(id, Collect.getInstance().getString(R.string.success));
cv.put(InstanceColumns.STATUS, InstanceProviderAPI.STATUS_SUBMITTED);
Collect.getInstance().getContentResolver().update(toUpdate, cv, null, null);
}
if (c != null) {
c.close();
}
} // end while
return mResults;
}
|
diff --git a/src/java/org/osjava/norbert/AllowedRule.java b/src/java/org/osjava/norbert/AllowedRule.java
index f1f8089..6e96bc3 100644
--- a/src/java/org/osjava/norbert/AllowedRule.java
+++ b/src/java/org/osjava/norbert/AllowedRule.java
@@ -1,60 +1,58 @@
/*
* Copyright (c) 2003, Henri Yandell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the
* following conditions are met:
*
* + Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* + Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* + Neither the name of OSJava nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.osjava.norbert;
/**
* A norobots Allow: rule.
* Any path which begins with the rule's path is
* allowed.
*/
class AllowedRule extends AbstractRule {
public AllowedRule(String path) {
super(path);
}
public Boolean isAllowed(String query) {
if("".equals(super.getPath())) {
- // What does the spec say here?
- // I think it says to ignore any
- // line without a match
+ // What does the spec say here? Until I know, I'll just ignore this.
return null;
}
boolean test = query.startsWith( super.getPath() );
if(!test) {
return null;
} else {
return Boolean.TRUE;
}
}
}
| true | true | public Boolean isAllowed(String query) {
if("".equals(super.getPath())) {
// What does the spec say here?
// I think it says to ignore any
// line without a match
return null;
}
boolean test = query.startsWith( super.getPath() );
if(!test) {
return null;
} else {
return Boolean.TRUE;
}
}
| public Boolean isAllowed(String query) {
if("".equals(super.getPath())) {
// What does the spec say here? Until I know, I'll just ignore this.
return null;
}
boolean test = query.startsWith( super.getPath() );
if(!test) {
return null;
} else {
return Boolean.TRUE;
}
}
|
diff --git a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java
index 306904e82..0cfb305bd 100644
--- a/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java
+++ b/backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/GwtGL20.java
@@ -1,1105 +1,1105 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.backends.gwt;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.HasArrayBufferView;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.HashMap;
import java.util.Map;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.google.gwt.core.client.GWT;
import com.google.gwt.typedarrays.client.Float32Array;
import com.google.gwt.typedarrays.client.Int16Array;
import com.google.gwt.typedarrays.client.Int32Array;
import com.google.gwt.typedarrays.client.Uint8Array;
import com.google.gwt.webgl.client.WebGLActiveInfo;
import com.google.gwt.webgl.client.WebGLBuffer;
import com.google.gwt.webgl.client.WebGLFramebuffer;
import com.google.gwt.webgl.client.WebGLProgram;
import com.google.gwt.webgl.client.WebGLRenderbuffer;
import com.google.gwt.webgl.client.WebGLRenderingContext;
import com.google.gwt.webgl.client.WebGLShader;
import com.google.gwt.webgl.client.WebGLTexture;
import com.google.gwt.webgl.client.WebGLUniformLocation;
public class GwtGL20 implements GL20 {
final Map<Integer, WebGLProgram> programs = new HashMap<Integer, WebGLProgram>();
int nextProgramId = 1;
final Map<Integer, WebGLShader> shaders = new HashMap<Integer, WebGLShader>();
int nextShaderId = 1;
final Map<Integer, WebGLBuffer> buffers = new HashMap<Integer, WebGLBuffer>();
int nextBufferId = 1;
final Map<Integer, WebGLFramebuffer> frameBuffers = new HashMap<Integer, WebGLFramebuffer>();
int nextFrameBufferId = 1;
final Map<Integer, WebGLRenderbuffer> renderBuffers = new HashMap<Integer, WebGLRenderbuffer>();
int nextRenderBufferId = 1;
final Map<Integer, WebGLTexture> textures = new HashMap<Integer, WebGLTexture>();
int nextTextureId = 1;
final Map<Integer, Map<Integer, WebGLUniformLocation>> uniforms = new HashMap<Integer, Map<Integer, WebGLUniformLocation>>();
int nextUniformId = 1;
int currProgram = 0;
Float32Array floatBuffer = Float32Array.create(2000 * 20);
Int16Array shortBuffer = Int16Array.create(2000 * 6);
final WebGLRenderingContext gl;
protected GwtGL20 (WebGLRenderingContext gl) {
this.gl = gl;
this.gl.pixelStorei(WebGLRenderingContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
}
private void ensureCapacity (FloatBuffer buffer) {
if (buffer.remaining() > floatBuffer.getLength()) {
floatBuffer = Float32Array.create(buffer.remaining());
}
}
private void ensureCapacity (ShortBuffer buffer) {
if (buffer.remaining() > shortBuffer.getLength()) {
shortBuffer = Int16Array.create(buffer.remaining());
}
}
public Float32Array copy (FloatBuffer buffer) {
if (GWT.isProdMode()) {
return ((Float32Array)((HasArrayBufferView)buffer).getTypedArray()).subarray(buffer.position(), buffer.remaining());
} else {
ensureCapacity(buffer);
float[] array = buffer.array();
for (int i = buffer.position(), j = 0; i < buffer.limit(); i++, j++) {
floatBuffer.set(j, array[i]);
}
return floatBuffer.subarray(0, buffer.remaining());
}
}
public Int16Array copy (ShortBuffer buffer) {
if (GWT.isProdMode()) {
return ((Int16Array)((HasArrayBufferView)buffer).getTypedArray()).subarray(buffer.position(), buffer.remaining());
} else {
ensureCapacity(buffer);
short[] array = buffer.array();
for (int i = buffer.position(), j = 0; i < buffer.limit(); i++, j++) {
shortBuffer.set(j, array[i]);
}
return shortBuffer.subarray(0, buffer.remaining());
}
}
private int allocateUniformLocationId (int program, WebGLUniformLocation location) {
Map<Integer, WebGLUniformLocation> progUniforms = uniforms.get(program);
if (progUniforms == null) {
progUniforms = new HashMap<Integer, WebGLUniformLocation>();
uniforms.put(program, progUniforms);
}
// FIXME check if uniform already stored.
int id = nextUniformId++;
progUniforms.put(id, location);
return id;
}
private WebGLUniformLocation getUniformLocation (int location) {
return uniforms.get(currProgram).get(location);
}
private int allocateShaderId (WebGLShader shader) {
int id = nextShaderId++;
shaders.put(id, shader);
return id;
}
private void deallocateShaderId (int id) {
shaders.remove(id);
}
private int allocateProgramId (WebGLProgram program) {
int id = nextProgramId++;
programs.put(id, program);
return id;
}
private void deallocateProgramId (int id) {
uniforms.remove(id);
programs.remove(id);
}
private int allocateBufferId (WebGLBuffer buffer) {
int id = nextBufferId++;
buffers.put(id, buffer);
return id;
}
private void deallocateBufferId (int id) {
buffers.remove(id);
}
private int allocateFrameBufferId (WebGLFramebuffer frameBuffer) {
int id = nextBufferId++;
frameBuffers.put(id, frameBuffer);
return id;
}
private void deallocateFrameBufferId (int id) {
frameBuffers.remove(id);
}
private int allocateRenderBufferId (WebGLRenderbuffer renderBuffer) {
int id = nextRenderBufferId++;
renderBuffers.put(id, renderBuffer);
return id;
}
private void deallocateRenderBufferId (int id) {
renderBuffers.remove(id);
}
private int allocateTextureId (WebGLTexture texture) {
int id = nextTextureId++;
textures.put(id, texture);
return id;
}
private void deallocateTextureId (int id) {
textures.remove(id);
}
@Override
public void glActiveTexture (int texture) {
gl.activeTexture(texture);
}
@Override
public void glBindTexture (int target, int texture) {
gl.bindTexture(target, textures.get(texture));
}
@Override
public void glBlendFunc (int sfactor, int dfactor) {
gl.blendFunc(sfactor, dfactor);
}
@Override
public void glClear (int mask) {
gl.clear(mask);
}
@Override
public void glClearColor (float red, float green, float blue, float alpha) {
gl.clearColor(red, green, blue, alpha);
}
@Override
public void glClearDepthf (float depth) {
gl.clearDepth(depth);
}
@Override
public void glClearStencil (int s) {
gl.clearStencil(s);
}
@Override
public void glColorMask (boolean red, boolean green, boolean blue, boolean alpha) {
gl.colorMask(red, green, blue, alpha);
}
@Override
public void glCompressedTexImage2D (int target, int level, int internalformat, int width, int height, int border,
int imageSize, Buffer data) {
throw new GdxRuntimeException("compressed textures not supported by GWT WebGL backend");
}
@Override
public void glCompressedTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format,
int imageSize, Buffer data) {
throw new GdxRuntimeException("compressed textures not supported by GWT WebGL backend");
}
@Override
public void glCopyTexImage2D (int target, int level, int internalformat, int x, int y, int width, int height, int border) {
gl.copyTexImage2D(target, level, internalformat, x, y, width, height, border);
}
@Override
public void glCopyTexSubImage2D (int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) {
gl.copyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height);
}
@Override
public void glCullFace (int mode) {
gl.cullFace(mode);
}
@Override
public void glDeleteTextures (int n, IntBuffer textures) {
for (int i = 0; i < n; i++) {
int id = textures.get();
WebGLTexture texture = this.textures.get(id);
deallocateTextureId(id);
gl.deleteTexture(texture);
}
}
@Override
public void glDepthFunc (int func) {
gl.depthFunc(func);
}
@Override
public void glDepthMask (boolean flag) {
gl.depthMask(flag);
}
@Override
public void glDepthRangef (float zNear, float zFar) {
gl.depthRange(zNear, zFar);
}
@Override
public void glDisable (int cap) {
gl.disable(cap);
}
@Override
public void glDrawArrays (int mode, int first, int count) {
gl.drawArrays(mode, first, count);
}
@Override
public void glDrawElements (int mode, int count, int type, Buffer indices) {
gl.drawElements(mode, count, type, indices.position()); // FIXME this is assuming WebGL supports client side buffers...
}
@Override
public void glEnable (int cap) {
gl.enable(cap);
}
@Override
public void glFinish () {
gl.finish();
}
@Override
public void glFlush () {
gl.flush();
}
@Override
public void glFrontFace (int mode) {
gl.frontFace(mode);
}
@Override
public void glGenTextures (int n, IntBuffer textures) {
WebGLTexture texture = gl.createTexture();
int id = allocateTextureId(texture);
textures.put(id);
}
@Override
public int glGetError () {
return gl.getError();
}
@Override
public void glGetIntegerv (int pname, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("glGetInteger not supported by GWT WebGL backend");
}
@Override
public String glGetString (int name) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glHint (int target, int mode) {
gl.hint(target, mode);
}
@Override
public void glLineWidth (float width) {
gl.lineWidth(width);
}
@Override
public void glPixelStorei (int pname, int param) {
gl.pixelStorei(pname, param);
}
@Override
public void glPolygonOffset (float factor, float units) {
gl.polygonOffset(factor, units);
}
@Override
public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) {
// verify request
- if ((format != WebGLRenderingContext.UNSIGNED_BYTE) || (type != WebGLRenderingContext.RGBA)) {
+ if ((format != WebGLRenderingContext.RGBA) || (type != WebGLRenderingContext.UNSIGNED_BYTE)) {
throw new GdxRuntimeException("Only format UNSIGNED_BYTE for type RGBA is currently supported.");
}
if (!(pixels instanceof ByteBuffer)) {
throw new GdxRuntimeException("Inputed pixels buffer needs to be of type ByteBuffer.");
}
// create new ArrayBufferView (4 bytes per pixel)
int size = 4 * width * height;
Uint8Array buffer = Uint8Array.create(size);
// read bytes to ArrayBufferView
gl.readPixels(x, y, width, height, format, type, buffer);
// copy ArrayBufferView to our pixels array
ByteBuffer pixelsByte = (ByteBuffer)pixels;
for (int i = 0; i < size; i++) {
pixelsByte.put((byte)(buffer.get(i) & 0x000000ff));
}
}
@Override
public void glScissor (int x, int y, int width, int height) {
gl.scissor(x, y, width, height);
}
@Override
public void glStencilFunc (int func, int ref, int mask) {
gl.stencilFunc(func, ref, mask);
}
@Override
public void glStencilMask (int mask) {
gl.stencilMask(mask);
}
@Override
public void glStencilOp (int fail, int zfail, int zpass) {
gl.stencilOp(fail, zfail, zpass);
}
@Override
public void glTexImage2D (int target, int level, int internalformat, int width, int height, int border, int format, int type,
Buffer pixels) {
Pixmap pixmap = Pixmap.pixmaps.get(((IntBuffer)pixels).get(0));
gl.texImage2D(target, level, internalformat, format, type, pixmap.getCanvasElement());
}
@Override
public void glTexParameterf (int target, int pname, float param) {
gl.texParameterf(target, pname, param);
}
@Override
public void glTexSubImage2D (int target, int level, int xoffset, int yoffset, int width, int height, int format, int type,
Buffer pixels) {
Pixmap pixmap = Pixmap.pixmaps.get(((IntBuffer)pixels).get(0));
gl.texSubImage2D(target, level, xoffset, yoffset, width, height, pixmap.getCanvasElement());
}
@Override
public void glViewport (int x, int y, int width, int height) {
gl.viewport(x, y, width, height);
}
@Override
public void glAttachShader (int program, int shader) {
WebGLProgram glProgram = programs.get(program);
WebGLShader glShader = shaders.get(shader);
gl.attachShader(glProgram, glShader);
}
@Override
public void glBindAttribLocation (int program, int index, String name) {
WebGLProgram glProgram = programs.get(program);
gl.bindAttribLocation(glProgram, index, name);
}
@Override
public void glBindBuffer (int target, int buffer) {
gl.bindBuffer(target, buffers.get(buffer));
}
@Override
public void glBindFramebuffer (int target, int framebuffer) {
gl.bindFramebuffer(target, frameBuffers.get(framebuffer));
}
@Override
public void glBindRenderbuffer (int target, int renderbuffer) {
gl.bindRenderbuffer(target, renderBuffers.get(renderbuffer));
}
@Override
public void glBlendColor (float red, float green, float blue, float alpha) {
gl.blendColor(red, green, blue, alpha);
}
@Override
public void glBlendEquation (int mode) {
gl.blendEquation(mode);
}
@Override
public void glBlendEquationSeparate (int modeRGB, int modeAlpha) {
gl.blendEquationSeparate(modeRGB, modeAlpha);
}
@Override
public void glBlendFuncSeparate (int srcRGB, int dstRGB, int srcAlpha, int dstAlpha) {
gl.blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
}
@Override
public void glBufferData (int target, int size, Buffer data, int usage) {
if (data instanceof FloatBuffer) {
gl.bufferData(target, copy((FloatBuffer)data), usage);
} else if (data instanceof ShortBuffer) {
gl.bufferData(target, copy((ShortBuffer)data), usage);
} else {
throw new GdxRuntimeException("Can only cope with FloatBuffer and ShortBuffer at the moment");
}
}
@Override
public void glBufferSubData (int target, int offset, int size, Buffer data) {
if (data instanceof FloatBuffer) {
gl.bufferSubData(target, offset, copy((FloatBuffer)data));
} else if (data instanceof ShortBuffer) {
gl.bufferSubData(target, offset, copy((ShortBuffer)data));
} else {
throw new GdxRuntimeException("Can only cope with FloatBuffer and ShortBuffer at the moment");
}
}
@Override
public int glCheckFramebufferStatus (int target) {
return gl.checkFramebufferStatus(target);
}
@Override
public void glCompileShader (int shader) {
WebGLShader glShader = shaders.get(shader);
gl.compileShader(glShader);
}
@Override
public int glCreateProgram () {
WebGLProgram program = gl.createProgram();
return allocateProgramId(program);
}
@Override
public int glCreateShader (int type) {
WebGLShader shader = gl.createShader(type);
return allocateShaderId(shader);
}
@Override
public void glDeleteBuffers (int n, IntBuffer buffers) {
for (int i = 0; i < n; i++) {
int id = buffers.get();
WebGLBuffer buffer = this.buffers.get(id);
deallocateBufferId(id);
gl.deleteBuffer(buffer);
}
}
@Override
public void glDeleteFramebuffers (int n, IntBuffer framebuffers) {
for (int i = 0; i < n; i++) {
int id = framebuffers.get();
WebGLFramebuffer fb = this.frameBuffers.get(id);
deallocateFrameBufferId(id);
gl.deleteFramebuffer(fb);
}
}
@Override
public void glDeleteProgram (int program) {
WebGLProgram prog = programs.get(program);
deallocateProgramId(program);
gl.deleteProgram(prog);
}
@Override
public void glDeleteRenderbuffers (int n, IntBuffer renderbuffers) {
for (int i = 0; i < n; i++) {
int id = renderbuffers.get();
WebGLRenderbuffer rb = this.renderBuffers.get(id);
deallocateRenderBufferId(id);
gl.deleteRenderbuffer(rb);
}
}
@Override
public void glDeleteShader (int shader) {
WebGLShader sh = shaders.get(shader);
deallocateShaderId(shader);
gl.deleteShader(sh);
}
@Override
public void glDetachShader (int program, int shader) {
gl.detachShader(programs.get(program), shaders.get(shader));
}
@Override
public void glDisableVertexAttribArray (int index) {
gl.disableVertexAttribArray(index);
}
@Override
public void glDrawElements (int mode, int count, int type, int indices) {
gl.drawElements(mode, count, type, indices);
}
@Override
public void glEnableVertexAttribArray (int index) {
gl.enableVertexAttribArray(index);
}
@Override
public void glFramebufferRenderbuffer (int target, int attachment, int renderbuffertarget, int renderbuffer) {
gl.framebufferRenderbuffer(target, attachment, renderbuffertarget, renderBuffers.get(renderbuffer));
}
@Override
public void glFramebufferTexture2D (int target, int attachment, int textarget, int texture, int level) {
gl.framebufferTexture2D(target, attachment, textarget, textures.get(texture), level);
}
@Override
public void glGenBuffers (int n, IntBuffer buffers) {
for (int i = 0; i < n; i++) {
WebGLBuffer buffer = gl.createBuffer();
int id = allocateBufferId(buffer);
buffers.put(id);
}
}
@Override
public void glGenerateMipmap (int target) {
gl.generateMipmap(target);
}
@Override
public void glGenFramebuffers (int n, IntBuffer framebuffers) {
for (int i = 0; i < n; i++) {
WebGLFramebuffer fb = gl.createFramebuffer();
int id = allocateFrameBufferId(fb);
framebuffers.put(id);
}
}
@Override
public void glGenRenderbuffers (int n, IntBuffer renderbuffers) {
for (int i = 0; i < n; i++) {
WebGLRenderbuffer rb = gl.createRenderbuffer();
int id = allocateRenderBufferId(rb);
renderbuffers.put(id);
}
}
@Override
public String glGetActiveAttrib (int program, int index, IntBuffer size, Buffer type) {
WebGLActiveInfo activeAttrib = gl.getActiveAttrib(programs.get(program), index);
size.put(activeAttrib.getSize());
((IntBuffer)type).put(activeAttrib.getType());
return activeAttrib.getName();
}
@Override
public String glGetActiveUniform (int program, int index, IntBuffer size, Buffer type) {
WebGLActiveInfo activeUniform = gl.getActiveUniform(programs.get(program), index);
size.put(activeUniform.getSize());
((IntBuffer)type).put(activeUniform.getType());
return activeUniform.getName();
}
@Override
public void glGetAttachedShaders (int program, int maxcount, Buffer count, IntBuffer shaders) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public int glGetAttribLocation (int program, String name) {
WebGLProgram prog = programs.get(program);
return gl.getAttribLocation(prog, name);
}
@Override
public void glGetBooleanv (int pname, Buffer params) {
throw new GdxRuntimeException("glGetBoolean not supported by GWT WebGL backend");
}
@Override
public void glGetBufferParameteriv (int target, int pname, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetFloatv (int pname, FloatBuffer params) {
throw new GdxRuntimeException("glGetFloat not supported by GWT WebGL backend");
}
@Override
public void glGetFramebufferAttachmentParameteriv (int target, int attachment, int pname, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetProgramiv (int program, int pname, IntBuffer params) {
if (pname == GL20.GL_DELETE_STATUS || pname == GL20.GL_LINK_STATUS || pname == GL20.GL_VALIDATE_STATUS) {
boolean result = gl.getProgramParameterb(programs.get(program), pname);
params.put(result ? GL20.GL_TRUE : GL20.GL_FALSE);
} else {
params.put(gl.getProgramParameteri(programs.get(program), pname));
}
}
@Override
public String glGetProgramInfoLog (int program) {
return gl.getProgramInfoLog(programs.get(program));
}
@Override
public void glGetRenderbufferParameteriv (int target, int pname, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetShaderiv (int shader, int pname, IntBuffer params) {
if (pname == GL20.GL_COMPILE_STATUS || pname == GL20.GL_DELETE_STATUS) {
boolean result = gl.getShaderParameterb(shaders.get(shader), pname);
params.put(result ? GL20.GL_TRUE : GL20.GL_FALSE);
} else {
int result = gl.getShaderParameteri(shaders.get(shader), pname);
params.put(result);
}
}
@Override
public String glGetShaderInfoLog (int shader) {
return gl.getShaderInfoLog(shaders.get(shader));
}
@Override
public void glGetShaderPrecisionFormat (int shadertype, int precisiontype, IntBuffer range, IntBuffer precision) {
throw new GdxRuntimeException("glGetShaderPrecisionFormat not supported by GWT WebGL backend");
}
@Override
public void glGetShaderSource (int shader, int bufsize, Buffer length, String source) {
throw new GdxRuntimeException("glGetShaderSource not supported by GWT WebGL backend");
}
@Override
public void glGetTexParameterfv (int target, int pname, FloatBuffer params) {
throw new GdxRuntimeException("glGetTexParameter not supported by GWT WebGL backend");
}
@Override
public void glGetTexParameteriv (int target, int pname, IntBuffer params) {
throw new GdxRuntimeException("glGetTexParameter not supported by GWT WebGL backend");
}
@Override
public void glGetUniformfv (int program, int location, FloatBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetUniformiv (int program, int location, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public int glGetUniformLocation (int program, String name) {
WebGLUniformLocation location = gl.getUniformLocation(programs.get(program), name);
return allocateUniformLocationId(program, location);
}
@Override
public void glGetVertexAttribfv (int index, int pname, FloatBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetVertexAttribiv (int index, int pname, IntBuffer params) {
// FIXME
throw new GdxRuntimeException("not implemented");
}
@Override
public void glGetVertexAttribPointerv (int index, int pname, Buffer pointer) {
throw new GdxRuntimeException("glGetVertexAttribPointer not supported by GWT WebGL backend");
}
@Override
public boolean glIsBuffer (int buffer) {
return gl.isBuffer(buffers.get(buffer));
}
@Override
public boolean glIsEnabled (int cap) {
return gl.isEnabled(cap);
}
@Override
public boolean glIsFramebuffer (int framebuffer) {
return gl.isFramebuffer(frameBuffers.get(framebuffer));
}
@Override
public boolean glIsProgram (int program) {
return gl.isProgram(programs.get(program));
}
@Override
public boolean glIsRenderbuffer (int renderbuffer) {
return gl.isRenderbuffer(renderBuffers.get(renderbuffer));
}
@Override
public boolean glIsShader (int shader) {
return gl.isShader(shaders.get(shader));
}
@Override
public boolean glIsTexture (int texture) {
return gl.isTexture(textures.get(texture));
}
@Override
public void glLinkProgram (int program) {
gl.linkProgram(programs.get(program));
}
@Override
public void glReleaseShaderCompiler () {
throw new GdxRuntimeException("not implemented");
}
@Override
public void glRenderbufferStorage (int target, int internalformat, int width, int height) {
gl.renderbufferStorage(target, internalformat, width, height);
}
@Override
public void glSampleCoverage (float value, boolean invert) {
gl.sampleCoverage(value, invert);
}
@Override
public void glShaderBinary (int n, IntBuffer shaders, int binaryformat, Buffer binary, int length) {
throw new GdxRuntimeException("glShaderBinary not supported by GWT WebGL backend");
}
@Override
public void glShaderSource (int shader, String source) {
gl.shaderSource(shaders.get(shader), source);
}
@Override
public void glStencilFuncSeparate (int face, int func, int ref, int mask) {
gl.stencilFuncSeparate(face, func, ref, mask);
}
@Override
public void glStencilMaskSeparate (int face, int mask) {
gl.stencilMaskSeparate(face, mask);
}
@Override
public void glStencilOpSeparate (int face, int fail, int zfail, int zpass) {
gl.stencilOpSeparate(face, fail, zfail, zpass);
}
@Override
public void glTexParameterfv (int target, int pname, FloatBuffer params) {
gl.texParameterf(target, pname, params.get());
}
@Override
public void glTexParameteri (int target, int pname, int param) {
gl.texParameterf(target, pname, param);
}
@Override
public void glTexParameteriv (int target, int pname, IntBuffer params) {
gl.texParameterf(target, pname, params.get());
}
@Override
public void glUniform1f (int location, float x) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform1f(loc, x);
}
@Override
public void glUniform1fv (int location, int count, FloatBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform1fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform1fv(loc, v.array());
}
}
@Override
public void glUniform1i (int location, int x) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform1i(loc, x);
}
@Override
public void glUniform1iv (int location, int count, IntBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform1iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform1iv(loc, v.array());
}
}
@Override
public void glUniform2f (int location, float x, float y) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform2f(loc, x, y);
}
@Override
public void glUniform2fv (int location, int count, FloatBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform2fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
;
} else {
gl.uniform2fv(loc, v.array());
}
}
@Override
public void glUniform2i (int location, int x, int y) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform2i(loc, x, y);
}
@Override
public void glUniform2iv (int location, int count, IntBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform2iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform2iv(loc, v.array());
}
}
@Override
public void glUniform3f (int location, float x, float y, float z) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform3f(loc, x, y, z);
}
@Override
public void glUniform3fv (int location, int count, FloatBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform3fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform3fv(loc, v.array());
}
}
@Override
public void glUniform3i (int location, int x, int y, int z) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform3i(loc, x, y, z);
}
@Override
public void glUniform3iv (int location, int count, IntBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform3iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform3iv(loc, v.array());
}
}
@Override
public void glUniform4f (int location, float x, float y, float z, float w) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform4f(loc, x, y, z, w);
}
@Override
public void glUniform4fv (int location, int count, FloatBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform4fv(loc, ((Float32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform4fv(loc, v.array());
}
}
@Override
public void glUniform4i (int location, int x, int y, int z, int w) {
WebGLUniformLocation loc = getUniformLocation(location);
gl.uniform4i(loc, x, y, z, w);
}
@Override
public void glUniform4iv (int location, int count, IntBuffer v) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniform4iv(loc, ((Int32Array)((HasArrayBufferView)v).getTypedArray()).subarray(v.position(), v.remaining()));
} else {
gl.uniform4iv(loc, v.array());
}
}
@Override
public void glUniformMatrix2fv (int location, int count, boolean transpose, FloatBuffer value) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniformMatrix2fv(loc, transpose,
((Float32Array)((HasArrayBufferView)value).getTypedArray()).subarray(value.position(), value.remaining()));
} else {
gl.uniformMatrix2fv(loc, transpose, value.array());
}
}
@Override
public void glUniformMatrix3fv (int location, int count, boolean transpose, FloatBuffer value) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniformMatrix3fv(loc, transpose,
((Float32Array)((HasArrayBufferView)value).getTypedArray()).subarray(value.position(), value.remaining()));
} else {
gl.uniformMatrix3fv(loc, transpose, value.array());
}
}
@Override
public void glUniformMatrix4fv (int location, int count, boolean transpose, FloatBuffer value) {
WebGLUniformLocation loc = getUniformLocation(location);
if (GWT.isProdMode()) {
gl.uniformMatrix4fv(loc, transpose,
((Float32Array)((HasArrayBufferView)value).getTypedArray()).subarray(value.position(), value.remaining()));
} else {
gl.uniformMatrix4fv(loc, transpose, value.array());
}
}
@Override
public void glUseProgram (int program) {
currProgram = program;
gl.useProgram(programs.get(program));
}
@Override
public void glValidateProgram (int program) {
gl.validateProgram(programs.get(program));
}
@Override
public void glVertexAttrib1f (int indx, float x) {
gl.vertexAttrib1f(indx, x);
}
@Override
public void glVertexAttrib1fv (int indx, FloatBuffer values) {
if (GWT.isProdMode()) {
gl.vertexAttrib1fv(indx,
((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining()));
} else {
gl.vertexAttrib1fv(indx, values.array());
}
}
@Override
public void glVertexAttrib2f (int indx, float x, float y) {
gl.vertexAttrib2f(indx, x, y);
}
@Override
public void glVertexAttrib2fv (int indx, FloatBuffer values) {
if (GWT.isProdMode()) {
gl.vertexAttrib2fv(indx,
((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining()));
} else {
gl.vertexAttrib2fv(indx, values.array());
}
}
@Override
public void glVertexAttrib3f (int indx, float x, float y, float z) {
gl.vertexAttrib3f(indx, x, y, z);
}
@Override
public void glVertexAttrib3fv (int indx, FloatBuffer values) {
if (GWT.isProdMode()) {
gl.vertexAttrib3fv(indx,
((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining()));
} else {
gl.vertexAttrib3fv(indx, values.array());
}
}
@Override
public void glVertexAttrib4f (int indx, float x, float y, float z, float w) {
gl.vertexAttrib4f(indx, x, y, z, w);
}
@Override
public void glVertexAttrib4fv (int indx, FloatBuffer values) {
if (GWT.isProdMode()) {
gl.vertexAttrib4fv(indx,
((Float32Array)((HasArrayBufferView)values).getTypedArray()).subarray(values.position(), values.remaining()));
} else {
gl.vertexAttrib4fv(indx, values.array());
}
}
@Override
public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, Buffer ptr) {
throw new GdxRuntimeException("not implemented, vertex arrays aren't support in WebGL it seems");
}
@Override
public void glVertexAttribPointer (int indx, int size, int type, boolean normalized, int stride, int ptr) {
gl.vertexAttribPointer(indx, size, type, normalized, stride, ptr);
}
}
| true | true | public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) {
// verify request
if ((format != WebGLRenderingContext.UNSIGNED_BYTE) || (type != WebGLRenderingContext.RGBA)) {
throw new GdxRuntimeException("Only format UNSIGNED_BYTE for type RGBA is currently supported.");
}
if (!(pixels instanceof ByteBuffer)) {
throw new GdxRuntimeException("Inputed pixels buffer needs to be of type ByteBuffer.");
}
// create new ArrayBufferView (4 bytes per pixel)
int size = 4 * width * height;
Uint8Array buffer = Uint8Array.create(size);
// read bytes to ArrayBufferView
gl.readPixels(x, y, width, height, format, type, buffer);
// copy ArrayBufferView to our pixels array
ByteBuffer pixelsByte = (ByteBuffer)pixels;
for (int i = 0; i < size; i++) {
pixelsByte.put((byte)(buffer.get(i) & 0x000000ff));
}
}
| public void glReadPixels (int x, int y, int width, int height, int format, int type, Buffer pixels) {
// verify request
if ((format != WebGLRenderingContext.RGBA) || (type != WebGLRenderingContext.UNSIGNED_BYTE)) {
throw new GdxRuntimeException("Only format UNSIGNED_BYTE for type RGBA is currently supported.");
}
if (!(pixels instanceof ByteBuffer)) {
throw new GdxRuntimeException("Inputed pixels buffer needs to be of type ByteBuffer.");
}
// create new ArrayBufferView (4 bytes per pixel)
int size = 4 * width * height;
Uint8Array buffer = Uint8Array.create(size);
// read bytes to ArrayBufferView
gl.readPixels(x, y, width, height, format, type, buffer);
// copy ArrayBufferView to our pixels array
ByteBuffer pixelsByte = (ByteBuffer)pixels;
for (int i = 0; i < size; i++) {
pixelsByte.put((byte)(buffer.get(i) & 0x000000ff));
}
}
|
diff --git a/src/main/java/net/pms/configuration/MapFileConfiguration.java b/src/main/java/net/pms/configuration/MapFileConfiguration.java
index 88baac101..1bb4f5ab5 100644
--- a/src/main/java/net/pms/configuration/MapFileConfiguration.java
+++ b/src/main/java/net/pms/configuration/MapFileConfiguration.java
@@ -1,156 +1,156 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.pms.configuration;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import net.pms.PMS;
import net.pms.util.FileUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author mfranco
*/
public class MapFileConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(MapFileConfiguration.class);
private static final PmsConfiguration configuration = PMS.getConfiguration();
private String name;
private String thumbnailIcon;
private List<MapFileConfiguration> children;
private List<File> files;
public String getName() {
return name;
}
public String getThumbnailIcon() {
return thumbnailIcon;
}
public List<MapFileConfiguration> getChildren() {
return children;
}
public List<File> getFiles() {
return files;
}
public void setName(String n) {
name = n;
}
public void setThumbnailIcon(String t) {
thumbnailIcon = t;
}
public void setFiles(List<File> f) {
files = f;
}
public MapFileConfiguration() {
children = new ArrayList<>();
files = new ArrayList<>();
}
@Deprecated
public static List<MapFileConfiguration> parse(String conf) {
return parseVirtualFolders(null);
}
public static List<MapFileConfiguration> parseVirtualFolders(ArrayList<String> tags) {
String conf;
if (configuration.getVirtualFoldersFile(tags).trim().length() > 0) {
// Get the virtual folder info from the user's file
conf = configuration.getVirtualFoldersFile(tags).trim().replaceAll(",", ",");
File file = new File(configuration.getProfileDirectory(), conf);
conf = null;
if (FileUtil.isFileReadable(file)) {
try {
conf = FileUtils.readFileToString(file);
} catch (IOException ex) {
return null;
}
} else {
LOGGER.warn("Can't read file: {}", file.getAbsolutePath());
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(File.class, new FileSerializer());
Gson gson = gsonBuilder.create();
Type listType = (new TypeToken<ArrayList<MapFileConfiguration>>() { }).getType();
List<MapFileConfiguration> out = gson.fromJson(conf, listType);
return out;
} else if (configuration.getVirtualFolders(tags).trim().length() > 0) {
// Get the virtual folder info from the config string
conf = configuration.getVirtualFolders(tags).trim().replaceAll(",", ",");
// Convert our syntax into JSON syntax
String arrayLevel1[] = conf.split("\\|");
int i = 0;
boolean firstLoop = true;
- StringBuffer jsonStringFromConf = new StringBuffer();
+ StringBuilder jsonStringFromConf = new StringBuilder();
for (String value : arrayLevel1) {
if (!firstLoop) {
jsonStringFromConf.append(",");
}
if (i == 0) {
jsonStringFromConf.append("[{\"name\":\"").append(value).append("\",files:[");
i++;
} else {
String arrayLevel2[] = value.split(",");
for (String value2 : arrayLevel2) {
jsonStringFromConf.append("\"").append(value2).append("\",");
}
jsonStringFromConf.append("]}]");
firstLoop = false;
i = 0;
}
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(File.class, new FileSerializer());
Gson gson = gsonBuilder.create();
Type listType = (new TypeToken<ArrayList<MapFileConfiguration>>() { }).getType();
List<MapFileConfiguration> out = gson.fromJson(jsonStringFromConf.toString().replaceAll("\\\\","\\\\\\\\"), listType);
return out;
}
return null;
}
}
class FileSerializer implements JsonSerializer<File>, JsonDeserializer<File> {
private static final Logger LOGGER = LoggerFactory.getLogger(FileSerializer.class);
@Override
public JsonElement serialize(File src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getAbsolutePath());
}
@Override
public File deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
File file = new File(json.getAsJsonPrimitive().getAsString());
if (!FileUtil.isDirectoryReadable(file)) {
LOGGER.warn("Can't read directory: {}", file.getAbsolutePath());
return null;
} else {
return file;
}
}
}
| true | true | public static List<MapFileConfiguration> parseVirtualFolders(ArrayList<String> tags) {
String conf;
if (configuration.getVirtualFoldersFile(tags).trim().length() > 0) {
// Get the virtual folder info from the user's file
conf = configuration.getVirtualFoldersFile(tags).trim().replaceAll(",", ",");
File file = new File(configuration.getProfileDirectory(), conf);
conf = null;
if (FileUtil.isFileReadable(file)) {
try {
conf = FileUtils.readFileToString(file);
} catch (IOException ex) {
return null;
}
} else {
LOGGER.warn("Can't read file: {}", file.getAbsolutePath());
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(File.class, new FileSerializer());
Gson gson = gsonBuilder.create();
Type listType = (new TypeToken<ArrayList<MapFileConfiguration>>() { }).getType();
List<MapFileConfiguration> out = gson.fromJson(conf, listType);
return out;
} else if (configuration.getVirtualFolders(tags).trim().length() > 0) {
// Get the virtual folder info from the config string
conf = configuration.getVirtualFolders(tags).trim().replaceAll(",", ",");
// Convert our syntax into JSON syntax
String arrayLevel1[] = conf.split("\\|");
int i = 0;
boolean firstLoop = true;
StringBuffer jsonStringFromConf = new StringBuffer();
for (String value : arrayLevel1) {
if (!firstLoop) {
jsonStringFromConf.append(",");
}
if (i == 0) {
jsonStringFromConf.append("[{\"name\":\"").append(value).append("\",files:[");
i++;
} else {
String arrayLevel2[] = value.split(",");
for (String value2 : arrayLevel2) {
jsonStringFromConf.append("\"").append(value2).append("\",");
}
jsonStringFromConf.append("]}]");
firstLoop = false;
i = 0;
}
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(File.class, new FileSerializer());
Gson gson = gsonBuilder.create();
Type listType = (new TypeToken<ArrayList<MapFileConfiguration>>() { }).getType();
List<MapFileConfiguration> out = gson.fromJson(jsonStringFromConf.toString().replaceAll("\\\\","\\\\\\\\"), listType);
return out;
}
return null;
}
| public static List<MapFileConfiguration> parseVirtualFolders(ArrayList<String> tags) {
String conf;
if (configuration.getVirtualFoldersFile(tags).trim().length() > 0) {
// Get the virtual folder info from the user's file
conf = configuration.getVirtualFoldersFile(tags).trim().replaceAll(",", ",");
File file = new File(configuration.getProfileDirectory(), conf);
conf = null;
if (FileUtil.isFileReadable(file)) {
try {
conf = FileUtils.readFileToString(file);
} catch (IOException ex) {
return null;
}
} else {
LOGGER.warn("Can't read file: {}", file.getAbsolutePath());
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(File.class, new FileSerializer());
Gson gson = gsonBuilder.create();
Type listType = (new TypeToken<ArrayList<MapFileConfiguration>>() { }).getType();
List<MapFileConfiguration> out = gson.fromJson(conf, listType);
return out;
} else if (configuration.getVirtualFolders(tags).trim().length() > 0) {
// Get the virtual folder info from the config string
conf = configuration.getVirtualFolders(tags).trim().replaceAll(",", ",");
// Convert our syntax into JSON syntax
String arrayLevel1[] = conf.split("\\|");
int i = 0;
boolean firstLoop = true;
StringBuilder jsonStringFromConf = new StringBuilder();
for (String value : arrayLevel1) {
if (!firstLoop) {
jsonStringFromConf.append(",");
}
if (i == 0) {
jsonStringFromConf.append("[{\"name\":\"").append(value).append("\",files:[");
i++;
} else {
String arrayLevel2[] = value.split(",");
for (String value2 : arrayLevel2) {
jsonStringFromConf.append("\"").append(value2).append("\",");
}
jsonStringFromConf.append("]}]");
firstLoop = false;
i = 0;
}
}
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(File.class, new FileSerializer());
Gson gson = gsonBuilder.create();
Type listType = (new TypeToken<ArrayList<MapFileConfiguration>>() { }).getType();
List<MapFileConfiguration> out = gson.fromJson(jsonStringFromConf.toString().replaceAll("\\\\","\\\\\\\\"), listType);
return out;
}
return null;
}
|
diff --git a/hidapi/src/com/codeminders/hidapi/HIDAPITest.java b/hidapi/src/com/codeminders/hidapi/HIDAPITest.java
index 20a1853..eb7f44e 100644
--- a/hidapi/src/com/codeminders/hidapi/HIDAPITest.java
+++ b/hidapi/src/com/codeminders/hidapi/HIDAPITest.java
@@ -1,94 +1,96 @@
package com.codeminders.hidapi;
import java.io.IOException;
public class HIDAPITest
{
private static final long READ_UPDATE_DELAY_MS = 50L;
static
{
System.loadLibrary("hidapi-jni");
}
// "Afterglow" controller for PS3
static final int VENDOR_ID = 3695;
static final int PRODUCT_ID = 25346;
private static final int BUFSIZE = 2048;
/**
* @param args
*/
public static void main(String[] args)
{
listDevices();
readDevice();
}
private static void readDevice()
{
HIDDevice dev;
try
{
dev = HIDManager.openById(VENDOR_ID, PRODUCT_ID, null);
- //dev.close();
+ System.err.print("Manufacturer: " + dev.getManufacturerString() + "\n");
+ System.err.print("Product: " + dev.getProductString() + "\n");
+ System.err.print("Serial Number: " + dev.getSerialNumberString() + "\n");
try
{
byte[] buf = new byte[BUFSIZE];
dev.enableBlocking();
while(true)
{
int n = dev.read(buf);
System.err.print(""+n+" bytes read:\n\t");
for(int i=0; i<n; i++)
{
int v = buf[i];
if (v<0) v = n+256;
String hs = Integer.toHexString(v);
if (v<16)
System.err.print("0");
System.err.print(hs + " ");
}
System.err.println("");
try
{
Thread.sleep(READ_UPDATE_DELAY_MS);
} catch(InterruptedException e)
{
//Ignore
}
}
} finally
{
dev.close();
}
} catch(IOException e)
{
e.printStackTrace();
}
}
private static void listDevices()
{
String property = System.getProperty("java.library.path");
System.err.println(property);
try
{
HIDDeviceInfo[] devs = HIDManager.listDevices();
System.err.println("Devices:\n\n");
for(int i=0;i<devs.length;i++)
{
System.err.println(""+i+".\t"+devs[i]);
System.err.println("---------------------------------------------\n");
}
}
catch(IOException e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}
}
}
| true | true | private static void readDevice()
{
HIDDevice dev;
try
{
dev = HIDManager.openById(VENDOR_ID, PRODUCT_ID, null);
//dev.close();
try
{
byte[] buf = new byte[BUFSIZE];
dev.enableBlocking();
while(true)
{
int n = dev.read(buf);
System.err.print(""+n+" bytes read:\n\t");
for(int i=0; i<n; i++)
{
int v = buf[i];
if (v<0) v = n+256;
String hs = Integer.toHexString(v);
if (v<16)
System.err.print("0");
System.err.print(hs + " ");
}
System.err.println("");
try
{
Thread.sleep(READ_UPDATE_DELAY_MS);
} catch(InterruptedException e)
{
//Ignore
}
}
} finally
{
dev.close();
}
} catch(IOException e)
{
e.printStackTrace();
}
}
| private static void readDevice()
{
HIDDevice dev;
try
{
dev = HIDManager.openById(VENDOR_ID, PRODUCT_ID, null);
System.err.print("Manufacturer: " + dev.getManufacturerString() + "\n");
System.err.print("Product: " + dev.getProductString() + "\n");
System.err.print("Serial Number: " + dev.getSerialNumberString() + "\n");
try
{
byte[] buf = new byte[BUFSIZE];
dev.enableBlocking();
while(true)
{
int n = dev.read(buf);
System.err.print(""+n+" bytes read:\n\t");
for(int i=0; i<n; i++)
{
int v = buf[i];
if (v<0) v = n+256;
String hs = Integer.toHexString(v);
if (v<16)
System.err.print("0");
System.err.print(hs + " ");
}
System.err.println("");
try
{
Thread.sleep(READ_UPDATE_DELAY_MS);
} catch(InterruptedException e)
{
//Ignore
}
}
} finally
{
dev.close();
}
} catch(IOException e)
{
e.printStackTrace();
}
}
|
diff --git a/src/test/java/org/scriptlet4docx/docx/TemplateFileManagerTest.java b/src/test/java/org/scriptlet4docx/docx/TemplateFileManagerTest.java
index fdc83d8..385c0f4 100644
--- a/src/test/java/org/scriptlet4docx/docx/TemplateFileManagerTest.java
+++ b/src/test/java/org/scriptlet4docx/docx/TemplateFileManagerTest.java
@@ -1,34 +1,36 @@
package org.scriptlet4docx.docx;
import java.io.File;
import java.io.FileInputStream;
import org.junit.Assert;
import org.junit.Test;
public class TemplateFileManagerTest extends Assert {
@Test
public void testTemplatesDirOps() throws Exception {
TemplateFileManager mgr = new TemplateFileManager();
String templateKey = "k1";
File tempDir = mgr.getTemplatesDir();
File docxFile = new File("src/test/resources/docx/DocxTemplaterTest-1.docx");
+ assertFalse(mgr.isPrepared(templateKey));
mgr.prepare(docxFile, templateKey);
+ assertTrue(mgr.isPrepared(templateKey));
assertFalse(mgr.getTemplateContent(templateKey).isEmpty());
assertEquals(mgr.getTemplateUnzipFolder(templateKey), new File(tempDir, templateKey + "/"
+ TemplateFileManager.DOC_UNIZIP_FOLDER_NAME));
assertFalse(mgr.isPreProcessedTemplateExists(templateKey));
mgr.savePreProcessed(templateKey, "1");
assertTrue(mgr.isPreProcessedTemplateExists(templateKey));
assertEquals("1", mgr.getTemplateContent(templateKey));
- assertFalse(mgr.isPreProcessedTemplateExists(templateKey));
+ assertFalse(mgr.isTemplateFileFromStreamExists(templateKey));
mgr.saveTemplateFileFromStream(templateKey, new FileInputStream(docxFile));
- assertTrue(mgr.isPreProcessedTemplateExists(templateKey));
+ assertTrue(mgr.isTemplateFileFromStreamExists(templateKey));
mgr.cleanup();
assertTrue(tempDir.exists());
assertEquals(0, tempDir.listFiles().length);
}
}
| false | true | public void testTemplatesDirOps() throws Exception {
TemplateFileManager mgr = new TemplateFileManager();
String templateKey = "k1";
File tempDir = mgr.getTemplatesDir();
File docxFile = new File("src/test/resources/docx/DocxTemplaterTest-1.docx");
mgr.prepare(docxFile, templateKey);
assertFalse(mgr.getTemplateContent(templateKey).isEmpty());
assertEquals(mgr.getTemplateUnzipFolder(templateKey), new File(tempDir, templateKey + "/"
+ TemplateFileManager.DOC_UNIZIP_FOLDER_NAME));
assertFalse(mgr.isPreProcessedTemplateExists(templateKey));
mgr.savePreProcessed(templateKey, "1");
assertTrue(mgr.isPreProcessedTemplateExists(templateKey));
assertEquals("1", mgr.getTemplateContent(templateKey));
assertFalse(mgr.isPreProcessedTemplateExists(templateKey));
mgr.saveTemplateFileFromStream(templateKey, new FileInputStream(docxFile));
assertTrue(mgr.isPreProcessedTemplateExists(templateKey));
mgr.cleanup();
assertTrue(tempDir.exists());
assertEquals(0, tempDir.listFiles().length);
}
| public void testTemplatesDirOps() throws Exception {
TemplateFileManager mgr = new TemplateFileManager();
String templateKey = "k1";
File tempDir = mgr.getTemplatesDir();
File docxFile = new File("src/test/resources/docx/DocxTemplaterTest-1.docx");
assertFalse(mgr.isPrepared(templateKey));
mgr.prepare(docxFile, templateKey);
assertTrue(mgr.isPrepared(templateKey));
assertFalse(mgr.getTemplateContent(templateKey).isEmpty());
assertEquals(mgr.getTemplateUnzipFolder(templateKey), new File(tempDir, templateKey + "/"
+ TemplateFileManager.DOC_UNIZIP_FOLDER_NAME));
assertFalse(mgr.isPreProcessedTemplateExists(templateKey));
mgr.savePreProcessed(templateKey, "1");
assertTrue(mgr.isPreProcessedTemplateExists(templateKey));
assertEquals("1", mgr.getTemplateContent(templateKey));
assertFalse(mgr.isTemplateFileFromStreamExists(templateKey));
mgr.saveTemplateFileFromStream(templateKey, new FileInputStream(docxFile));
assertTrue(mgr.isTemplateFileFromStreamExists(templateKey));
mgr.cleanup();
assertTrue(tempDir.exists());
assertEquals(0, tempDir.listFiles().length);
}
|
diff --git a/src/fi/helsinki/cs/scheduler3000/report/WeekReport.java b/src/fi/helsinki/cs/scheduler3000/report/WeekReport.java
index afdc7ff..3b6f0ed 100644
--- a/src/fi/helsinki/cs/scheduler3000/report/WeekReport.java
+++ b/src/fi/helsinki/cs/scheduler3000/report/WeekReport.java
@@ -1,95 +1,95 @@
package fi.helsinki.cs.scheduler3000.report;
/**
* @author Team TA's
*/
import java.util.ArrayList;
import java.util.HashMap;
import fi.helsinki.cs.scheduler3000.model.Event;
import fi.helsinki.cs.scheduler3000.model.Schedule;
import fi.helsinki.cs.scheduler3000.model.Weekday;
import fi.helsinki.cs.scheduler3000.model.Weekday.Day;
public class WeekReport extends Report {
public WeekReport(Schedule schedule, HashMap<String, Object> options) {
super(schedule, options);
}
@Override
public String toString() {
if (this.options.containsKey("days")){
ArrayList<Weekday.Day> days = (ArrayList<Day>)this.options.get("days");
String[][] res = new String[days.size() + 1][7]; // +1 for header row
res[0][0] = "\t";
for (int i = 1, j = 0; j < Event.VALID_TIMES.length ; i++, j++){
res[0][i] = Event.VALID_TIMES[j] + "\t";
}
int i = 1;
for (Day day : days){
res[i][0] = day.toString() + "\t";
i++;
}
i = 1;
for (Day d : days){
ArrayList<Event> events = this.schedule.getSchedule().get(d);
if (events == null){
return null;
}
else if (events.size() == 0){
for (int x = 1; x < 7; x++) {
res[i][x] = "\t";
}
}
for (Event event : events){
String entry = "\t"; // if event is null
if (event.getLocation() != null) {
entry = event.getLocation()+"\t";
}
- for( int k = 0; i < Event.VALID_TIMES.length; k++ ) {
+ for( int k = 0; k < Event.VALID_TIMES.length; k++ ) {
int thisTime = Event.VALID_TIMES[k];
if( event.getStartTime() == thisTime) {
res[i][k+1] = entry;
}
}
// fill up with empties
for (int x = 1; x < 7; x++) {
if (res[i][x] == null){
res[i][x] = "\t";
}
}
}
i++;
}
String response = "";
for (int j = 0; j < res.length; j++){
for (int k = 0; k < res[0].length; k++){
response += res[j][k];
}
response += "\n";
}
return response;
}
return null;
}
}
| true | true | public String toString() {
if (this.options.containsKey("days")){
ArrayList<Weekday.Day> days = (ArrayList<Day>)this.options.get("days");
String[][] res = new String[days.size() + 1][7]; // +1 for header row
res[0][0] = "\t";
for (int i = 1, j = 0; j < Event.VALID_TIMES.length ; i++, j++){
res[0][i] = Event.VALID_TIMES[j] + "\t";
}
int i = 1;
for (Day day : days){
res[i][0] = day.toString() + "\t";
i++;
}
i = 1;
for (Day d : days){
ArrayList<Event> events = this.schedule.getSchedule().get(d);
if (events == null){
return null;
}
else if (events.size() == 0){
for (int x = 1; x < 7; x++) {
res[i][x] = "\t";
}
}
for (Event event : events){
String entry = "\t"; // if event is null
if (event.getLocation() != null) {
entry = event.getLocation()+"\t";
}
for( int k = 0; i < Event.VALID_TIMES.length; k++ ) {
int thisTime = Event.VALID_TIMES[k];
if( event.getStartTime() == thisTime) {
res[i][k+1] = entry;
}
}
// fill up with empties
for (int x = 1; x < 7; x++) {
if (res[i][x] == null){
res[i][x] = "\t";
}
}
}
i++;
}
String response = "";
for (int j = 0; j < res.length; j++){
for (int k = 0; k < res[0].length; k++){
response += res[j][k];
}
response += "\n";
}
return response;
}
return null;
}
| public String toString() {
if (this.options.containsKey("days")){
ArrayList<Weekday.Day> days = (ArrayList<Day>)this.options.get("days");
String[][] res = new String[days.size() + 1][7]; // +1 for header row
res[0][0] = "\t";
for (int i = 1, j = 0; j < Event.VALID_TIMES.length ; i++, j++){
res[0][i] = Event.VALID_TIMES[j] + "\t";
}
int i = 1;
for (Day day : days){
res[i][0] = day.toString() + "\t";
i++;
}
i = 1;
for (Day d : days){
ArrayList<Event> events = this.schedule.getSchedule().get(d);
if (events == null){
return null;
}
else if (events.size() == 0){
for (int x = 1; x < 7; x++) {
res[i][x] = "\t";
}
}
for (Event event : events){
String entry = "\t"; // if event is null
if (event.getLocation() != null) {
entry = event.getLocation()+"\t";
}
for( int k = 0; k < Event.VALID_TIMES.length; k++ ) {
int thisTime = Event.VALID_TIMES[k];
if( event.getStartTime() == thisTime) {
res[i][k+1] = entry;
}
}
// fill up with empties
for (int x = 1; x < 7; x++) {
if (res[i][x] == null){
res[i][x] = "\t";
}
}
}
i++;
}
String response = "";
for (int j = 0; j < res.length; j++){
for (int k = 0; k < res[0].length; k++){
response += res[j][k];
}
response += "\n";
}
return response;
}
return null;
}
|
diff --git a/tubular-core/src/main/java/org/trancecode/xproc/Environment.java b/tubular-core/src/main/java/org/trancecode/xproc/Environment.java
index d0089ab4..83e6ff69 100644
--- a/tubular-core/src/main/java/org/trancecode/xproc/Environment.java
+++ b/tubular-core/src/main/java/org/trancecode/xproc/Environment.java
@@ -1,935 +1,934 @@
/*
* Copyright (C) 2008 Herve Quiroz
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* $Id$
*/
package org.trancecode.xproc;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.net.URI;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XPathCompiler;
import net.sf.saxon.s9api.XPathSelector;
import net.sf.saxon.s9api.XdmAtomicValue;
import net.sf.saxon.s9api.XdmItem;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.s9api.XdmValue;
import org.apache.commons.lang.StringUtils;
import org.trancecode.api.ReturnsNullable;
import org.trancecode.collection.TcMaps;
import org.trancecode.logging.Logger;
import org.trancecode.xml.Location;
import org.trancecode.xml.saxon.Saxon;
import org.trancecode.xml.saxon.SaxonAxis;
import org.trancecode.xml.saxon.SaxonBuilder;
import org.trancecode.xml.saxon.SaxonLocation;
import org.trancecode.xml.saxon.SaxonNamespaces;
import org.trancecode.xproc.binding.PortBinding;
import org.trancecode.xproc.port.EnvironmentPort;
import org.trancecode.xproc.port.Port;
import org.trancecode.xproc.port.PortFunctions;
import org.trancecode.xproc.port.PortReference;
import org.trancecode.xproc.port.XProcPorts;
import org.trancecode.xproc.step.Step;
import org.trancecode.xproc.variable.Variable;
/**
* @author Herve Quiroz
*/
public final class Environment
{
private static final Logger LOG = Logger.getLogger(Environment.class);
private static final QName ATTRIBUTE_NAME = new QName("name");
private static final QName ATTRIBUTE_NAMESPACE = new QName("namespace");
private static final QName ATTRIBUTE_VALUE = new QName("value");
private static final QName ELEMENT_PARAM = XProcXmlModel.xprocStepNamespace().newSaxonQName("param");
private static final QName ELEMENT_RESULT = XProcXmlModel.xprocStepNamespace().newSaxonQName("result");
private static final ThreadLocal<Environment> CURRENT_ENVIRONMENT = new ThreadLocal<Environment>();
private static final ThreadLocal<XdmNode> CURRENT_XPATH_CONTEXT = new ThreadLocal<XdmNode>();
private static final ThreadLocal<XdmNode> CURRENT_NAMESPACE_CONTEXT = new ThreadLocal<XdmNode>();
private final EnvironmentPort defaultReadablePort;
private final Map<QName, String> inheritedVariables;
private final Map<QName, String> localVariables;
private final PipelineContext configuration;
private final Map<PortReference, EnvironmentPort> ports;
private final Step pipeline;
private final EnvironmentPort defaultParametersPort;
private final EnvironmentPort xpathContextPort;
public static void setCurrentNamespaceContext(final XdmNode node)
{
CURRENT_NAMESPACE_CONTEXT.set(node);
}
public static XdmNode getCurrentNamespaceContext()
{
return CURRENT_NAMESPACE_CONTEXT.get();
}
public static void setCurrentXPathContext(final XdmNode node)
{
CURRENT_XPATH_CONTEXT.set(node);
}
public static XdmNode getCurrentXPathContext()
{
return CURRENT_XPATH_CONTEXT.get();
}
public static void setCurrentEnvironment(final Environment environment)
{
CURRENT_ENVIRONMENT.set(environment);
}
public void setCurrentEnvironment()
{
setCurrentEnvironment(this);
}
public static Environment getCurrentEnvironment()
{
return CURRENT_ENVIRONMENT.get();
}
private static Map<PortReference, EnvironmentPort> getPortsMap(final Iterable<EnvironmentPort> ports)
{
return Maps.uniqueIndex(ports, PortFunctions.getPortReference());
}
public static Environment newEnvironment(final Step pipeline, final PipelineContext configuration)
{
final Map<QName, String> variables = ImmutableMap.of();
final Iterable<EnvironmentPort> ports = ImmutableList.of();
return new Environment(pipeline, configuration, ports, null, null, null, variables, variables);
}
private Environment(final Step pipeline, final PipelineContext configuration,
final Iterable<EnvironmentPort> ports, final EnvironmentPort defaultReadablePort,
final EnvironmentPort defaultParametersPort, final EnvironmentPort xpathContextPort,
final Map<QName, String> inheritedVariables, final Map<QName, String> localVariables)
{
this(pipeline, configuration, getPortsMap(ports), defaultReadablePort, defaultParametersPort, xpathContextPort,
inheritedVariables, localVariables);
}
private Environment(final Step pipeline, final PipelineContext configuration,
final Map<PortReference, EnvironmentPort> ports, final EnvironmentPort defaultReadablePort,
final EnvironmentPort defaultParametersPort, final EnvironmentPort xpathContextPort,
final Map<QName, String> inheritedVariables, final Map<QName, String> localVariables)
{
this.pipeline = pipeline;
this.configuration = configuration;
this.ports = ImmutableMap.copyOf(ports);
this.defaultReadablePort = defaultReadablePort;
this.defaultParametersPort = defaultParametersPort;
this.xpathContextPort = xpathContextPort;
this.inheritedVariables = ImmutableMap.copyOf(inheritedVariables);
this.localVariables = ImmutableMap.copyOf(localVariables);
}
private Environment setupStepEnvironment(final Step step)
{
return setupStepEnvironment(step, true);
}
private Environment setupStepEnvironment(final Step step, final boolean evaluteVariables)
{
LOG.trace("{@method} step = {}", step.getName());
Environment environment = setupInputPorts(step);
environment = environment.setPrimaryInputPortAsDefaultReadablePort(step);
environment = environment.setXPathContextPort(step);
environment = environment.setDefaultParametersPort(step);
if (evaluteVariables)
{
environment = environment.setupVariables(step);
}
return environment;
}
private Environment setupInputPorts(final Step step)
{
LOG.trace("{@method} step = {}", step.getName());
final Map<PortReference, EnvironmentPort> newPorts = Maps.newHashMap();
for (final Port port : step.getInputPorts())
{
EnvironmentPort environmentPort = EnvironmentPort.newEnvironmentPort(port, this);
if (port.getPortName().equals(XProcPorts.XPATH_CONTEXT) && port.getPortBindings().isEmpty()
&& getXPathContextPort() != null)
{
LOG.trace(" {} is XPath context port", environmentPort);
environmentPort = environmentPort.pipe(getXPathContextPort());
}
newPorts.put(port.getPortReference(), environmentPort);
}
for (final Port port : step.getOutputPorts())
{
if (port.getPortBindings().isEmpty())
{
newPorts.put(port.getPortReference(), EnvironmentPort.newEnvironmentPort(port, this));
}
}
return addPorts(newPorts);
}
public Environment setupOutputPorts(final Step step)
{
LOG.trace("{@method} step = {}", step.getName());
return setupOutputPorts(step, this);
}
public Environment setupOutputPorts(final Step step, final Environment sourceEnvironment)
{
LOG.trace("{@method} step = {}", step.getName());
final Map<PortReference, EnvironmentPort> newPorts = Maps.newHashMap();
for (final Port port : step.getOutputPorts())
{
if (!ports.containsKey(port.getPortReference()))
{
newPorts.put(port.getPortReference(), EnvironmentPort.newEnvironmentPort(port, sourceEnvironment));
}
}
Environment result = addPorts(newPorts);
result = result.setPrimaryOutputPortAsDefaultReadablePort(step, sourceEnvironment);
result = result.setDefaultReadablePortAsXPathContextPort();
return result;
}
public Environment setDefaultReadablePortAsXPathContextPort()
{
final EnvironmentPort port = getDefaultReadablePort();
LOG.trace("{@method} port = {}", port);
return setXPathContextPort(port);
}
private Environment setPrimaryInputPortAsDefaultReadablePort(final Step step)
{
LOG.trace("{@method} step = {} ; type = {}", step.getName(), step.getType());
final Port primaryInputPort = step.getPrimaryInputPort();
LOG.trace("primaryInputPort = {}", primaryInputPort);
if (primaryInputPort == null)
{
return this;
}
LOG.trace("new default readable port = {}", primaryInputPort);
// if port is empty then pipe to existing default readable port
final EnvironmentPort environmentPort = getEnvironmentPort(primaryInputPort);
final EnvironmentPort nonEmptyEnvironmentPort;
if (Iterables.isEmpty(environmentPort.portBindings()) && getDefaultReadablePort() != null)
{
nonEmptyEnvironmentPort = environmentPort.pipe(getDefaultReadablePort());
}
else
{
nonEmptyEnvironmentPort = environmentPort;
}
return addPorts(nonEmptyEnvironmentPort).setDefaultReadablePort(nonEmptyEnvironmentPort);
}
public Environment setPrimaryOutputPortAsDefaultReadablePort(final Step step, final Environment sourceEnvironment)
{
LOG.trace("{@method} step = {}", step.getName());
final Port primaryOutputPort = step.getPrimaryOutputPort();
if (primaryOutputPort == null)
{
return this;
}
LOG.trace("new default readable port = {}", primaryOutputPort);
final EnvironmentPort environmentPort = getEnvironmentPort(primaryOutputPort);
final EnvironmentPort nonEmptyEnvironmentPort;
if (Iterables.isEmpty(environmentPort.portBindings()))
{
nonEmptyEnvironmentPort = environmentPort.pipe(sourceEnvironment.getDefaultReadablePort());
}
else
{
nonEmptyEnvironmentPort = environmentPort;
}
return addPorts(nonEmptyEnvironmentPort).setDefaultReadablePort(nonEmptyEnvironmentPort);
}
private Environment setXPathContextPort(final Step step)
{
LOG.trace("{@method} step = {}", step.getName());
final Port xpathContextPort = step.getXPathContextPort();
if (xpathContextPort == null)
{
return this;
}
return setXPathContextPort(getEnvironmentPort(xpathContextPort));
}
public Environment setupVariables(final Step step)
{
- LOG.trace(this.toString());
LOG.trace("{@method} step = {}", step.getName());
LOG.trace("variables = {keys}", step.getVariables());
final Map<QName, String> allVariables = Maps.newHashMap(inheritedVariables);
allVariables.putAll(localVariables);
final Map<QName, String> newLocalVariables = Maps.newHashMap(localVariables);
final List<XdmNode> newParameterNodes = Lists.newArrayList();
for (final Entry<QName, Variable> variableEntry : step.getVariables().entrySet())
{
final Variable variable = variableEntry.getValue();
LOG.trace("variable = {}", variable);
final String value;
if (variable.getValue() != null)
{
value = variable.getValue();
}
else if (variable.getSelect() == null)
{
if (variable.isRequired())
{
throw XProcExceptions.xs0018(variable);
}
value = null;
}
else
{
final PortBinding xpathPortBinding = variable.getPortBinding();
final XdmNode xpathContextNode;
if (xpathPortBinding != null)
{
try
{
xpathContextNode = Iterables.getOnlyElement(xpathPortBinding.newEnvironmentPortBinding(this)
.readNodes());
}
catch (final NoSuchElementException e)
{
// TODO XProc error?
throw new IllegalStateException("error while evaluating " + variable.getName(), e);
}
}
else
{
xpathContextNode = getXPathContextNode(variable);
}
final XdmValue result = evaluateXPath(variable.getSelect(), getPipelineContext().getProcessor(),
xpathContextNode, variable.getNode(), allVariables, variable.getLocation());
final XdmItem resultNode = Iterables.getOnlyElement(result);
value = resultNode.getStringValue();
}
LOG.trace("{} = {}", variable.getName(), value);
if (value != null)
{
if (variable.isParameter())
{
final XdmNode parameterNode = newParameterElement(variable.getName(), value);
newParameterNodes.add(parameterNode);
}
else
{
allVariables.put(variable.getName(), value);
newLocalVariables.put(variable.getName(), value);
}
}
else
{
newLocalVariables.put(variable.getName(), null);
}
}
final EnvironmentPort parametersPort = getDefaultParametersPort();
final Environment resultEnvironment;
if (newParameterNodes.isEmpty())
{
resultEnvironment = this;
}
else
{
assert parametersPort != null : step.toString();
resultEnvironment = writeNodes(parametersPort, newParameterNodes);
}
return resultEnvironment.setLocalVariables(newLocalVariables);
}
private static XdmValue evaluateXPath(final String select, final Processor processor,
final XdmNode xpathContextNode, final XdmNode namespaceContextNode, final Map<QName, String> variables,
final Location location)
{
LOG.trace("{@method} select = {} ; variables = {}", select, variables);
try
{
final XPathCompiler xpathCompiler = processor.newXPathCompiler();
for (final Map.Entry<QName, String> variableEntry : variables.entrySet())
{
if (variableEntry.getValue() != null)
{
xpathCompiler.declareVariable(variableEntry.getKey());
}
}
for (final Entry<String, String> namespace : SaxonNamespaces.namespaceSequence(namespaceContextNode))
{
xpathCompiler.declareNamespace(namespace.getKey(), namespace.getValue());
}
setCurrentNamespaceContext(namespaceContextNode);
final XPathSelector selector = xpathCompiler.compile(select).load();
if (xpathContextNode != null)
{
LOG.trace("xpathContextNode = {}", xpathContextNode);
selector.setContextItem(processor.newDocumentBuilder().build(xpathContextNode.asSource()));
setCurrentXPathContext(xpathContextNode);
}
for (final Map.Entry<QName, String> variableEntry : variables.entrySet())
{
if (variableEntry.getValue() != null)
{
LOG.trace(" {} = {}", variableEntry.getKey(), variableEntry.getValue());
selector.setVariable(variableEntry.getKey(), new XdmAtomicValue(variableEntry.getValue()));
}
}
final XdmValue result = selector.evaluate();
LOG.trace("result = {}", result);
return result;
}
catch (final SaxonApiException e)
{
final XProcException xprocException = XProcExceptions.xd0023(location, select, e.getMessage());
xprocException.initCause(e);
throw xprocException;
}
}
public Environment newFollowingStepEnvironment(final Step step)
{
return newFollowingStepEnvironment(step, true);
}
public Environment newFollowingStepEnvironment(final Step step, final boolean evaluateVariables)
{
LOG.trace("{@method} step = {}", step.getName());
return newFollowingStepEnvironment().setupStepEnvironment(step, evaluateVariables).setupStepAlias(step);
}
public Environment newFollowingStepEnvironment()
{
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, localVariables);
}
public Environment newChildStepEnvironment(final Step step)
{
LOG.trace("{@method} step = {}", step.getName());
return newChildStepEnvironment().setupStepEnvironment(step);
}
private Environment setupStepAlias(final Step step)
{
Environment environment = this;
final String internalStepName = step.getInternalName();
if (internalStepName != null)
{
LOG.trace("step alias {} -> {}", step.getName(), internalStepName);
for (final Port port : step.getInputPorts())
{
final Port internalPort = port.setStepName(internalStepName).pipe(port);
LOG.trace("{} -> {}", internalPort, port);
final EnvironmentPort environmentPort = EnvironmentPort.newEnvironmentPort(internalPort, environment);
environment = environment.addPorts(environmentPort);
}
}
return environment;
}
public Environment newChildStepEnvironment()
{
final Map<QName, String> variables = ImmutableMap.of();
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, TcMaps.merge(inheritedVariables, localVariables), variables);
}
public Environment setLocalVariables(final Map<QName, String> localVariables)
{
assert localVariables != null;
final ImmutableMap.Builder<QName, String> builder = new ImmutableMap.Builder<QName, String>();
final Map newLocalMap = Maps.newHashMap(this.localVariables);
for (Map.Entry<QName, String> entry : localVariables.entrySet())
{
if (entry.getValue()==null)
{
if (newLocalMap.containsKey(entry.getKey()))
{
newLocalMap.remove(entry.getKey());
}
}
else
{
builder.put(entry.getKey(), entry.getValue());
}
}
final Map<QName, String> mergedMap = TcMaps.merge(newLocalMap, builder.build());
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, mergedMap);
}
public void setLocalVariable(final QName name, final String value)
{
localVariables.put(name, value);
}
public EnvironmentPort getDefaultReadablePort()
{
return defaultReadablePort;
}
public EnvironmentPort getXPathContextPort()
{
return xpathContextPort;
}
public Environment setXPathContextPort(final EnvironmentPort xpathContextPort)
{
LOG.trace("{@method} port = {}", xpathContextPort);
assert xpathContextPort != null;
assert ports.containsValue(xpathContextPort);
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, localVariables);
}
public PipelineContext getPipelineContext()
{
return configuration;
}
public String getVariable(final QName name, final String defaultValue)
{
assert name != null;
LOG.trace("{@method} name = {} ; defaultValue = {}", name, defaultValue);
final String value = getVariable(name);
if (value != null)
{
return value;
}
return defaultValue;
}
public String getVariable(final QName name)
{
assert name != null;
LOG.trace("{@method} name = {}", name);
final String localValue = localVariables.get(name);
if (localValue != null)
{
return localValue;
}
return inheritedVariables.get(name);
}
public Environment setDefaultReadablePort(final EnvironmentPort defaultReadablePort)
{
assert defaultReadablePort != null;
assert ports.containsValue(defaultReadablePort) : defaultReadablePort.getPortReference() + " ; "
+ ports.keySet();
LOG.trace("{@method} defaultReadablePort = {}", defaultReadablePort);
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, localVariables);
}
public Environment setDefaultReadablePort(final PortReference portReference)
{
return setDefaultReadablePort(getPort(portReference));
}
public Map<PortReference, EnvironmentPort> getPorts()
{
return ports;
}
public EnvironmentPort getEnvironmentPort(final Port port)
{
return getEnvironmentPort(port.getPortReference());
}
public EnvironmentPort getEnvironmentPort(final PortReference portReference)
{
final EnvironmentPort port = ports.get(portReference);
Preconditions.checkArgument(port != null, "no such port: %s\navailable ports: %s", portReference,
ports.keySet());
return port;
}
public Environment addPorts(final EnvironmentPort... ports)
{
return addPorts(ImmutableList.copyOf(ports));
}
public Environment addPorts(final Iterable<EnvironmentPort> ports)
{
assert ports != null;
LOG.trace("{@method} ports = {}", ports);
final Map<PortReference, EnvironmentPort> newPorts = Maps.newHashMap(this.ports);
newPorts.putAll(getPortsMap(ports));
return new Environment(pipeline, configuration, newPorts, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, localVariables);
}
public Environment addPorts(final Map<PortReference, EnvironmentPort> ports)
{
assert ports != null;
LOG.trace("{@method} ports = {}", ports);
return new Environment(pipeline, configuration, TcMaps.merge(this.ports, ports), defaultReadablePort,
defaultParametersPort, xpathContextPort, inheritedVariables, localVariables);
}
public Step getPipeline()
{
return pipeline;
}
public URI getBaseUri()
{
return URI.create(pipeline.getLocation().getSystemId());
}
public EnvironmentPort getDefaultParametersPort()
{
return defaultParametersPort;
}
private Environment setDefaultParametersPort(final Step step)
{
final Port port = step.getPrimaryParameterPort();
if (port != null)
{
final EnvironmentPort environmentPort = getEnvironmentPort(port);
assert environmentPort != null;
return setDefaultParametersPort(environmentPort);
}
return this;
}
public Environment setDefaultParametersPort(final EnvironmentPort defaultParametersPort)
{
assert defaultParametersPort != null;
assert ports.containsValue(defaultParametersPort);
LOG.trace("{@method} defaultParametersPort = {}", defaultParametersPort);
return new Environment(pipeline, configuration, ports, defaultReadablePort, defaultParametersPort,
xpathContextPort, inheritedVariables, localVariables);
}
@ReturnsNullable
public XdmNode getXPathContextNode()
{
LOG.trace("{@method}");
// TODO cache
final EnvironmentPort xpathContextPort = getXPathContextPort();
LOG.trace(" xpathContextPort = {}", xpathContextPort);
if (xpathContextPort != null)
{
final Iterator<XdmNode> contextNodes = xpathContextPort.readNodes().iterator();
if (contextNodes.hasNext())
{
final XdmNode contextNode = contextNodes.next();
if (xpathContextPort.getDeclaredPort().getPortName().equals(XProcPorts.XPATH_CONTEXT))
{
// TODO XProc error
assert !contextNodes.hasNext() : xpathContextPort.readNodes();
}
return Saxon.asDocumentNode(contextNode, configuration.getProcessor());
}
}
return Saxon.getEmptyDocument(configuration.getProcessor());
}
@ReturnsNullable
public XdmNode getXPathContextNode(final Variable variable)
{
final EnvironmentPort xpathContextPort = getXPathContextPort();
if (xpathContextPort != null)
{
Iterable<XdmNode> nodes = xpathContextPort.readNodes();
if (((List)nodes).size() > 1 && variable.isVariable())
{
throw XProcExceptions.xd0008(SaxonLocation.of(variable.getNode()));
}
else if (!((List) nodes).isEmpty())
{
return nodes.iterator().next();
}
}
return Saxon.getEmptyDocument(configuration.getProcessor());
}
public XdmValue evaluateXPath(final String select)
{
assert select != null;
LOG.trace("{@method} select = {}", select);
final XdmNode xpathContextNode = getXPathContextNode();
assert xpathContextNode != null;
LOG.trace("xpathContextNode = {}", xpathContextNode);
return evaluateXPath(select, xpathContextNode);
}
public XdmValue evaluateXPath(final String select, final XdmNode xpathContextNode)
{
assert select != null;
LOG.trace("{@method} select = {}", select);
// TODO slow
final Map<QName, String> variables = TcMaps.merge(inheritedVariables, localVariables);
try
{
final XPathCompiler xpathCompiler = configuration.getProcessor().newXPathCompiler();
final String pipelineSystemId = getPipeline().getLocation().getSystemId();
if (pipelineSystemId != null)
{
xpathCompiler.setBaseURI(URI.create(pipelineSystemId));
}
for (final Map.Entry<QName, String> variableEntry : variables.entrySet())
{
if (variableEntry.getValue() != null)
{
xpathCompiler.declareVariable(variableEntry.getKey());
}
}
xpathCompiler.declareNamespace(XProcXmlModel.xprocNamespace().prefix(), XProcXmlModel.xprocNamespace()
.uri());
xpathCompiler.declareNamespace(XProcXmlModel.xprocStepNamespace().prefix(), XProcXmlModel
.xprocStepNamespace().uri());
final XPathSelector selector = xpathCompiler.compile(select).load();
setCurrentXPathContext(xpathContextNode);
selector.setContextItem(xpathContextNode);
for (final Map.Entry<QName, String> variableEntry : variables.entrySet())
{
if (variableEntry.getValue() != null)
{
selector.setVariable(variableEntry.getKey(),
Saxon.getUntypedXdmItem(variableEntry.getValue(), configuration.getProcessor()));
}
}
return selector.evaluate();
}
catch (final Exception e)
{
throw new IllegalStateException("error while evaluating XPath query: " + select, e);
}
}
private EnvironmentPort getPort(final PortReference portReference)
{
assert ports.containsKey(portReference) : "port = " + portReference.toString() + " ; ports = " + ports.keySet();
return ports.get(portReference);
}
public Environment writeNodes(final PortReference portReference, final XdmNode... nodes)
{
return writeNodes(portReference, ImmutableList.copyOf(nodes));
}
public Environment writeNodes(final PortReference portReference, final Iterable<XdmNode> nodes)
{
LOG.trace("{@method} port = {}", portReference);
return addPorts(getPort(portReference).writeNodes(nodes));
}
private Environment writeNodes(final EnvironmentPort port, final Iterable<XdmNode> nodes)
{
LOG.trace("{@method} port = {}", port);
return addPorts(port.writeNodes(nodes));
}
public Iterable<XdmNode> readNodes(final PortReference portReference)
{
LOG.trace("{@method} port = {}", portReference);
final Iterable<XdmNode> nodes = getPort(portReference).readNodes();
LOG.trace("nodes = {}", nodes);
return nodes;
}
public XdmNode readNode(final PortReference portReference)
{
return Iterables.getOnlyElement(readNodes(portReference));
}
public Map<QName, String> readParameters(final PortReference portReference)
{
final Map<QName, String> parameters = TcMaps.newSmallWriteOnceMap();
for (final XdmNode parameterNode : readNodes(portReference))
{
final XPathCompiler xpathCompiler = getPipelineContext().getProcessor().newXPathCompiler();
try
{
final XPathSelector paramsSelector = xpathCompiler.compile("//.[@name]").load();
paramsSelector.setContextItem(parameterNode);
final Iterator<XdmItem> iteratorParams = paramsSelector.iterator();
while (iteratorParams.hasNext())
{
final XdmNode item = (XdmNode) iteratorParams.next();
final Iterable<XdmNode> attributes = SaxonAxis.attributes(item);
final Iterator<XdmNode> iterator = attributes.iterator();
while (iterator.hasNext())
{
final XdmNode attribute = iterator.next();
final QName attName = attribute.getNodeName();
if (!ATTRIBUTE_NAME.equals(attName) && !ATTRIBUTE_NAMESPACE.equals(attName)
&& !ATTRIBUTE_VALUE.equals(attName))
{
throw XProcExceptions.xd0014(item);
}
}
final String name = item.getAttributeValue(ATTRIBUTE_NAME);
final String namespace = item.getAttributeValue(ATTRIBUTE_NAMESPACE);
if (!StringUtils.isEmpty(namespace) && name.contains(":"))
{
final QName aNode = new QName(StringUtils.substringAfter(name, ":"), item);
if (!namespace.equals(aNode.getNamespaceURI()))
{
throw XProcExceptions.xd0025(SaxonLocation.of(item));
}
}
final String value = item.getAttributeValue(ATTRIBUTE_VALUE);
// TODO name should be real QName
parameters.put(new QName(namespace, name), value);
}
}
catch (final SaxonApiException e)
{
throw new PipelineException(e);
}
}
return ImmutableMap.copyOf(parameters);
}
public XdmNode newParameterElement(final QName name, final String value)
{
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(value);
final SaxonBuilder builder = new SaxonBuilder(configuration.getProcessor().getUnderlyingConfiguration());
builder.startDocument();
builder.startElement(ELEMENT_PARAM);
builder.namespace(XProcXmlModel.xprocStepNamespace().prefix(), XProcXmlModel.xprocStepNamespace().uri());
builder.attribute(ATTRIBUTE_NAME, name.toString());
builder.attribute(ATTRIBUTE_VALUE, value);
builder.text(value);
builder.endElement();
builder.endDocument();
return builder.getNode();
}
public XdmNode newResultElement(final String value)
{
Preconditions.checkNotNull(value);
final SaxonBuilder builder = new SaxonBuilder(configuration.getProcessor().getUnderlyingConfiguration());
builder.startDocument();
builder.startElement(ELEMENT_RESULT);
builder.namespace(XProcXmlModel.xprocStepNamespace().prefix(), XProcXmlModel.xprocStepNamespace().uri());
builder.text(value);
builder.endElement();
builder.endDocument();
return builder.getNode();
}
public Iterable<EnvironmentPort> getOutputPorts()
{
return Iterables.filter(ports.values(), new Predicate<EnvironmentPort>()
{
@Override
public boolean apply(final EnvironmentPort port)
{
return port.getDeclaredPort().isOutput();
}
});
}
}
| true | true | public Environment setupVariables(final Step step)
{
LOG.trace(this.toString());
LOG.trace("{@method} step = {}", step.getName());
LOG.trace("variables = {keys}", step.getVariables());
final Map<QName, String> allVariables = Maps.newHashMap(inheritedVariables);
allVariables.putAll(localVariables);
final Map<QName, String> newLocalVariables = Maps.newHashMap(localVariables);
final List<XdmNode> newParameterNodes = Lists.newArrayList();
for (final Entry<QName, Variable> variableEntry : step.getVariables().entrySet())
{
final Variable variable = variableEntry.getValue();
LOG.trace("variable = {}", variable);
final String value;
if (variable.getValue() != null)
{
value = variable.getValue();
}
else if (variable.getSelect() == null)
{
if (variable.isRequired())
{
throw XProcExceptions.xs0018(variable);
}
value = null;
}
else
{
final PortBinding xpathPortBinding = variable.getPortBinding();
final XdmNode xpathContextNode;
if (xpathPortBinding != null)
{
try
{
xpathContextNode = Iterables.getOnlyElement(xpathPortBinding.newEnvironmentPortBinding(this)
.readNodes());
}
catch (final NoSuchElementException e)
{
// TODO XProc error?
throw new IllegalStateException("error while evaluating " + variable.getName(), e);
}
}
else
{
xpathContextNode = getXPathContextNode(variable);
}
final XdmValue result = evaluateXPath(variable.getSelect(), getPipelineContext().getProcessor(),
xpathContextNode, variable.getNode(), allVariables, variable.getLocation());
final XdmItem resultNode = Iterables.getOnlyElement(result);
value = resultNode.getStringValue();
}
LOG.trace("{} = {}", variable.getName(), value);
if (value != null)
{
if (variable.isParameter())
{
final XdmNode parameterNode = newParameterElement(variable.getName(), value);
newParameterNodes.add(parameterNode);
}
else
{
allVariables.put(variable.getName(), value);
newLocalVariables.put(variable.getName(), value);
}
}
else
{
newLocalVariables.put(variable.getName(), null);
}
}
final EnvironmentPort parametersPort = getDefaultParametersPort();
final Environment resultEnvironment;
if (newParameterNodes.isEmpty())
{
resultEnvironment = this;
}
else
{
assert parametersPort != null : step.toString();
resultEnvironment = writeNodes(parametersPort, newParameterNodes);
}
return resultEnvironment.setLocalVariables(newLocalVariables);
}
| public Environment setupVariables(final Step step)
{
LOG.trace("{@method} step = {}", step.getName());
LOG.trace("variables = {keys}", step.getVariables());
final Map<QName, String> allVariables = Maps.newHashMap(inheritedVariables);
allVariables.putAll(localVariables);
final Map<QName, String> newLocalVariables = Maps.newHashMap(localVariables);
final List<XdmNode> newParameterNodes = Lists.newArrayList();
for (final Entry<QName, Variable> variableEntry : step.getVariables().entrySet())
{
final Variable variable = variableEntry.getValue();
LOG.trace("variable = {}", variable);
final String value;
if (variable.getValue() != null)
{
value = variable.getValue();
}
else if (variable.getSelect() == null)
{
if (variable.isRequired())
{
throw XProcExceptions.xs0018(variable);
}
value = null;
}
else
{
final PortBinding xpathPortBinding = variable.getPortBinding();
final XdmNode xpathContextNode;
if (xpathPortBinding != null)
{
try
{
xpathContextNode = Iterables.getOnlyElement(xpathPortBinding.newEnvironmentPortBinding(this)
.readNodes());
}
catch (final NoSuchElementException e)
{
// TODO XProc error?
throw new IllegalStateException("error while evaluating " + variable.getName(), e);
}
}
else
{
xpathContextNode = getXPathContextNode(variable);
}
final XdmValue result = evaluateXPath(variable.getSelect(), getPipelineContext().getProcessor(),
xpathContextNode, variable.getNode(), allVariables, variable.getLocation());
final XdmItem resultNode = Iterables.getOnlyElement(result);
value = resultNode.getStringValue();
}
LOG.trace("{} = {}", variable.getName(), value);
if (value != null)
{
if (variable.isParameter())
{
final XdmNode parameterNode = newParameterElement(variable.getName(), value);
newParameterNodes.add(parameterNode);
}
else
{
allVariables.put(variable.getName(), value);
newLocalVariables.put(variable.getName(), value);
}
}
else
{
newLocalVariables.put(variable.getName(), null);
}
}
final EnvironmentPort parametersPort = getDefaultParametersPort();
final Environment resultEnvironment;
if (newParameterNodes.isEmpty())
{
resultEnvironment = this;
}
else
{
assert parametersPort != null : step.toString();
resultEnvironment = writeNodes(parametersPort, newParameterNodes);
}
return resultEnvironment.setLocalVariables(newLocalVariables);
}
|
diff --git a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java
index f0b5b86fd..e45b7c383 100644
--- a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java
+++ b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/SynapseCallbackReceiver.java
@@ -1,331 +1,331 @@
/*
* 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.soap.SOAPEnvelope;
import org.apache.axiom.soap.SOAPFault;
import org.apache.axiom.soap.SOAPFaultReason;
import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.AddressingConstants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.addressing.RelatesTo;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.async.AxisCallback;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.engine.MessageReceiver;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sandesha2.client.SandeshaClientConstants;
import org.apache.synapse.FaultHandler;
import org.apache.synapse.SynapseConstants;
import org.apache.synapse.SynapseException;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.endpoints.Endpoint;
import org.apache.synapse.transport.nhttp.NhttpConstants;
import java.util.*;
/**
* This is the message receiver that receives the responses for outgoing messages sent out
* by Synapse. It holds a callbackStore that maps the [unique] messageID of each message to
* a callback object that gets executed on timeout or when a response is received (before timeout)
*
* The AnonymousServiceFactory uses this MessageReceiver for all Anonymous services created by it.
* This however - effectively - is a singleton class
*/
public class SynapseCallbackReceiver implements MessageReceiver {
private static final Log log = LogFactory.getLog(SynapseCallbackReceiver.class);
/** This is the synchronized callbackStore that maps outgoing messageID's to callback objects */
private Map callbackStore; // this will be made thread safe within the constructor
/**
* Create the *single* instance of this class that would be used by all anonymous services
* used for outgoing messaging.
* @param synCfg the Synapse configuration
*/
public SynapseCallbackReceiver(SynapseConfiguration synCfg) {
callbackStore = Collections.synchronizedMap(new HashMap());
// create the Timer object and a TimeoutHandler task
TimeoutHandler timeoutHandler = new TimeoutHandler(callbackStore);
Timer timeOutTimer = synCfg.getSynapseTimer();
long timeoutHandlerInterval = SynapseConstants.DEFAULT_TIMEOUT_HANDLER_INTERVAL;
try {
timeoutHandlerInterval = Long.parseLong(
System.getProperty(SynapseConstants.TIMEOUT_HANDLER_INTERVAL));
} catch (Exception ignore) {}
// schedule timeout handler to run every n seconds (n : specified or defaults to 15s)
timeOutTimer.schedule(timeoutHandler, 0, timeoutHandlerInterval);
}
public void addCallback(String MsgID, AxisCallback callback) {
callbackStore.put(MsgID, callback);
}
/**
* Everytime a response message is received this method gets invoked. It will then select
* the outgoing *Synapse* message context for the reply we received, and determine what action
* to take at the Synapse level
*
* @param messageCtx the Axis2 message context of the reply received
* @throws AxisFault
*/
public void receive(MessageContext messageCtx) throws AxisFault {
String messageID = null;
if (messageCtx.getOptions() != null && messageCtx.getOptions().getRelatesTo() != null) {
// never take a chance with a NPE at this stage.. so check at each level :-)
Options options = messageCtx.getOptions();
if (options != null) {
RelatesTo relatesTo = options.getRelatesTo();
if (relatesTo != null) {
messageID = relatesTo.getValue();
}
}
} else if (messageCtx.getProperty(SandeshaClientConstants.SEQUENCE_KEY) == null) {
messageID = (String) messageCtx.getProperty(SynapseConstants.RELATES_TO_FOR_POX);
}
if (messageID != null) {
AxisCallback callback = (AxisCallback) callbackStore.remove(messageID);
RelatesTo[] relates = messageCtx.getRelationships();
if (relates != null && relates.length > 1) {
// we set a relates to to the response message so that if WSA is not used, we
// could still link back to the original message. But if WSA was used, this
// gets duplicated, and we should remove it
removeDuplicateRelatesTo(messageCtx, relates);
}
if (callback != null) {
handleMessage(messageCtx, ((AsyncCallback) callback).getSynapseOutMsgCtx());
} else {
// TODO invoke a generic synapse error handler for this message
log.warn("Synapse received a response for the request with message Id : " +
messageID + " But a callback is not registered (anymore) to process this response");
}
} else if (!messageCtx.isPropertyTrue(NhttpConstants.SC_ACCEPTED)){
// TODO invoke a generic synapse error handler for this message
log.warn("Synapse received a response message without a message Id");
}
}
/**
* Handle the response or error (during a failed send) message received for an outgoing request
*
* @param response the Axis2 MessageContext that has been received and has to be handled
* @param synapseOutMsgCtx the corresponding (outgoing) Synapse MessageContext for the above
* Axis2 MC, that holds Synapse specific information such as the error
* handler stack and local properties etc.
* @throws AxisFault
*/
private void handleMessage(MessageContext response,
org.apache.synapse.MessageContext synapseOutMsgCtx) throws AxisFault {
Object o = response.getProperty(NhttpConstants.SENDING_FAULT);
if (o != null && Boolean.TRUE.equals(o)) {
// there is a sending fault. propagate the fault to fault handlers.
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack != null && !faultStack.isEmpty()) {
SOAPEnvelope envelope = response.getEnvelope();
if (envelope != null) {
SOAPFault fault = envelope.getBody().getFault();
if (fault != null) {
Exception e = fault.getException();
if (e == null) {
e = new Exception(fault.toString());
}
// set an error code to the message context, so that error sequences can
// filter using that property to determine the cause of error
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE,
SynapseConstants.SENDING_FAULT);
SOAPFaultReason faultReason = fault.getReason();
if (faultReason != null) {
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_MESSAGE,
faultReason.getText());
}
if (fault.getException() != null) {
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION,
fault.getException());
}
((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, e);
}
}
}
} else {
// there can always be only one instance of an Endpoint in the faultStack of a message
// if the send was successful, so remove it before we proceed any further
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack !=null && !faultStack.isEmpty()
&& faultStack.peek() instanceof Endpoint) {
faultStack.pop();
}
if (log.isDebugEnabled()) {
log.debug("Synapse received an asynchronous response message");
log.debug("Received To: " +
(response.getTo() != null ? response.getTo().getAddress() : "null"));
log.debug("SOAPAction: " +
(response.getSoapAction() != null ? response.getSoapAction() : "null"));
log.debug("WSA-Action: " +
(response.getWSAAction() != null ? response.getWSAAction() : "null"));
String[] cids = response.getAttachmentMap().getAllContentIDs();
if (cids != null && cids.length > 0) {
for (int i = 0; i < cids.length; i++) {
log.debug("Attachment : " + cids[i]);
}
}
log.debug("Body : \n" + response.getEnvelope());
}
MessageContext axisOutMsgCtx =
((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
response.setServiceContext(null);
response.setOperationContext(axisOutMsgCtx.getOperationContext());
response.getAxisMessage().setParent(
axisOutMsgCtx.getOperationContext().getAxisOperation());
response.setAxisService(axisOutMsgCtx.getAxisService());
// set properties on response
response.setServerSide(true);
response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
response.setProperty(MessageContext.TRANSPORT_OUT,
axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
response.setTransportIn(axisOutMsgCtx.getTransportIn());
response.setTransportOut(axisOutMsgCtx.getTransportOut());
// If request is REST assume that the response is REST too
response.setDoingREST(axisOutMsgCtx.isDoingREST());
if (axisOutMsgCtx.isDoingMTOM()) {
response.setDoingMTOM(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
org.apache.axis2.Constants.VALUE_TRUE);
}
if (axisOutMsgCtx.isDoingSwA()) {
response.setDoingSwA(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_SWA,
org.apache.axis2.Constants.VALUE_TRUE);
}
- // clear the message type property thats used by the message formatter later on
- // to decide whether to write as SOAP/POX etc..
- response.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
+ // copy the message type property thats used by the out message to the response message
+ response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
+ axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE));
// compare original received message (axisOutMsgCtx) soap version with the response
// if they are different change to original version
if(axisOutMsgCtx.isSOAP11() != response.isSOAP11()) {
if(axisOutMsgCtx.isSOAP11()) {
SOAPUtils.convertSOAP12toSOAP11(response);
} else {
SOAPUtils.convertSOAP11toSOAP12(response);
}
}
if (axisOutMsgCtx.getMessageID() != null) {
response.setRelationships(
new RelatesTo[]{new RelatesTo(axisOutMsgCtx.getMessageID())});
}
// create the synapse message context for the response
Axis2MessageContext synapseInMessageContext =
new Axis2MessageContext(
response,
synapseOutMsgCtx.getConfiguration(),
synapseOutMsgCtx.getEnvironment());
synapseInMessageContext.setResponse(true);
synapseInMessageContext.setTo(
new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());
// set the properties of the original MC to the new MC
Iterator iter = synapseOutMsgCtx.getPropertyKeySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
synapseInMessageContext.setProperty(
(String) key, synapseOutMsgCtx.getProperty((String) key));
}
// send the response message through the synapse mediation flow
try {
synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
} catch (SynapseException syne) {
Stack stack = synapseInMessageContext.getFaultStack();
if (stack != null &&
!stack.isEmpty()) {
((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
} else {
log.error("Synapse encountered an exception, " +
"No error handlers found - [Message Dropped]\n" + syne.getMessage());
}
}
}
}
/**
* It is possible for us (Synapse) to cause the creation of a duplicate relatesTo as we
* try to hold onto the outgoing message ID even for POX messages using the relates to
* Now once we get a response, make sure we remove any trace of this before we proceed any
* further
* @param mc the message context from which a possibly duplicated relatesTo should be removed
* @param relates the existing relatedTo array of the message
*/
private void removeDuplicateRelatesTo(MessageContext mc, RelatesTo[] relates) {
int insertPos = 0;
RelatesTo[] newRelates = new RelatesTo[relates.length];
for (int i = 0; i < relates.length; i++) {
RelatesTo current = relates[i];
boolean found = false;
for (int j = 0; j < newRelates.length && j < insertPos; j++) {
if (newRelates[j].equals(current) ||
newRelates[j].getValue().equals(current.getValue())) {
found = true;
break;
}
}
if (!found) {
newRelates[insertPos++] = current;
}
}
RelatesTo[] trimmedRelates = new RelatesTo[insertPos];
System.arraycopy(newRelates, 0, trimmedRelates, 0, insertPos);
mc.setRelationships(trimmedRelates);
}
}
| true | true | private void handleMessage(MessageContext response,
org.apache.synapse.MessageContext synapseOutMsgCtx) throws AxisFault {
Object o = response.getProperty(NhttpConstants.SENDING_FAULT);
if (o != null && Boolean.TRUE.equals(o)) {
// there is a sending fault. propagate the fault to fault handlers.
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack != null && !faultStack.isEmpty()) {
SOAPEnvelope envelope = response.getEnvelope();
if (envelope != null) {
SOAPFault fault = envelope.getBody().getFault();
if (fault != null) {
Exception e = fault.getException();
if (e == null) {
e = new Exception(fault.toString());
}
// set an error code to the message context, so that error sequences can
// filter using that property to determine the cause of error
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE,
SynapseConstants.SENDING_FAULT);
SOAPFaultReason faultReason = fault.getReason();
if (faultReason != null) {
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_MESSAGE,
faultReason.getText());
}
if (fault.getException() != null) {
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION,
fault.getException());
}
((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, e);
}
}
}
} else {
// there can always be only one instance of an Endpoint in the faultStack of a message
// if the send was successful, so remove it before we proceed any further
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack !=null && !faultStack.isEmpty()
&& faultStack.peek() instanceof Endpoint) {
faultStack.pop();
}
if (log.isDebugEnabled()) {
log.debug("Synapse received an asynchronous response message");
log.debug("Received To: " +
(response.getTo() != null ? response.getTo().getAddress() : "null"));
log.debug("SOAPAction: " +
(response.getSoapAction() != null ? response.getSoapAction() : "null"));
log.debug("WSA-Action: " +
(response.getWSAAction() != null ? response.getWSAAction() : "null"));
String[] cids = response.getAttachmentMap().getAllContentIDs();
if (cids != null && cids.length > 0) {
for (int i = 0; i < cids.length; i++) {
log.debug("Attachment : " + cids[i]);
}
}
log.debug("Body : \n" + response.getEnvelope());
}
MessageContext axisOutMsgCtx =
((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
response.setServiceContext(null);
response.setOperationContext(axisOutMsgCtx.getOperationContext());
response.getAxisMessage().setParent(
axisOutMsgCtx.getOperationContext().getAxisOperation());
response.setAxisService(axisOutMsgCtx.getAxisService());
// set properties on response
response.setServerSide(true);
response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
response.setProperty(MessageContext.TRANSPORT_OUT,
axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
response.setTransportIn(axisOutMsgCtx.getTransportIn());
response.setTransportOut(axisOutMsgCtx.getTransportOut());
// If request is REST assume that the response is REST too
response.setDoingREST(axisOutMsgCtx.isDoingREST());
if (axisOutMsgCtx.isDoingMTOM()) {
response.setDoingMTOM(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
org.apache.axis2.Constants.VALUE_TRUE);
}
if (axisOutMsgCtx.isDoingSwA()) {
response.setDoingSwA(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_SWA,
org.apache.axis2.Constants.VALUE_TRUE);
}
// clear the message type property thats used by the message formatter later on
// to decide whether to write as SOAP/POX etc..
response.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
// compare original received message (axisOutMsgCtx) soap version with the response
// if they are different change to original version
if(axisOutMsgCtx.isSOAP11() != response.isSOAP11()) {
if(axisOutMsgCtx.isSOAP11()) {
SOAPUtils.convertSOAP12toSOAP11(response);
} else {
SOAPUtils.convertSOAP11toSOAP12(response);
}
}
if (axisOutMsgCtx.getMessageID() != null) {
response.setRelationships(
new RelatesTo[]{new RelatesTo(axisOutMsgCtx.getMessageID())});
}
// create the synapse message context for the response
Axis2MessageContext synapseInMessageContext =
new Axis2MessageContext(
response,
synapseOutMsgCtx.getConfiguration(),
synapseOutMsgCtx.getEnvironment());
synapseInMessageContext.setResponse(true);
synapseInMessageContext.setTo(
new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());
// set the properties of the original MC to the new MC
Iterator iter = synapseOutMsgCtx.getPropertyKeySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
synapseInMessageContext.setProperty(
(String) key, synapseOutMsgCtx.getProperty((String) key));
}
// send the response message through the synapse mediation flow
try {
synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
} catch (SynapseException syne) {
Stack stack = synapseInMessageContext.getFaultStack();
if (stack != null &&
!stack.isEmpty()) {
((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
} else {
log.error("Synapse encountered an exception, " +
"No error handlers found - [Message Dropped]\n" + syne.getMessage());
}
}
}
}
| private void handleMessage(MessageContext response,
org.apache.synapse.MessageContext synapseOutMsgCtx) throws AxisFault {
Object o = response.getProperty(NhttpConstants.SENDING_FAULT);
if (o != null && Boolean.TRUE.equals(o)) {
// there is a sending fault. propagate the fault to fault handlers.
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack != null && !faultStack.isEmpty()) {
SOAPEnvelope envelope = response.getEnvelope();
if (envelope != null) {
SOAPFault fault = envelope.getBody().getFault();
if (fault != null) {
Exception e = fault.getException();
if (e == null) {
e = new Exception(fault.toString());
}
// set an error code to the message context, so that error sequences can
// filter using that property to determine the cause of error
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE,
SynapseConstants.SENDING_FAULT);
SOAPFaultReason faultReason = fault.getReason();
if (faultReason != null) {
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_MESSAGE,
faultReason.getText());
}
if (fault.getException() != null) {
synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION,
fault.getException());
}
((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, e);
}
}
}
} else {
// there can always be only one instance of an Endpoint in the faultStack of a message
// if the send was successful, so remove it before we proceed any further
Stack faultStack = synapseOutMsgCtx.getFaultStack();
if (faultStack !=null && !faultStack.isEmpty()
&& faultStack.peek() instanceof Endpoint) {
faultStack.pop();
}
if (log.isDebugEnabled()) {
log.debug("Synapse received an asynchronous response message");
log.debug("Received To: " +
(response.getTo() != null ? response.getTo().getAddress() : "null"));
log.debug("SOAPAction: " +
(response.getSoapAction() != null ? response.getSoapAction() : "null"));
log.debug("WSA-Action: " +
(response.getWSAAction() != null ? response.getWSAAction() : "null"));
String[] cids = response.getAttachmentMap().getAllContentIDs();
if (cids != null && cids.length > 0) {
for (int i = 0; i < cids.length; i++) {
log.debug("Attachment : " + cids[i]);
}
}
log.debug("Body : \n" + response.getEnvelope());
}
MessageContext axisOutMsgCtx =
((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
response.setServiceContext(null);
response.setOperationContext(axisOutMsgCtx.getOperationContext());
response.getAxisMessage().setParent(
axisOutMsgCtx.getOperationContext().getAxisOperation());
response.setAxisService(axisOutMsgCtx.getAxisService());
// set properties on response
response.setServerSide(true);
response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
response.setProperty(MessageContext.TRANSPORT_OUT,
axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
response.setTransportIn(axisOutMsgCtx.getTransportIn());
response.setTransportOut(axisOutMsgCtx.getTransportOut());
// If request is REST assume that the response is REST too
response.setDoingREST(axisOutMsgCtx.isDoingREST());
if (axisOutMsgCtx.isDoingMTOM()) {
response.setDoingMTOM(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
org.apache.axis2.Constants.VALUE_TRUE);
}
if (axisOutMsgCtx.isDoingSwA()) {
response.setDoingSwA(true);
response.setProperty(
org.apache.axis2.Constants.Configuration.ENABLE_SWA,
org.apache.axis2.Constants.VALUE_TRUE);
}
// copy the message type property thats used by the out message to the response message
response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE));
// compare original received message (axisOutMsgCtx) soap version with the response
// if they are different change to original version
if(axisOutMsgCtx.isSOAP11() != response.isSOAP11()) {
if(axisOutMsgCtx.isSOAP11()) {
SOAPUtils.convertSOAP12toSOAP11(response);
} else {
SOAPUtils.convertSOAP11toSOAP12(response);
}
}
if (axisOutMsgCtx.getMessageID() != null) {
response.setRelationships(
new RelatesTo[]{new RelatesTo(axisOutMsgCtx.getMessageID())});
}
// create the synapse message context for the response
Axis2MessageContext synapseInMessageContext =
new Axis2MessageContext(
response,
synapseOutMsgCtx.getConfiguration(),
synapseOutMsgCtx.getEnvironment());
synapseInMessageContext.setResponse(true);
synapseInMessageContext.setTo(
new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());
// set the properties of the original MC to the new MC
Iterator iter = synapseOutMsgCtx.getPropertyKeySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
synapseInMessageContext.setProperty(
(String) key, synapseOutMsgCtx.getProperty((String) key));
}
// send the response message through the synapse mediation flow
try {
synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
} catch (SynapseException syne) {
Stack stack = synapseInMessageContext.getFaultStack();
if (stack != null &&
!stack.isEmpty()) {
((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
} else {
log.error("Synapse encountered an exception, " +
"No error handlers found - [Message Dropped]\n" + syne.getMessage());
}
}
}
}
|
diff --git a/main/BigNFA.java b/main/BigNFA.java
index 6eea2f6..1dd35df 100644
--- a/main/BigNFA.java
+++ b/main/BigNFA.java
@@ -1,47 +1,44 @@
package main;
import java.util.*;
public class BigNFA
{
private NFA nfa;
public BigNFA(HashSet<NFA> NFATable)
{
nfa = conversion(NFATable);
}
// Converts a set of NFA's into one giant NFA
// Adds epsilon transitions from a new start state to each NFA
// Adds epsilon transitions from all accept states to one new accept state
- private NFA conversion(HashSet<NFA> NFATAble)
+ private NFA conversion(HashSet<NFA> NFATable)
{
NFA fin=new NFA("The Big One");
- State start=new State(false,new HashMap<String,State>());
+ State start=new State(false,new HashMap<String,List<State>>());
State accept=new State(true,null);
for(NFA nfa : NFATable)
{
- start.addTransition("Epsilon",nfa.getStart());
- for(State st : nfa.getAccept())
- {
- st.addTransition("Epsilon",accept);
- st.setAccept(false);
- }
+ start.addTransition("Epsilon",nfa.getStart());
+ nfa.getAccept().addTransition("Epsilon",accept);
+ nfa.getAccept().setIsAccept(false);
}
- fin=fin.setStart(start);
- fin=fin.setAccept(accept);
+ fin.setStart(start);
+ fin.setAccept(accept);
return fin;
}
public NFA getNFA()
{
return nfa;
}
public void setNFA(NFA nfa)
{
this.nfa=nfa;
}
}
| false | true | private NFA conversion(HashSet<NFA> NFATAble)
{
NFA fin=new NFA("The Big One");
State start=new State(false,new HashMap<String,State>());
State accept=new State(true,null);
for(NFA nfa : NFATable)
{
start.addTransition("Epsilon",nfa.getStart());
for(State st : nfa.getAccept())
{
st.addTransition("Epsilon",accept);
st.setAccept(false);
}
}
fin=fin.setStart(start);
fin=fin.setAccept(accept);
return fin;
}
| private NFA conversion(HashSet<NFA> NFATable)
{
NFA fin=new NFA("The Big One");
State start=new State(false,new HashMap<String,List<State>>());
State accept=new State(true,null);
for(NFA nfa : NFATable)
{
start.addTransition("Epsilon",nfa.getStart());
nfa.getAccept().addTransition("Epsilon",accept);
nfa.getAccept().setIsAccept(false);
}
fin.setStart(start);
fin.setAccept(accept);
return fin;
}
|
diff --git a/gui/src/java/com/robonobo/gui/sheets/WelcomeSheet.java b/gui/src/java/com/robonobo/gui/sheets/WelcomeSheet.java
index f45bb27..5ef8f04 100644
--- a/gui/src/java/com/robonobo/gui/sheets/WelcomeSheet.java
+++ b/gui/src/java/com/robonobo/gui/sheets/WelcomeSheet.java
@@ -1,124 +1,124 @@
package com.robonobo.gui.sheets;
import static com.robonobo.gui.GuiUtil.*;
import info.clearthought.layout.TableLayout;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.*;
import com.robonobo.common.concurrent.CatchingRunnable;
import com.robonobo.core.Platform;
import com.robonobo.gui.RoboFont;
import com.robonobo.gui.components.FileChoosePanel;
import com.robonobo.gui.components.base.*;
import com.robonobo.gui.frames.RobonoboFrame;
@SuppressWarnings("serial")
public class WelcomeSheet extends Sheet {
private RButton feckOffBtn;
private FileChoosePanel filePanel;
public WelcomeSheet(RobonoboFrame rFrame) {
super(rFrame);
- Dimension sz = new Dimension(540, 370);
+ Dimension sz = new Dimension(540, 375);
setPreferredSize(sz);
setSize(sz);
double[][] cells = { { 20, 270, 20, 220, 20 }, { 20, 40/* title */, 20, 20/*intro*/, 10, 40/* dir blurb */, 5, 25/* filechoose */, 20, TableLayout.FILL/* addstuff */, 20, 32/* feckoff */, 10 } };
setLayout(new TableLayout(cells));
setName("playback.background.panel");
JPanel titlePnl = new JPanel();
titlePnl.setLayout(new BoxLayout(titlePnl, BoxLayout.X_AXIS));
titlePnl.add(Box.createHorizontalStrut(72));
titlePnl.add(new RLabel36B("Welcome to"));
titlePnl.add(Box.createHorizontalStrut(10));
JLabel logo = new JLabel(createImageIcon("/rbnb-logo_mid-grey-bg.png", -1, 37));
logo.setBorder(BorderFactory.createEmptyBorder(0, 0, 8, 0));
titlePnl.add(logo);
add(titlePnl, "1,1,3,1,LEFT,TOP");
LineBreakTextPanel intro = new LineBreakTextPanel("Now you and your friends can hear each others' music effortlessly.", RoboFont.getFont(16, false), 560);
add(intro, "1,3,3,3,LEFT,TOP");
LineBreakTextPanel dirBlurb = new LineBreakTextPanel("All the music you play or download will be saved on your computer, in this folder:", RoboFont.getFont(16, false),
560);
add(dirBlurb, "1,5,3,5,LEFT,TOP");
filePanel = new FileChoosePanel(frame, frame.ctrl.getConfig().getFinishedDownloadsDirectory(), true, new CatchingRunnable() {
public void doRun() throws Exception {
File f = filePanel.chosenFile;
frame.ctrl.getConfig().setFinishedDownloadsDirectory(f.getAbsolutePath());
frame.ctrl.saveConfig();
}
});
add(filePanel, "1,7,3,7,LEFT,TOP");
JPanel addFriendsPnl = new JPanel();
- double[][] afCells = { {120, TableLayout.FILL}, {20, 10, 35, 10, 32} };
+ double[][] afCells = { {120, TableLayout.FILL}, {20, 10, 40, 10, 32} };
addFriendsPnl.setLayout(new TableLayout(afCells));
RLabel18B afTitle = new RLabel18B("Add friends");
addFriendsPnl.add(afTitle, "0,0,1,0");
LineBreakTextPanel afExpln = new LineBreakTextPanel("You can add friends from Facebook, or using their email addresses.", RoboFont.getFont(16, false), 270);
addFriendsPnl.add(afExpln,"0,2,1,2");
RButton addFriendsBtn = new RGlassButton("Add friends...");
addFriendsBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
frame.showAddFriendsSheet();
}
});
addFriendsPnl.add(addFriendsBtn,"0,4");
add(addFriendsPnl, "1,9");
JPanel shareTracksPnl = new JPanel();
shareTracksPnl.setLayout(new BoxLayout(shareTracksPnl, BoxLayout.Y_AXIS));
shareTracksPnl.add(new RLabel18B("Share tracks"));
shareTracksPnl.add(Box.createVerticalStrut(10));
RButton shareFilesBtn = new RGlassButton("Share MP3 files...");
shareFilesBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
frame.showAddSharesDialog();
}
});
shareTracksPnl.add(shareFilesBtn);
if (Platform.getPlatform().iTunesAvailable()) {
shareTracksPnl.add(Box.createVerticalStrut(10));
RButton shareITunesBtn = new RGlassButton("Share from iTunes...");
shareITunesBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
frame.shareFromITunes();
}
});
shareTracksPnl.add(shareITunesBtn);
}
add(shareTracksPnl, "3,9");
JPanel feckOffPnl = new JPanel();
feckOffPnl.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
feckOffPnl.setLayout(new BoxLayout(feckOffPnl, BoxLayout.PAGE_AXIS));
feckOffPnl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
feckOffBtn = new RRedGlassButton("Close");
feckOffBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
frame.guiCfg.setShowWelcomePanel(false);
frame.ctrl.getExecutor().execute(new CatchingRunnable() {
public void doRun() throws Exception {
frame.ctrl.saveConfig();
}
});
}
});
feckOffPnl.add(feckOffBtn);
add(feckOffPnl, "1,11,3,11,RIGHT,TOP");
}
@Override
public void onShow() {
}
@Override
public JButton defaultButton() {
return feckOffBtn;
}
}
| false | true | public WelcomeSheet(RobonoboFrame rFrame) {
super(rFrame);
Dimension sz = new Dimension(540, 370);
setPreferredSize(sz);
setSize(sz);
double[][] cells = { { 20, 270, 20, 220, 20 }, { 20, 40/* title */, 20, 20/*intro*/, 10, 40/* dir blurb */, 5, 25/* filechoose */, 20, TableLayout.FILL/* addstuff */, 20, 32/* feckoff */, 10 } };
setLayout(new TableLayout(cells));
setName("playback.background.panel");
JPanel titlePnl = new JPanel();
titlePnl.setLayout(new BoxLayout(titlePnl, BoxLayout.X_AXIS));
titlePnl.add(Box.createHorizontalStrut(72));
titlePnl.add(new RLabel36B("Welcome to"));
titlePnl.add(Box.createHorizontalStrut(10));
JLabel logo = new JLabel(createImageIcon("/rbnb-logo_mid-grey-bg.png", -1, 37));
logo.setBorder(BorderFactory.createEmptyBorder(0, 0, 8, 0));
titlePnl.add(logo);
add(titlePnl, "1,1,3,1,LEFT,TOP");
LineBreakTextPanel intro = new LineBreakTextPanel("Now you and your friends can hear each others' music effortlessly.", RoboFont.getFont(16, false), 560);
add(intro, "1,3,3,3,LEFT,TOP");
LineBreakTextPanel dirBlurb = new LineBreakTextPanel("All the music you play or download will be saved on your computer, in this folder:", RoboFont.getFont(16, false),
560);
add(dirBlurb, "1,5,3,5,LEFT,TOP");
filePanel = new FileChoosePanel(frame, frame.ctrl.getConfig().getFinishedDownloadsDirectory(), true, new CatchingRunnable() {
public void doRun() throws Exception {
File f = filePanel.chosenFile;
frame.ctrl.getConfig().setFinishedDownloadsDirectory(f.getAbsolutePath());
frame.ctrl.saveConfig();
}
});
add(filePanel, "1,7,3,7,LEFT,TOP");
JPanel addFriendsPnl = new JPanel();
double[][] afCells = { {120, TableLayout.FILL}, {20, 10, 35, 10, 32} };
addFriendsPnl.setLayout(new TableLayout(afCells));
RLabel18B afTitle = new RLabel18B("Add friends");
addFriendsPnl.add(afTitle, "0,0,1,0");
LineBreakTextPanel afExpln = new LineBreakTextPanel("You can add friends from Facebook, or using their email addresses.", RoboFont.getFont(16, false), 270);
addFriendsPnl.add(afExpln,"0,2,1,2");
RButton addFriendsBtn = new RGlassButton("Add friends...");
addFriendsBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
frame.showAddFriendsSheet();
}
});
addFriendsPnl.add(addFriendsBtn,"0,4");
add(addFriendsPnl, "1,9");
JPanel shareTracksPnl = new JPanel();
shareTracksPnl.setLayout(new BoxLayout(shareTracksPnl, BoxLayout.Y_AXIS));
shareTracksPnl.add(new RLabel18B("Share tracks"));
shareTracksPnl.add(Box.createVerticalStrut(10));
RButton shareFilesBtn = new RGlassButton("Share MP3 files...");
shareFilesBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
frame.showAddSharesDialog();
}
});
shareTracksPnl.add(shareFilesBtn);
if (Platform.getPlatform().iTunesAvailable()) {
shareTracksPnl.add(Box.createVerticalStrut(10));
RButton shareITunesBtn = new RGlassButton("Share from iTunes...");
shareITunesBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
frame.shareFromITunes();
}
});
shareTracksPnl.add(shareITunesBtn);
}
add(shareTracksPnl, "3,9");
JPanel feckOffPnl = new JPanel();
feckOffPnl.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
feckOffPnl.setLayout(new BoxLayout(feckOffPnl, BoxLayout.PAGE_AXIS));
feckOffPnl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
feckOffBtn = new RRedGlassButton("Close");
feckOffBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
frame.guiCfg.setShowWelcomePanel(false);
frame.ctrl.getExecutor().execute(new CatchingRunnable() {
public void doRun() throws Exception {
frame.ctrl.saveConfig();
}
});
}
});
feckOffPnl.add(feckOffBtn);
add(feckOffPnl, "1,11,3,11,RIGHT,TOP");
}
| public WelcomeSheet(RobonoboFrame rFrame) {
super(rFrame);
Dimension sz = new Dimension(540, 375);
setPreferredSize(sz);
setSize(sz);
double[][] cells = { { 20, 270, 20, 220, 20 }, { 20, 40/* title */, 20, 20/*intro*/, 10, 40/* dir blurb */, 5, 25/* filechoose */, 20, TableLayout.FILL/* addstuff */, 20, 32/* feckoff */, 10 } };
setLayout(new TableLayout(cells));
setName("playback.background.panel");
JPanel titlePnl = new JPanel();
titlePnl.setLayout(new BoxLayout(titlePnl, BoxLayout.X_AXIS));
titlePnl.add(Box.createHorizontalStrut(72));
titlePnl.add(new RLabel36B("Welcome to"));
titlePnl.add(Box.createHorizontalStrut(10));
JLabel logo = new JLabel(createImageIcon("/rbnb-logo_mid-grey-bg.png", -1, 37));
logo.setBorder(BorderFactory.createEmptyBorder(0, 0, 8, 0));
titlePnl.add(logo);
add(titlePnl, "1,1,3,1,LEFT,TOP");
LineBreakTextPanel intro = new LineBreakTextPanel("Now you and your friends can hear each others' music effortlessly.", RoboFont.getFont(16, false), 560);
add(intro, "1,3,3,3,LEFT,TOP");
LineBreakTextPanel dirBlurb = new LineBreakTextPanel("All the music you play or download will be saved on your computer, in this folder:", RoboFont.getFont(16, false),
560);
add(dirBlurb, "1,5,3,5,LEFT,TOP");
filePanel = new FileChoosePanel(frame, frame.ctrl.getConfig().getFinishedDownloadsDirectory(), true, new CatchingRunnable() {
public void doRun() throws Exception {
File f = filePanel.chosenFile;
frame.ctrl.getConfig().setFinishedDownloadsDirectory(f.getAbsolutePath());
frame.ctrl.saveConfig();
}
});
add(filePanel, "1,7,3,7,LEFT,TOP");
JPanel addFriendsPnl = new JPanel();
double[][] afCells = { {120, TableLayout.FILL}, {20, 10, 40, 10, 32} };
addFriendsPnl.setLayout(new TableLayout(afCells));
RLabel18B afTitle = new RLabel18B("Add friends");
addFriendsPnl.add(afTitle, "0,0,1,0");
LineBreakTextPanel afExpln = new LineBreakTextPanel("You can add friends from Facebook, or using their email addresses.", RoboFont.getFont(16, false), 270);
addFriendsPnl.add(afExpln,"0,2,1,2");
RButton addFriendsBtn = new RGlassButton("Add friends...");
addFriendsBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
frame.showAddFriendsSheet();
}
});
addFriendsPnl.add(addFriendsBtn,"0,4");
add(addFriendsPnl, "1,9");
JPanel shareTracksPnl = new JPanel();
shareTracksPnl.setLayout(new BoxLayout(shareTracksPnl, BoxLayout.Y_AXIS));
shareTracksPnl.add(new RLabel18B("Share tracks"));
shareTracksPnl.add(Box.createVerticalStrut(10));
RButton shareFilesBtn = new RGlassButton("Share MP3 files...");
shareFilesBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
frame.showAddSharesDialog();
}
});
shareTracksPnl.add(shareFilesBtn);
if (Platform.getPlatform().iTunesAvailable()) {
shareTracksPnl.add(Box.createVerticalStrut(10));
RButton shareITunesBtn = new RGlassButton("Share from iTunes...");
shareITunesBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
frame.shareFromITunes();
}
});
shareTracksPnl.add(shareITunesBtn);
}
add(shareTracksPnl, "3,9");
JPanel feckOffPnl = new JPanel();
feckOffPnl.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
feckOffPnl.setLayout(new BoxLayout(feckOffPnl, BoxLayout.PAGE_AXIS));
feckOffPnl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 10));
feckOffBtn = new RRedGlassButton("Close");
feckOffBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
frame.guiCfg.setShowWelcomePanel(false);
frame.ctrl.getExecutor().execute(new CatchingRunnable() {
public void doRun() throws Exception {
frame.ctrl.saveConfig();
}
});
}
});
feckOffPnl.add(feckOffBtn);
add(feckOffPnl, "1,11,3,11,RIGHT,TOP");
}
|
diff --git a/src/com/herocraftonline/dev/heroes/persistence/Hero.java b/src/com/herocraftonline/dev/heroes/persistence/Hero.java
index 5c124f47..2c473190 100644
--- a/src/com/herocraftonline/dev/heroes/persistence/Hero.java
+++ b/src/com/herocraftonline/dev/heroes/persistence/Hero.java
@@ -1,355 +1,355 @@
package com.herocraftonline.dev.heroes.persistence;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import com.herocraftonline.dev.heroes.Heroes;
import com.herocraftonline.dev.heroes.api.ExperienceGainEvent;
import com.herocraftonline.dev.heroes.api.LevelEvent;
import com.herocraftonline.dev.heroes.classes.HeroClass;
import com.herocraftonline.dev.heroes.classes.HeroClass.ExperienceType;
import com.herocraftonline.dev.heroes.effects.Effect;
import com.herocraftonline.dev.heroes.party.HeroParty;
import com.herocraftonline.dev.heroes.skill.Skill;
import com.herocraftonline.dev.heroes.util.Messaging;
import com.herocraftonline.dev.heroes.util.Properties;
public class Hero {
private static final DecimalFormat decFormat = new DecimalFormat("#0.##");
protected final Heroes plugin;
protected Player player;
protected HeroClass heroClass;
protected int mana = 0;
protected HeroParty party = null;
protected boolean verbose = true;
protected Set<Effect> effects = new HashSet<Effect>();
protected Map<String, Double> experience = new HashMap<String, Double>();
protected Map<String, Long> cooldowns = new HashMap<String, Long>();
protected Map<Entity, CreatureType> summons = new HashMap<Entity, CreatureType>();
protected Map<Material, String[]> binds = new HashMap<Material, String[]>();
protected List<ItemStack> itemRecovery = new ArrayList<ItemStack>();
protected Set<String> suppressedSkills = new HashSet<String>();
protected double health;
public Hero(Heroes plugin, Player player, HeroClass heroClass) {
this.plugin = plugin;
this.player = player;
this.heroClass = heroClass;
}
public void syncHealth() {
getPlayer().setHealth((int) (health / getMaxHealth() * 20));
}
public void addEffect(Effect effect) {
effects.add(effect);
effect.apply(this);
}
public void addRecoveryItem(ItemStack item) {
this.itemRecovery.add(item);
}
public void bind(Material material, String[] skillName) {
binds.put(material, skillName);
}
public void changeHeroClass(HeroClass heroClass) {
setHeroClass(heroClass);
binds.clear();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Hero other = (Hero) obj;
if (player == null) {
if (other.player != null)
return false;
} else if (!player.getName().equals(other.player.getName()))
return false;
return true;
}
public void gainExp(double expGain, ExperienceType source) {
gainExp(expGain, source, true);
}
public void gainExp(double expGain, ExperienceType source, boolean distributeToParty) {
Properties prop = plugin.getConfigManager().getProperties();
if (distributeToParty && party != null && party.getExp()) {
Location location = getPlayer().getLocation();
Set<Hero> partyMembers = party.getMembers();
Set<Hero> inRangeMembers = new HashSet<Hero>();
for (Hero partyMember : partyMembers) {
if (location.distance(partyMember.getPlayer().getLocation()) <= 50) {
inRangeMembers.add(partyMember);
}
}
int partySize = inRangeMembers.size();
double sharedExpGain = expGain / partySize * ((partySize - 1) * prop.partyBonus + 1.0);
for (Hero partyMember : inRangeMembers) {
partyMember.gainExp(sharedExpGain, source, false);
}
return;
}
double exp = getExperience();
// adjust exp using the class modifier
expGain *= heroClass.getExpModifier();
int currentLevel = prop.getLevel(exp);
int newLevel = prop.getLevel(exp + expGain);
if (currentLevel >= prop.maxLevel) {
expGain = 0;
}
// add the experience
exp += expGain;
// call event
ExperienceGainEvent expEvent;
if (newLevel == currentLevel) {
expEvent = new ExperienceGainEvent(this, expGain, source);
} else {
expEvent = new LevelEvent(this, expGain, currentLevel, newLevel, source);
}
plugin.getServer().getPluginManager().callEvent(expEvent);
if (expEvent.isCancelled()) {
// undo the experience gain
exp -= expGain;
return;
}
// undo the previous gain to make sure we use the updated value
exp -= expGain;
expGain = expEvent.getExpGain();
// add the updated experience
exp += expGain;
// notify the user
if (expGain != 0) {
if (verbose) {
Messaging.send(player, "$1: Gained $2 Exp", heroClass.getName(), decFormat.format(expGain));
}
if (newLevel != currentLevel) {
- player.setHealth(20);
- // setHealth(getMaxHealth());
+ setHealth(getMaxHealth());
+ syncHealth();
Messaging.send(player, "You leveled up! (Lvl $1 $2)", String.valueOf(newLevel), heroClass.getName());
if (newLevel >= prop.maxLevel) {
exp = prop.getExperience(prop.maxLevel);
Messaging.broadcast(plugin, "$1 has become a master $2!", player.getName(), heroClass.getName());
plugin.getHeroManager().saveHero(player);
}
}
}
setExperience(exp);
}
public Map<Material, String[]> getBinds() {
return binds;
}
public Map<String, Long> getCooldowns() {
return cooldowns;
}
public Effect getEffect(String name) {
for (Effect effect : effects) {
if (effect.getName().equalsIgnoreCase(name))
return effect;
}
return null;
}
public Set<Effect> getEffects() {
return new HashSet<Effect>(effects);
}
public double getExperience() {
return getExperience(heroClass);
}
public double getExperience(HeroClass heroClass) {
Double exp = experience.get(heroClass.getName());
return exp == null ? 0 : exp;
}
public HeroClass getHeroClass() {
return heroClass;
}
public int getLevel() {
return plugin.getConfigManager().getProperties().getLevel(getExperience());
}
public double getHealth() {
return health;
}
public double getMaxHealth() {
int level = plugin.getConfigManager().getProperties().getLevel(getExperience());
return heroClass.getBaseMaxHealth() + (level - 1) * heroClass.getMaxHealthPerLevel();
}
public int getMana() {
return mana;
}
public HeroParty getParty() {
return party;
}
public Player getPlayer() {
Player servPlayer = plugin.getServer().getPlayer(player.getName());
if (servPlayer != null && player != servPlayer) {
player = servPlayer;
}
return player;
}
public List<ItemStack> getRecoveryItems() {
return this.itemRecovery;
}
public Map<Entity, CreatureType> getSummons() {
return summons;
}
public Set<String> getSuppressedSkills() {
return new HashSet<String>(suppressedSkills);
}
public boolean hasEffect(String name) {
for (Effect effect : effects) {
if (effect.getName().equalsIgnoreCase(name))
return true;
}
return false;
}
@Override
public int hashCode() {
return player == null ? 0 : player.getName().hashCode();
}
public boolean hasParty() {
return party != null;
}
public boolean isMaster() {
return isMaster(heroClass);
}
public boolean isMaster(HeroClass heroClass) {
int maxExp = plugin.getConfigManager().getProperties().maxExp;
return getExperience(heroClass) >= maxExp || getExperience(heroClass) - maxExp > 0;
}
public boolean isSuppressing(Skill skill) {
return suppressedSkills.contains(skill.getName());
}
public boolean isVerbose() {
return verbose;
}
public void removeEffect(Effect effect) {
effects.remove(effect);
if (effect != null) {
effect.remove(this);
}
}
public void setExperience(double experience) {
setExperience(heroClass, experience);
}
public void setExperience(HeroClass heroClass, double experience) {
this.experience.put(heroClass.getName(), experience);
}
public void setHeroClass(HeroClass heroClass) {
double currentMaxHP = getMaxHealth();
this.heroClass = heroClass;
double newMaxHP = getMaxHealth();
health *= newMaxHP / currentMaxHP;
if (health > newMaxHP) {
health = newMaxHP;
}
// Check the Players inventory now that they have changed class.
this.plugin.getInventoryChecker().checkInventory(getPlayer());
}
public void setMana(int mana) {
if (mana > 100) {
mana = 100;
} else if (mana < 0) {
mana = 0;
}
this.mana = mana;
}
public void setParty(HeroParty party) {
this.party = party;
}
public void setRecoveryItems(List<ItemStack> items) {
this.itemRecovery = items;
}
public void setSuppressed(Skill skill, boolean suppressed) {
if (suppressed) {
suppressedSkills.add(skill.getName());
} else {
suppressedSkills.remove(skill.getName());
}
}
public void setVerbose(boolean verbose) {
this.verbose = verbose;
}
public void unbind(Material material) {
binds.remove(material);
}
public void setHealth(Double health) {
double maxHealth = getMaxHealth();
if (health > maxHealth) {
this.health = maxHealth;
} else if (health < 0) {
this.health = 0;
} else {
this.health = health;
}
}
}
| true | true | public void gainExp(double expGain, ExperienceType source, boolean distributeToParty) {
Properties prop = plugin.getConfigManager().getProperties();
if (distributeToParty && party != null && party.getExp()) {
Location location = getPlayer().getLocation();
Set<Hero> partyMembers = party.getMembers();
Set<Hero> inRangeMembers = new HashSet<Hero>();
for (Hero partyMember : partyMembers) {
if (location.distance(partyMember.getPlayer().getLocation()) <= 50) {
inRangeMembers.add(partyMember);
}
}
int partySize = inRangeMembers.size();
double sharedExpGain = expGain / partySize * ((partySize - 1) * prop.partyBonus + 1.0);
for (Hero partyMember : inRangeMembers) {
partyMember.gainExp(sharedExpGain, source, false);
}
return;
}
double exp = getExperience();
// adjust exp using the class modifier
expGain *= heroClass.getExpModifier();
int currentLevel = prop.getLevel(exp);
int newLevel = prop.getLevel(exp + expGain);
if (currentLevel >= prop.maxLevel) {
expGain = 0;
}
// add the experience
exp += expGain;
// call event
ExperienceGainEvent expEvent;
if (newLevel == currentLevel) {
expEvent = new ExperienceGainEvent(this, expGain, source);
} else {
expEvent = new LevelEvent(this, expGain, currentLevel, newLevel, source);
}
plugin.getServer().getPluginManager().callEvent(expEvent);
if (expEvent.isCancelled()) {
// undo the experience gain
exp -= expGain;
return;
}
// undo the previous gain to make sure we use the updated value
exp -= expGain;
expGain = expEvent.getExpGain();
// add the updated experience
exp += expGain;
// notify the user
if (expGain != 0) {
if (verbose) {
Messaging.send(player, "$1: Gained $2 Exp", heroClass.getName(), decFormat.format(expGain));
}
if (newLevel != currentLevel) {
player.setHealth(20);
// setHealth(getMaxHealth());
Messaging.send(player, "You leveled up! (Lvl $1 $2)", String.valueOf(newLevel), heroClass.getName());
if (newLevel >= prop.maxLevel) {
exp = prop.getExperience(prop.maxLevel);
Messaging.broadcast(plugin, "$1 has become a master $2!", player.getName(), heroClass.getName());
plugin.getHeroManager().saveHero(player);
}
}
}
setExperience(exp);
}
| public void gainExp(double expGain, ExperienceType source, boolean distributeToParty) {
Properties prop = plugin.getConfigManager().getProperties();
if (distributeToParty && party != null && party.getExp()) {
Location location = getPlayer().getLocation();
Set<Hero> partyMembers = party.getMembers();
Set<Hero> inRangeMembers = new HashSet<Hero>();
for (Hero partyMember : partyMembers) {
if (location.distance(partyMember.getPlayer().getLocation()) <= 50) {
inRangeMembers.add(partyMember);
}
}
int partySize = inRangeMembers.size();
double sharedExpGain = expGain / partySize * ((partySize - 1) * prop.partyBonus + 1.0);
for (Hero partyMember : inRangeMembers) {
partyMember.gainExp(sharedExpGain, source, false);
}
return;
}
double exp = getExperience();
// adjust exp using the class modifier
expGain *= heroClass.getExpModifier();
int currentLevel = prop.getLevel(exp);
int newLevel = prop.getLevel(exp + expGain);
if (currentLevel >= prop.maxLevel) {
expGain = 0;
}
// add the experience
exp += expGain;
// call event
ExperienceGainEvent expEvent;
if (newLevel == currentLevel) {
expEvent = new ExperienceGainEvent(this, expGain, source);
} else {
expEvent = new LevelEvent(this, expGain, currentLevel, newLevel, source);
}
plugin.getServer().getPluginManager().callEvent(expEvent);
if (expEvent.isCancelled()) {
// undo the experience gain
exp -= expGain;
return;
}
// undo the previous gain to make sure we use the updated value
exp -= expGain;
expGain = expEvent.getExpGain();
// add the updated experience
exp += expGain;
// notify the user
if (expGain != 0) {
if (verbose) {
Messaging.send(player, "$1: Gained $2 Exp", heroClass.getName(), decFormat.format(expGain));
}
if (newLevel != currentLevel) {
setHealth(getMaxHealth());
syncHealth();
Messaging.send(player, "You leveled up! (Lvl $1 $2)", String.valueOf(newLevel), heroClass.getName());
if (newLevel >= prop.maxLevel) {
exp = prop.getExperience(prop.maxLevel);
Messaging.broadcast(plugin, "$1 has become a master $2!", player.getName(), heroClass.getName());
plugin.getHeroManager().saveHero(player);
}
}
}
setExperience(exp);
}
|
diff --git a/src/gui/FragmentDisplay.java b/src/gui/FragmentDisplay.java
index 4fb1780..a1ecbe6 100755
--- a/src/gui/FragmentDisplay.java
+++ b/src/gui/FragmentDisplay.java
@@ -1,141 +1,141 @@
package gui;
import assembly.Fragment;
import assembly.FragmentPositionSource;
import generator.Fragmentizer;
import java.util.List;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.*;
import javax.swing.*;
public class FragmentDisplay
{
static
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (UnsupportedLookAndFeelException e)
{
e.printStackTrace();
}
}
JFrame frame;
Image image;
public FragmentDisplay(Image image_)
{
image = image_;
frame = new JFrame("Fragment Display");
// frame.setBounds(25, 25, 320, 320);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("Adding new ImagePanel");
frame.getContentPane().setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridheight = 1;
constraints.gridwidth = 1;
constraints.ipadx = constraints.ipady = 2;
frame.getContentPane().add(new ImagePanel(image_), constraints);
constraints.gridy = 1;
frame.getContentPane().add(new ImagePanel(image_), constraints);
constraints = new GridBagConstraints();
constraints.ipadx = constraints.ipady = 2;
constraints.gridheight = 2;
constraints.gridx = 1;
frame.getContentPane().add(new ImagePanel(image_), constraints);
// frame.getContentPane().add(new JLabel("Test"));
frame.pack();
frame.setVisible(true);
}
public static Image getFragmentGroupImage(String origSequence, List<List<Fragment>> fragmentGroups,
FragmentPositionSource source)
{
BufferedImage image = new BufferedImage(origSequence.length(), fragmentGroups.size() * 2 + 1,
BufferedImage.TYPE_INT_ARGB);
System.out.printf("Image height: %d%n", image.getHeight());
System.out.printf("Image width: %d%n", image.getWidth());
Graphics2D g2d = image.createGraphics();
Color red = new Color(255, 0, 0, 255);
g2d.setColor(red);
g2d.fill(new Rectangle2D.Float(0, 0, origSequence.length(), 1));
g2d.dispose();
int i = 0;
for (List<Fragment> list : fragmentGroups)
{
for (Fragment fragment : list)
{
g2d = image.createGraphics();
// Make all filled pixels transparent
Color black = new Color(0, 0, 0, 255);
g2d.setColor(black);
// g2d.setComposite(AlphaComposite.Src);
g2d.fill(new Rectangle2D.Float(fragment.getPosition(source), (i + 1) * 2, fragment.string.length(), 1));
g2d.dispose();
}
i++;
}
return image;
}
/**
* XXX: Temporary
*
* @param args
*/
public static void main(String[] args)
{
if (args.length < 4)
{
- System.err.printf("*** Usage: %s string n k kTolerance", Fragmentizer.class.getCanonicalName());
+ System.err.printf("*** Usage: %s string n k kTolerance", FragmentDisplay.class.getCanonicalName());
System.exit(1);
}
String string = args[0];
int n = Integer.parseInt(args[1]);
int k = Integer.parseInt(args[2]);
int kTolerance = Integer.parseInt(args[3]);
FragmentPositionSource source = FragmentPositionSource.ORIGINAL_SEQUENCE;
List<Fragment> fragments = Fragmentizer.fragmentizeForShotgun(string, n, k, kTolerance);
for (Fragment fragment : fragments)
{
System.out.printf("%5d: %s%n", fragment.getPosition(source), fragment.string);
}
System.out.println();
System.out.println(string);
List<List<Fragment>> grouped = Fragmentizer.groupByLine(fragments, source);
for (List<Fragment> list : grouped)
{
int begin = 0;
for (Fragment fragment : list)
{
for (int i = 0; i < fragment.getPosition(source) - begin; i++)
{
System.out.print(" ");
}
System.out.print(fragment.string);
begin = fragment.getPosition(source) + fragment.string.length();
}
System.out.println();
}
FragmentDisplay display = new FragmentDisplay(getFragmentGroupImage(string, grouped,
FragmentPositionSource.ORIGINAL_SEQUENCE));
}
}
| true | true | public static void main(String[] args)
{
if (args.length < 4)
{
System.err.printf("*** Usage: %s string n k kTolerance", Fragmentizer.class.getCanonicalName());
System.exit(1);
}
String string = args[0];
int n = Integer.parseInt(args[1]);
int k = Integer.parseInt(args[2]);
int kTolerance = Integer.parseInt(args[3]);
FragmentPositionSource source = FragmentPositionSource.ORIGINAL_SEQUENCE;
List<Fragment> fragments = Fragmentizer.fragmentizeForShotgun(string, n, k, kTolerance);
for (Fragment fragment : fragments)
{
System.out.printf("%5d: %s%n", fragment.getPosition(source), fragment.string);
}
System.out.println();
System.out.println(string);
List<List<Fragment>> grouped = Fragmentizer.groupByLine(fragments, source);
for (List<Fragment> list : grouped)
{
int begin = 0;
for (Fragment fragment : list)
{
for (int i = 0; i < fragment.getPosition(source) - begin; i++)
{
System.out.print(" ");
}
System.out.print(fragment.string);
begin = fragment.getPosition(source) + fragment.string.length();
}
System.out.println();
}
FragmentDisplay display = new FragmentDisplay(getFragmentGroupImage(string, grouped,
FragmentPositionSource.ORIGINAL_SEQUENCE));
}
| public static void main(String[] args)
{
if (args.length < 4)
{
System.err.printf("*** Usage: %s string n k kTolerance", FragmentDisplay.class.getCanonicalName());
System.exit(1);
}
String string = args[0];
int n = Integer.parseInt(args[1]);
int k = Integer.parseInt(args[2]);
int kTolerance = Integer.parseInt(args[3]);
FragmentPositionSource source = FragmentPositionSource.ORIGINAL_SEQUENCE;
List<Fragment> fragments = Fragmentizer.fragmentizeForShotgun(string, n, k, kTolerance);
for (Fragment fragment : fragments)
{
System.out.printf("%5d: %s%n", fragment.getPosition(source), fragment.string);
}
System.out.println();
System.out.println(string);
List<List<Fragment>> grouped = Fragmentizer.groupByLine(fragments, source);
for (List<Fragment> list : grouped)
{
int begin = 0;
for (Fragment fragment : list)
{
for (int i = 0; i < fragment.getPosition(source) - begin; i++)
{
System.out.print(" ");
}
System.out.print(fragment.string);
begin = fragment.getPosition(source) + fragment.string.length();
}
System.out.println();
}
FragmentDisplay display = new FragmentDisplay(getFragmentGroupImage(string, grouped,
FragmentPositionSource.ORIGINAL_SEQUENCE));
}
|
diff --git a/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/connect/PacketSendManager.java b/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/connect/PacketSendManager.java
index af9528a9e..cb73490cd 100644
--- a/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/connect/PacketSendManager.java
+++ b/org.eclipse.jdt.debug/jdi/org/eclipse/jdi/internal/connect/PacketSendManager.java
@@ -1,98 +1,103 @@
package org.eclipse.jdi.internal.connect;
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. All rights reserved.
This file is 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
**********************************************************************/
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.LinkedList;
import org.eclipse.jdi.internal.jdwp.JdwpPacket;
import com.sun.jdi.VMDisconnectedException;
/**
* This class implements a thread that sends available packets to the Virtual Machine.
*
*/
public class PacketSendManager extends PacketManager {
/** Output Stream to Virtual Machine. */
private OutputStream fOutStream;
/** List of packets to be sent to Virtual Machine */
private LinkedList fOutgoingPackets;
/**
* Create a new thread that send packets to the Virtual Machine.
*/
public PacketSendManager(ConnectorImpl connector) {
super(connector);
try {
fOutStream = connector.getOutputStream();
fOutgoingPackets = new LinkedList();
} catch (IOException e) {
disconnectVM(e);
}
}
/**
* Thread's run method.
*/
public void run() {
while (!VMIsDisconnected()) {
try {
sendAvailablePackets();
} catch (InterruptedException e) {
} catch (InterruptedIOException e) {
} catch (IOException e) {
disconnectVM(e);
}
}
}
/**
* Add a packet to be sent to the Virtual Machine.
*/
public synchronized void sendPacket(JdwpPacket packet) {
if (VMIsDisconnected()) {
String message;
if (getDisconnectException() == null) {
message= ConnectMessages.getString("PacketSendManager.Got_IOException_from_Virtual_Machine_1"); //$NON-NLS-1$
} else {
- message= MessageFormat.format(ConnectMessages.getString("PacketSendManager.Got_{0}_from_Virtual_Machine_1"), new String[] {getDisconnectException().getClass().getName()}); //$NON-NLS-1$
+ String exMessage = getDisconnectException().getMessage();
+ if (exMessage == null) {
+ message= MessageFormat.format(ConnectMessages.getString("PacketSendManager.Got_{0}_from_Virtual_Machine_1"), new String[] {getDisconnectException().getClass().getName()}); //$NON-NLS-1$
+ } else {
+ message= MessageFormat.format(ConnectMessages.getString("PacketSendManager.Got_{0}_from_Virtual_Machine__{1}_1"), new String[] {getDisconnectException().getClass().getName(), exMessage}); //$NON-NLS-1$
+ }
}
throw new VMDisconnectedException(message);
}
// Add packet to list of packets to send.
fOutgoingPackets.add(packet);
// Notify PacketSendThread that data is available.
notifyAll();
}
/**
* Send available packets to the Virtual Machine.
*/
private synchronized void sendAvailablePackets() throws InterruptedException, IOException {
while (fOutgoingPackets.size() == 0)
wait();
// Put available packets on Output Stream.
while (fOutgoingPackets.size() > 0) {
// Note that only JdwpPackets are added to the list, so a ClassCastException can't occur.
JdwpPacket packet = (JdwpPacket)fOutgoingPackets.removeFirst();
// Buffer the output until a complete packet is available.
BufferedOutputStream bufferOutStream = new BufferedOutputStream(fOutStream, packet.getLength());
packet.write(bufferOutStream);
bufferOutStream.flush();
}
}
}
| true | true | public synchronized void sendPacket(JdwpPacket packet) {
if (VMIsDisconnected()) {
String message;
if (getDisconnectException() == null) {
message= ConnectMessages.getString("PacketSendManager.Got_IOException_from_Virtual_Machine_1"); //$NON-NLS-1$
} else {
message= MessageFormat.format(ConnectMessages.getString("PacketSendManager.Got_{0}_from_Virtual_Machine_1"), new String[] {getDisconnectException().getClass().getName()}); //$NON-NLS-1$
}
throw new VMDisconnectedException(message);
}
// Add packet to list of packets to send.
fOutgoingPackets.add(packet);
// Notify PacketSendThread that data is available.
notifyAll();
}
| public synchronized void sendPacket(JdwpPacket packet) {
if (VMIsDisconnected()) {
String message;
if (getDisconnectException() == null) {
message= ConnectMessages.getString("PacketSendManager.Got_IOException_from_Virtual_Machine_1"); //$NON-NLS-1$
} else {
String exMessage = getDisconnectException().getMessage();
if (exMessage == null) {
message= MessageFormat.format(ConnectMessages.getString("PacketSendManager.Got_{0}_from_Virtual_Machine_1"), new String[] {getDisconnectException().getClass().getName()}); //$NON-NLS-1$
} else {
message= MessageFormat.format(ConnectMessages.getString("PacketSendManager.Got_{0}_from_Virtual_Machine__{1}_1"), new String[] {getDisconnectException().getClass().getName(), exMessage}); //$NON-NLS-1$
}
}
throw new VMDisconnectedException(message);
}
// Add packet to list of packets to send.
fOutgoingPackets.add(packet);
// Notify PacketSendThread that data is available.
notifyAll();
}
|
diff --git a/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java b/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java
index 7e709a93b..0e3667798 100644
--- a/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java
+++ b/src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java
@@ -1,897 +1,897 @@
/*
* Copyright 1999-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id$ */
package org.apache.fop.layoutmgr.inline;
import java.util.ArrayList;
import java.util.List;
import java.util.LinkedList;
import java.util.ListIterator;
import org.apache.fop.fo.FOText;
import org.apache.fop.fo.flow.Inline;
import org.apache.fop.fonts.Font;
import org.apache.fop.layoutmgr.KnuthSequence;
import org.apache.fop.layoutmgr.KnuthBox;
import org.apache.fop.layoutmgr.KnuthElement;
import org.apache.fop.layoutmgr.KnuthGlue;
import org.apache.fop.layoutmgr.KnuthPenalty;
import org.apache.fop.layoutmgr.LayoutContext;
import org.apache.fop.layoutmgr.LeafPosition;
import org.apache.fop.layoutmgr.Position;
import org.apache.fop.layoutmgr.PositionIterator;
import org.apache.fop.layoutmgr.TraitSetter;
import org.apache.fop.traits.SpaceVal;
import org.apache.fop.area.Trait;
import org.apache.fop.area.inline.InlineArea;
import org.apache.fop.area.inline.TextArea;
import org.apache.fop.traits.MinOptMax;
/**
* LayoutManager for text (a sequence of characters) which generates one
* or more inline areas.
*/
public class TextLayoutManager extends LeafNodeLayoutManager {
/**
* Store information about each potential text area.
* Index of character which ends the area, IPD of area, including
* any word-space and letter-space.
* Number of word-spaces?
*/
private class AreaInfo {
private short iStartIndex;
private short iBreakIndex;
private short iWScount;
private short iLScount;
private MinOptMax ipdArea;
private boolean bHyphenated;
public AreaInfo(short iSIndex, short iBIndex, short iWS, short iLS,
MinOptMax ipd, boolean bHyph) {
iStartIndex = iSIndex;
iBreakIndex = iBIndex;
iWScount = iWS;
iLScount = iLS;
ipdArea = ipd;
bHyphenated = bHyph;
}
}
// this class stores information about changes in vecAreaInfo
// which are not yet applied
private class PendingChange {
public AreaInfo ai;
public int index;
public PendingChange(AreaInfo ai, int index) {
this.ai = ai;
this.index = index;
}
}
// Hold all possible breaks for the text in this LM's FO.
private ArrayList vecAreaInfo;
/** Non-space characters on which we can end a line. */
private static final String BREAK_CHARS = "-/" ;
private FOText foText;
private char[] textArray;
private static final char NEWLINE = '\n';
private static final char SPACE = '\u0020'; // Normal space
private static final char NBSPACE = '\u00A0'; // Non-breaking space
private static final char LINEBREAK = '\u2028';
private static final char ZERO_WIDTH_SPACE = '\u200B';
// byte order mark
private static final char ZERO_WIDTH_NOBREAK_SPACE = '\uFEFF';
/** Start index of first character in this parent Area */
private short iAreaStart = 0;
/** Start index of next TextArea */
private short iNextStart = 0;
/** Size since last makeArea call, except for last break */
private MinOptMax ipdTotal;
/** Size including last break possibility returned */
// private MinOptMax nextIPD = new MinOptMax(0);
/** size of a space character (U+0020) glyph in current font */
private int spaceCharIPD;
private MinOptMax wordSpaceIPD;
private MinOptMax letterSpaceIPD;
/** size of the hyphen character glyph in current font */
private int hyphIPD;
/** 1/2 of word-spacing value */
private SpaceVal halfWS;
/** Number of space characters after previous possible break position. */
private int iNbSpacesPending;
private Font fs;
private boolean bChanged = false;
private int iReturnedIndex = 0;
private short iThisStart = 0;
private short iTempStart = 0;
private LinkedList changeList = null;
private int textHeight;
private int lead = 0;
private int total = 0;
private int middle = 0;
private int verticalAlignment = EN_BASELINE;
/**
* Create a Text layout manager.
*
* @param node The FOText object to be rendered
*/
public TextLayoutManager(FOText node) {
super();
foText = node;
textArray = new char[node.endIndex - node.startIndex];
System.arraycopy(node.ca, node.startIndex, textArray, 0,
node.endIndex - node.startIndex);
vecAreaInfo = new java.util.ArrayList();
}
public void initialize() {
fs = foText.getCommonFont().getFontState(foText.getFOEventHandler().getFontInfo(), this);
// With CID fonts, space isn't neccesary currentFontState.width(32)
spaceCharIPD = fs.getCharWidth(' ');
// Use hyphenationChar property
hyphIPD = fs.getCharWidth(foText.getCommonHyphenation().hyphenationCharacter);
// Make half-space: <space> on either side of a word-space)
SpaceVal ls = SpaceVal.makeLetterSpacing(foText.getLetterSpacing());
SpaceVal ws = SpaceVal.makeWordSpacing(foText.getWordSpacing(), ls, fs);
halfWS = new SpaceVal(MinOptMax.multiply(ws.getSpace(), 0.5),
ws.isConditional(), ws.isForcing(), ws.getPrecedence());
// letter space applies only to consecutive non-space characters,
// while word space applies to space characters;
// i.e. the spaces in the string "A SIMPLE TEST" are:
// A<<ws>>S<ls>I<ls>M<ls>P<ls>L<ls>E<<ws>>T<ls>E<ls>S<ls>T
// there is no letter space after the last character of a word,
// nor after a space character
// set letter space and word space dimension;
// the default value "normal" was converted into a MinOptMax value
// in the SpaceVal.makeWordSpacing() method
letterSpaceIPD = ls.getSpace();
wordSpaceIPD = MinOptMax.add(new MinOptMax(spaceCharIPD), ws.getSpace());
// set text height
textHeight = fs.getAscender()
- fs.getDescender();
// if the text node is son of an inline, set vertical align
if (foText.getParent() instanceof Inline) {
setAlignment(((Inline) foText.getParent()).getVerticalAlign());
}
switch (verticalAlignment) {
case EN_MIDDLE : middle = textHeight / 2 ;
break;
case EN_TOP : // fall through
case EN_BOTTOM : total = textHeight;
break;
case EN_BASELINE: // fall through
default : lead = fs.getAscender();
total = textHeight;
break;
}
}
/**
* Reset position for returning next BreakPossibility.
*
* @param prevPos the position to reset to
*/
public void resetPosition(Position prevPos) {
if (prevPos != null) {
// ASSERT (prevPos.getLM() == this)
if (prevPos.getLM() != this) {
log.error("TextLayoutManager.resetPosition: "
+ "LM mismatch!!!");
}
LeafPosition tbp = (LeafPosition) prevPos;
AreaInfo ai =
(AreaInfo) vecAreaInfo.get(tbp.getLeafPos());
if (ai.iBreakIndex != iNextStart) {
iNextStart = ai.iBreakIndex;
vecAreaInfo.ensureCapacity(tbp.getLeafPos() + 1);
// TODO: reset or recalculate total IPD = sum of all word IPD
// up to the break position
ipdTotal = ai.ipdArea;
setFinished(false);
}
} else {
// Reset to beginning!
vecAreaInfo.clear();
iNextStart = 0;
setFinished(false);
}
}
// TODO: see if we can use normal getNextBreakPoss for this with
// extra hyphenation information in LayoutContext
private boolean getHyphenIPD(HyphContext hc, MinOptMax hyphIPD) {
// Skip leading word-space before calculating count?
boolean bCanHyphenate = true;
int iStopIndex = iNextStart + hc.getNextHyphPoint();
if (textArray.length < iStopIndex) {
iStopIndex = textArray.length;
bCanHyphenate = false;
}
hc.updateOffset(iStopIndex - iNextStart);
for (; iNextStart < iStopIndex; iNextStart++) {
char c = textArray[iNextStart];
hyphIPD.opt += fs.getCharWidth(c);
// letter-space?
}
// Need to include hyphen size too, but don't count it in the
// stored running total, since it would be double counted
// with later hyphenation points
return bCanHyphenate;
}
/**
* Generate and add areas to parent area.
* This can either generate an area for each TextArea and each space, or
* an area containing all text with a parameter controlling the size of
* the word space. The latter is most efficient for PDF generation.
* Set size of each area.
* @param posIter Iterator over Position information returned
* by this LayoutManager.
* @param context LayoutContext for adjustments
*/
public void addAreas(PositionIterator posIter, LayoutContext context) {
// Add word areas
AreaInfo ai = null;
int iStart = -1;
int iWScount = 0;
int iLScount = 0;
MinOptMax realWidth = new MinOptMax(0);
/* On first area created, add any leading space.
* Calculate word-space stretch value.
*/
while (posIter.hasNext()) {
LeafPosition tbpNext = (LeafPosition) posIter.next();
//
if (tbpNext.getLeafPos() != -1) {
ai = (AreaInfo) vecAreaInfo.get(tbpNext.getLeafPos());
if (iStart == -1) {
iStart = ai.iStartIndex;
}
iWScount += ai.iWScount;
iLScount += ai.iLScount;
realWidth.add(ai.ipdArea);
}
}
if (ai == null) {
return;
}
// Make an area containing all characters between start and end.
InlineArea word = null;
int adjust = 0;
// ignore newline character
if (textArray[ai.iBreakIndex - 1] == NEWLINE) {
adjust = 1;
}
String str = new String(textArray, iStart,
ai.iBreakIndex - iStart - adjust);
// add hyphenation character if the last word is hyphenated
if (context.isLastArea() && ai.bHyphenated) {
str += foText.getCommonHyphenation().hyphenationCharacter;
realWidth.add(new MinOptMax(hyphIPD));
}
// Calculate adjustments
int iDifference = 0;
int iTotalAdjust = 0;
int iWordSpaceDim = wordSpaceIPD.opt;
int iLetterSpaceDim = letterSpaceIPD.opt;
double dIPDAdjust = context.getIPDAdjust();
double dSpaceAdjust = context.getSpaceAdjust(); // not used
// calculate total difference between real and available width
if (dIPDAdjust > 0.0) {
iDifference = (int) ((double) (realWidth.max - realWidth.opt)
* dIPDAdjust);
} else {
iDifference = (int) ((double) (realWidth.opt - realWidth.min)
* dIPDAdjust);
}
// set letter space adjustment
if (dIPDAdjust > 0.0) {
iLetterSpaceDim
+= (int) ((double) (letterSpaceIPD.max - letterSpaceIPD.opt)
* dIPDAdjust);
} else {
iLetterSpaceDim
+= (int) ((double) (letterSpaceIPD.opt - letterSpaceIPD.min)
* dIPDAdjust);
}
iTotalAdjust += (iLetterSpaceDim - letterSpaceIPD.opt) * iLScount;
// set word space adjustment
//
if (iWScount > 0) {
iWordSpaceDim += (int) ((iDifference - iTotalAdjust) / iWScount);
} else {
// there are no word spaces in this area
}
iTotalAdjust += (iWordSpaceDim - wordSpaceIPD.opt) * iWScount;
TextArea t = createTextArea(str, realWidth, iTotalAdjust, context,
wordSpaceIPD.opt - spaceCharIPD);
// iWordSpaceDim is computed in relation to wordSpaceIPD.opt
// but the renderer needs to know the adjustment in relation
// to the size of the space character in the current font;
// moreover, the pdf renderer adds the character spacing even to
// the last character of a word and to space characters: in order
// to avoid this, we must subtract the letter space width twice;
// the renderer will compute the space width as:
// space width =
// = "normal" space width + letterSpaceAdjust + wordSpaceAdjust
// = spaceCharIPD + letterSpaceAdjust +
// + (iWordSpaceDim - spaceCharIPD - 2 * letterSpaceAdjust)
// = iWordSpaceDim - letterSpaceAdjust
t.setTextLetterSpaceAdjust(iLetterSpaceDim);
t.setTextWordSpaceAdjust(iWordSpaceDim - spaceCharIPD
- 2 * t.getTextLetterSpaceAdjust());
if (context.getIPDAdjust() != 0) {
// add information about space width
t.setSpaceDifference(wordSpaceIPD.opt - spaceCharIPD
- 2 * t.getTextLetterSpaceAdjust());
}
word = t;
if (word != null) {
parentLM.addChildArea(word);
}
}
/**
* Create an inline word area.
* This creates a TextArea and sets up the various attributes.
*
* @param str the string for the TextArea
* @param width the MinOptMax width of the content
* @param adjust the total ipd adjustment with respect to the optimal width
* @param base the baseline position
* @return the new word area
*/
protected TextArea createTextArea(String str, MinOptMax width, int adjust,
LayoutContext context, int spaceDiff) {
TextArea textArea;
if (context.getIPDAdjust() == 0.0) {
// create just a TextArea
textArea = new TextArea();
} else {
// justified area: create a TextArea with extra info
// about potential adjustments
textArea = new TextArea(width.max - width.opt,
width.opt - width.min,
adjust);
}
textArea.setIPD(width.opt + adjust);
textArea.setBPD(fs.getAscender() - fs.getDescender());
int bpd = textArea.getBPD();
switch (verticalAlignment) {
case EN_MIDDLE:
textArea.setOffset(context.getMiddleBaseline() + fs.getXHeight() / 2);
break;
case EN_TOP:
textArea.setOffset(context.getTopBaseline() + fs.getAscender());
break;
case EN_BOTTOM:
textArea.setOffset(context.getBottomBaseline() - bpd + fs.getAscender());
break;
case EN_BASELINE:
default:
textArea.setOffset(context.getBaseline());
break;
}
textArea.setTextArea(str);
textArea.addTrait(Trait.FONT_NAME, fs.getFontName());
textArea.addTrait(Trait.FONT_SIZE, new Integer(fs.getFontSize()));
textArea.addTrait(Trait.COLOR, foText.getColor());
TraitSetter.addTextDecoration(textArea, foText.getTextDecoration());
return textArea;
}
/**
* Set the alignment of the inline area.
* @param al the vertical alignment positioning
*/
public void setAlignment(int al) {
verticalAlignment = al;
}
public LinkedList getNextKnuthElements(LayoutContext context,
int alignment) {
LinkedList returnList = new LinkedList();
KnuthSequence sequence = new KnuthSequence(true);
returnList.add(sequence);
while (iNextStart < textArray.length) {
if (textArray[iNextStart] == SPACE
|| textArray[iNextStart] == NBSPACE) {
// normal, breaking space
// or non-breaking space
if (textArray[iNextStart] == NBSPACE) {
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, vecAreaInfo.size() - 1),
false));
}
switch (alignment) {
case EN_CENTER :
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
- new LeafPosition(this, vecAreaInfo.size() - 1), false));
+ new LeafPosition(this, -1), false));
sequence.add
(new KnuthPenalty(0, 0, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
- 6 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
- new LeafPosition(this, -1), true));
+ new LeafPosition(this, vecAreaInfo.size() - 1), true));
sequence.add
(new KnuthInlineBox(0, 0, 0, 0,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, -1), true));
iNextStart ++;
break;
case EN_START : // fall through
case EN_END :
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(0, 3 * wordSpaceIPD.opt, 0,
- new LeafPosition(this, vecAreaInfo.size() - 1), false));
+ new LeafPosition(this, -1), false));
sequence.add
(new KnuthPenalty(0, 0, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
- 3 * wordSpaceIPD.opt, 0,
- new LeafPosition(this, -1), true));
+ new LeafPosition(this, vecAreaInfo.size() - 1), true));
iNextStart ++;
break;
case EN_JUSTIFY:
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
wordSpaceIPD.max - wordSpaceIPD.opt,
wordSpaceIPD.opt - wordSpaceIPD.min,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
iNextStart ++;
break;
default:
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
wordSpaceIPD.max - wordSpaceIPD.opt, 0,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
iNextStart ++;
}
} else if (textArray[iNextStart] == NBSPACE) {
// non breaking space
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
wordSpaceIPD.max - wordSpaceIPD.opt,
wordSpaceIPD.opt - wordSpaceIPD.min,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
iNextStart ++;
} else if (textArray[iNextStart] == NEWLINE) {
// linefeed; this can happen when linefeed-treatment="preserve"
// add a penalty item to the list and start a new sequence
sequence.add
(new KnuthPenalty(0, -KnuthElement.INFINITE,
false, null, false));
sequence = new KnuthSequence(true);
returnList.add(sequence);
iNextStart ++;
} else {
// the beginning of a word
iThisStart = iNextStart;
iTempStart = iNextStart;
MinOptMax wordIPD = new MinOptMax(0);
for (; iTempStart < textArray.length
&& textArray[iTempStart] != SPACE
&& textArray[iTempStart] != NBSPACE
&& textArray[iTempStart] != NEWLINE
&& !(iTempStart > iNextStart
&& alignment == EN_JUSTIFY
&& BREAK_CHARS.indexOf(textArray[iTempStart - 1]) >= 0);
iTempStart++) {
wordIPD.add(fs.getCharWidth(textArray[iTempStart]));
}
int iLetterSpaces = iTempStart - iThisStart - 1;
wordIPD.add(MinOptMax.multiply(letterSpaceIPD, iLetterSpaces));
vecAreaInfo.add
(new AreaInfo(iThisStart, iTempStart, (short) 0,
(short) iLetterSpaces,
wordIPD, false));
if (letterSpaceIPD.min == letterSpaceIPD.max) {
// constant letter space; simply return a box
// whose width includes letter spaces
sequence.add
(new KnuthInlineBox(wordIPD.opt, lead, total, middle,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
} else {
// adjustable letter space;
// some other KnuthElements are needed
sequence.add
(new KnuthInlineBox(wordIPD.opt - iLetterSpaces * letterSpaceIPD.opt,
lead, total, middle,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(iLetterSpaces * letterSpaceIPD.opt,
iLetterSpaces * (letterSpaceIPD.max - letterSpaceIPD.opt),
iLetterSpaces * (letterSpaceIPD.opt - letterSpaceIPD.min),
new LeafPosition(this, -1), true));
sequence.add
(new KnuthInlineBox(0, lead, total, middle,
new LeafPosition(this, -1), true));
}
// if the last character is '-' or '/', it could be used as a line end;
// add a flagged penalty element and glue element representing a suppressible
// letter space if the next character is not a space
if (BREAK_CHARS.indexOf(textArray[iTempStart - 1]) >= 0
&& iTempStart < textArray.length
&& textArray[iTempStart] != SPACE
&& textArray[iTempStart] != NBSPACE) {
sequence.add
(new KnuthPenalty(0, KnuthPenalty.FLAGGED_PENALTY, true,
new LeafPosition(this, -1), false));
sequence.add
(new KnuthGlue(letterSpaceIPD.opt,
letterSpaceIPD.max - letterSpaceIPD.opt,
letterSpaceIPD.opt - letterSpaceIPD.min,
new LeafPosition(this, -1), false));
// update the information in the AreaInfo, adding one more letter space
AreaInfo ai = (AreaInfo) vecAreaInfo.get(vecAreaInfo.size() - 1);
ai.iLScount ++;
}
iNextStart = iTempStart;
}
} // end of while
if (((List)returnList.getLast()).size() == 0) {
//Remove an empty sequence because of a trailing newline
returnList.removeLast();
}
setFinished(true);
if (returnList.size() > 0) {
return returnList;
} else {
return null;
}
}
public List addALetterSpaceTo(List oldList) {
// old list contains only a box, or the sequence: box penalty glue box;
// look at the Position stored in the first element in oldList
// which is always a box
ListIterator oldListIterator = oldList.listIterator();
KnuthElement el = (KnuthElement)oldListIterator.next();
LeafPosition pos = (LeafPosition) ((KnuthBox) el).getPosition();
AreaInfo ai = (AreaInfo) vecAreaInfo.get(pos.getLeafPos());
ai.iLScount ++;
ai.ipdArea.add(letterSpaceIPD);
if (BREAK_CHARS.indexOf(textArray[iTempStart - 1]) >= 0) {
// the last character could be used as a line break
// append new elements to oldList
oldListIterator = oldList.listIterator(oldList.size());
oldListIterator.add(new KnuthPenalty(0, KnuthPenalty.FLAGGED_PENALTY, true,
new LeafPosition(this, -1), false));
oldListIterator.add(new KnuthGlue(letterSpaceIPD.opt,
letterSpaceIPD.max - letterSpaceIPD.opt,
letterSpaceIPD.opt - letterSpaceIPD.min,
new LeafPosition(this, -1), false));
} else if (letterSpaceIPD.min == letterSpaceIPD.max) {
// constant letter space: replace the box
oldListIterator.set(new KnuthInlineBox(ai.ipdArea.opt, lead, total, middle, pos, false));
} else {
// adjustable letter space: replace the glue
oldListIterator.next(); // this would return the penalty element
oldListIterator.next(); // this would return the glue element
oldListIterator.set(new KnuthGlue(ai.iLScount * letterSpaceIPD.opt,
ai.iLScount * (letterSpaceIPD.max - letterSpaceIPD.opt),
ai.iLScount * (letterSpaceIPD.opt - letterSpaceIPD.min),
new LeafPosition(this, -1), true));
}
return oldList;
}
public void hyphenate(Position pos, HyphContext hc) {
AreaInfo ai
= (AreaInfo) vecAreaInfo.get(((LeafPosition) pos).getLeafPos());
int iStartIndex = ai.iStartIndex;
int iStopIndex;
boolean bNothingChanged = true;
while (iStartIndex < ai.iBreakIndex) {
MinOptMax newIPD = new MinOptMax(0);
boolean bHyphenFollows;
if (hc.hasMoreHyphPoints()
&& (iStopIndex = iStartIndex + hc.getNextHyphPoint())
<= ai.iBreakIndex) {
// iStopIndex is the index of the first character
// after a hyphenation point
bHyphenFollows = true;
} else {
// there are no more hyphenation points,
// or the next one is after ai.iBreakIndex
bHyphenFollows = false;
iStopIndex = ai.iBreakIndex;
}
hc.updateOffset(iStopIndex - iStartIndex);
for (int i = iStartIndex; i < iStopIndex; i++) {
char c = textArray[i];
newIPD.add(new MinOptMax(fs.getCharWidth(c)));
}
// add letter spaces
boolean bIsWordEnd
= iStopIndex == ai.iBreakIndex
&& ai.iLScount < (ai.iBreakIndex - ai.iStartIndex);
newIPD.add(MinOptMax.multiply(letterSpaceIPD,
(bIsWordEnd
? (iStopIndex - iStartIndex - 1)
: (iStopIndex - iStartIndex))));
if (!(bNothingChanged
&& iStopIndex == ai.iBreakIndex
&& bHyphenFollows == false)) {
// the new AreaInfo object is not equal to the old one
if (changeList == null) {
changeList = new LinkedList();
}
changeList.add
(new PendingChange
(new AreaInfo((short) iStartIndex, (short) iStopIndex,
(short) 0,
(short) (bIsWordEnd
? (iStopIndex - iStartIndex - 1)
: (iStopIndex - iStartIndex)),
newIPD, bHyphenFollows),
((LeafPosition) pos).getLeafPos()));
bNothingChanged = false;
}
iStartIndex = iStopIndex;
}
if (!bChanged && !bNothingChanged) {
bChanged = true;
}
}
public boolean applyChanges(List oldList) {
setFinished(false);
if (changeList != null) {
int iAddedAI = 0;
int iRemovedAI = 0;
int iOldIndex = -1;
PendingChange currChange = null;
ListIterator changeListIterator = changeList.listIterator();
while (changeListIterator.hasNext()) {
currChange = (PendingChange) changeListIterator.next();
if (currChange.index != iOldIndex) {
iRemovedAI ++;
iAddedAI ++;
iOldIndex = currChange.index;
vecAreaInfo.remove(currChange.index + iAddedAI - iRemovedAI);
vecAreaInfo.add(currChange.index + iAddedAI - iRemovedAI,
currChange.ai);
} else {
iAddedAI ++;
vecAreaInfo.add(currChange.index + iAddedAI - iRemovedAI,
currChange.ai);
}
}
changeList.clear();
}
iReturnedIndex = 0;
return bChanged;
}
public LinkedList getChangedKnuthElements(List oldList,
/*int flaggedPenalty,*/
int alignment) {
if (isFinished()) {
return null;
}
LinkedList returnList = new LinkedList();
while (iReturnedIndex < vecAreaInfo.size()) {
AreaInfo ai = (AreaInfo) vecAreaInfo.get(iReturnedIndex);
if (ai.iWScount == 0) {
// ai refers either to a word or a word fragment
// if the last character is '-' or '/' and the next character is not a space
// one of the letter spaces must be represented using a penalty and a glue,
// and its width must be subtracted
if (BREAK_CHARS.indexOf(textArray[ai.iBreakIndex - 1]) >= 0
&& ai.iLScount == (ai.iBreakIndex - ai.iStartIndex)) {
ai.ipdArea.add(new MinOptMax(-letterSpaceIPD.min, -letterSpaceIPD.opt, -letterSpaceIPD.max));
}
if (letterSpaceIPD.min == letterSpaceIPD.max) {
returnList.add
(new KnuthInlineBox(ai.ipdArea.opt, lead, total, middle,
new LeafPosition(this, iReturnedIndex), false));
} else {
returnList.add
(new KnuthInlineBox(ai.ipdArea.opt
- ai.iLScount * letterSpaceIPD.opt,
lead, total, middle,
new LeafPosition(this, iReturnedIndex), false));
returnList.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, -1), true));
returnList.add
(new KnuthGlue(ai.iLScount * letterSpaceIPD.opt,
ai.iLScount * (letterSpaceIPD.max - letterSpaceIPD.opt),
ai.iLScount * (letterSpaceIPD.opt - letterSpaceIPD.min),
new LeafPosition(this, -1), true));
returnList.add
(new KnuthInlineBox(0, 0, 0, 0,
new LeafPosition(this, -1), true));
}
if (ai.bHyphenated) {
returnList.add
(new KnuthPenalty(hyphIPD, KnuthPenalty.FLAGGED_PENALTY, true,
new LeafPosition(this, -1), false));
}
// if the last character is '-' or '/', it could be used as a line end;
// add a flagged penalty element and a glue element representing a suppressible
// letter space if the next character is not a space
if (BREAK_CHARS.indexOf(textArray[ai.iBreakIndex - 1]) >= 0
&& ai.iLScount == (ai.iBreakIndex - ai.iStartIndex)) {
returnList.add
(new KnuthPenalty(0, KnuthPenalty.FLAGGED_PENALTY, true,
new LeafPosition(this, -1), false));
returnList.add
(new KnuthGlue(letterSpaceIPD.opt,
letterSpaceIPD.max - letterSpaceIPD.opt,
letterSpaceIPD.opt - letterSpaceIPD.min,
new LeafPosition(this, -1), false));
}
iReturnedIndex ++;
} else {
// ai refers to a space
if (textArray[ai.iStartIndex] == NBSPACE) {
returnList.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, -1),
false));
}
switch (alignment) {
case EN_CENTER :
returnList.add
(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, iReturnedIndex), false));
returnList.add
(new KnuthPenalty(0, 0, false,
new LeafPosition(this, -1), true));
returnList.add
(new KnuthGlue(wordSpaceIPD.opt,
- 6 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, -1), true));
returnList.add
(new KnuthInlineBox(0, 0, 0, 0,
new LeafPosition(this, -1), true));
returnList.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, -1), true));
returnList.add
(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, -1), true));
iReturnedIndex ++;
break;
case EN_START : // fall through
case EN_END :
returnList.add
(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, iReturnedIndex), false));
returnList.add
(new KnuthPenalty(0, 0, false,
new LeafPosition(this, -1), true));
returnList.add
(new KnuthGlue(wordSpaceIPD.opt,
- 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, -1), true));
iReturnedIndex ++;
break;
case EN_JUSTIFY:
returnList.add
(new KnuthGlue(wordSpaceIPD.opt,
wordSpaceIPD.max - wordSpaceIPD.opt,
wordSpaceIPD.opt - wordSpaceIPD.min,
new LeafPosition(this, iReturnedIndex), false));
iReturnedIndex ++;
break;
default:
returnList.add
(new KnuthGlue(wordSpaceIPD.opt,
wordSpaceIPD.max - wordSpaceIPD.opt, 0,
new LeafPosition(this, iReturnedIndex), false));
iReturnedIndex ++;
}
}
} // end of while
setFinished(true);
return returnList;
}
public void getWordChars(StringBuffer sbChars, Position pos) {
int iLeafValue = ((LeafPosition) pos).getLeafPos();
if (iLeafValue != -1) {
AreaInfo ai = (AreaInfo) vecAreaInfo.get(iLeafValue);
sbChars.append(new String(textArray, ai.iStartIndex,
ai.iBreakIndex - ai.iStartIndex));
}
}
}
| false | true | public LinkedList getNextKnuthElements(LayoutContext context,
int alignment) {
LinkedList returnList = new LinkedList();
KnuthSequence sequence = new KnuthSequence(true);
returnList.add(sequence);
while (iNextStart < textArray.length) {
if (textArray[iNextStart] == SPACE
|| textArray[iNextStart] == NBSPACE) {
// normal, breaking space
// or non-breaking space
if (textArray[iNextStart] == NBSPACE) {
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, vecAreaInfo.size() - 1),
false));
}
switch (alignment) {
case EN_CENTER :
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
sequence.add
(new KnuthPenalty(0, 0, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
- 6 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthInlineBox(0, 0, 0, 0,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, -1), true));
iNextStart ++;
break;
case EN_START : // fall through
case EN_END :
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(0, 3 * wordSpaceIPD.opt, 0,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
sequence.add
(new KnuthPenalty(0, 0, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
- 3 * wordSpaceIPD.opt, 0,
new LeafPosition(this, -1), true));
iNextStart ++;
break;
case EN_JUSTIFY:
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
wordSpaceIPD.max - wordSpaceIPD.opt,
wordSpaceIPD.opt - wordSpaceIPD.min,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
iNextStart ++;
break;
default:
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
wordSpaceIPD.max - wordSpaceIPD.opt, 0,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
iNextStart ++;
}
} else if (textArray[iNextStart] == NBSPACE) {
// non breaking space
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
wordSpaceIPD.max - wordSpaceIPD.opt,
wordSpaceIPD.opt - wordSpaceIPD.min,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
iNextStart ++;
} else if (textArray[iNextStart] == NEWLINE) {
// linefeed; this can happen when linefeed-treatment="preserve"
// add a penalty item to the list and start a new sequence
sequence.add
(new KnuthPenalty(0, -KnuthElement.INFINITE,
false, null, false));
sequence = new KnuthSequence(true);
returnList.add(sequence);
iNextStart ++;
} else {
// the beginning of a word
iThisStart = iNextStart;
iTempStart = iNextStart;
MinOptMax wordIPD = new MinOptMax(0);
for (; iTempStart < textArray.length
&& textArray[iTempStart] != SPACE
&& textArray[iTempStart] != NBSPACE
&& textArray[iTempStart] != NEWLINE
&& !(iTempStart > iNextStart
&& alignment == EN_JUSTIFY
&& BREAK_CHARS.indexOf(textArray[iTempStart - 1]) >= 0);
iTempStart++) {
wordIPD.add(fs.getCharWidth(textArray[iTempStart]));
}
int iLetterSpaces = iTempStart - iThisStart - 1;
wordIPD.add(MinOptMax.multiply(letterSpaceIPD, iLetterSpaces));
vecAreaInfo.add
(new AreaInfo(iThisStart, iTempStart, (short) 0,
(short) iLetterSpaces,
wordIPD, false));
if (letterSpaceIPD.min == letterSpaceIPD.max) {
// constant letter space; simply return a box
// whose width includes letter spaces
sequence.add
(new KnuthInlineBox(wordIPD.opt, lead, total, middle,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
} else {
// adjustable letter space;
// some other KnuthElements are needed
sequence.add
(new KnuthInlineBox(wordIPD.opt - iLetterSpaces * letterSpaceIPD.opt,
lead, total, middle,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(iLetterSpaces * letterSpaceIPD.opt,
iLetterSpaces * (letterSpaceIPD.max - letterSpaceIPD.opt),
iLetterSpaces * (letterSpaceIPD.opt - letterSpaceIPD.min),
new LeafPosition(this, -1), true));
sequence.add
(new KnuthInlineBox(0, lead, total, middle,
new LeafPosition(this, -1), true));
}
// if the last character is '-' or '/', it could be used as a line end;
// add a flagged penalty element and glue element representing a suppressible
// letter space if the next character is not a space
if (BREAK_CHARS.indexOf(textArray[iTempStart - 1]) >= 0
&& iTempStart < textArray.length
&& textArray[iTempStart] != SPACE
&& textArray[iTempStart] != NBSPACE) {
sequence.add
(new KnuthPenalty(0, KnuthPenalty.FLAGGED_PENALTY, true,
new LeafPosition(this, -1), false));
sequence.add
(new KnuthGlue(letterSpaceIPD.opt,
letterSpaceIPD.max - letterSpaceIPD.opt,
letterSpaceIPD.opt - letterSpaceIPD.min,
new LeafPosition(this, -1), false));
// update the information in the AreaInfo, adding one more letter space
AreaInfo ai = (AreaInfo) vecAreaInfo.get(vecAreaInfo.size() - 1);
ai.iLScount ++;
}
iNextStart = iTempStart;
}
} // end of while
if (((List)returnList.getLast()).size() == 0) {
//Remove an empty sequence because of a trailing newline
returnList.removeLast();
}
setFinished(true);
if (returnList.size() > 0) {
return returnList;
} else {
return null;
}
}
| public LinkedList getNextKnuthElements(LayoutContext context,
int alignment) {
LinkedList returnList = new LinkedList();
KnuthSequence sequence = new KnuthSequence(true);
returnList.add(sequence);
while (iNextStart < textArray.length) {
if (textArray[iNextStart] == SPACE
|| textArray[iNextStart] == NBSPACE) {
// normal, breaking space
// or non-breaking space
if (textArray[iNextStart] == NBSPACE) {
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, vecAreaInfo.size() - 1),
false));
}
switch (alignment) {
case EN_CENTER :
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, -1), false));
sequence.add
(new KnuthPenalty(0, 0, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
- 6 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, vecAreaInfo.size() - 1), true));
sequence.add
(new KnuthInlineBox(0, 0, 0, 0,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(0, 3 * LineLayoutManager.DEFAULT_SPACE_WIDTH, 0,
new LeafPosition(this, -1), true));
iNextStart ++;
break;
case EN_START : // fall through
case EN_END :
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(0, 3 * wordSpaceIPD.opt, 0,
new LeafPosition(this, -1), false));
sequence.add
(new KnuthPenalty(0, 0, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
- 3 * wordSpaceIPD.opt, 0,
new LeafPosition(this, vecAreaInfo.size() - 1), true));
iNextStart ++;
break;
case EN_JUSTIFY:
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
wordSpaceIPD.max - wordSpaceIPD.opt,
wordSpaceIPD.opt - wordSpaceIPD.min,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
iNextStart ++;
break;
default:
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
wordSpaceIPD.max - wordSpaceIPD.opt, 0,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
iNextStart ++;
}
} else if (textArray[iNextStart] == NBSPACE) {
// non breaking space
vecAreaInfo.add
(new AreaInfo(iNextStart, (short) (iNextStart + 1),
(short) 1, (short) 0,
wordSpaceIPD, false));
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
sequence.add
(new KnuthGlue(wordSpaceIPD.opt,
wordSpaceIPD.max - wordSpaceIPD.opt,
wordSpaceIPD.opt - wordSpaceIPD.min,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
iNextStart ++;
} else if (textArray[iNextStart] == NEWLINE) {
// linefeed; this can happen when linefeed-treatment="preserve"
// add a penalty item to the list and start a new sequence
sequence.add
(new KnuthPenalty(0, -KnuthElement.INFINITE,
false, null, false));
sequence = new KnuthSequence(true);
returnList.add(sequence);
iNextStart ++;
} else {
// the beginning of a word
iThisStart = iNextStart;
iTempStart = iNextStart;
MinOptMax wordIPD = new MinOptMax(0);
for (; iTempStart < textArray.length
&& textArray[iTempStart] != SPACE
&& textArray[iTempStart] != NBSPACE
&& textArray[iTempStart] != NEWLINE
&& !(iTempStart > iNextStart
&& alignment == EN_JUSTIFY
&& BREAK_CHARS.indexOf(textArray[iTempStart - 1]) >= 0);
iTempStart++) {
wordIPD.add(fs.getCharWidth(textArray[iTempStart]));
}
int iLetterSpaces = iTempStart - iThisStart - 1;
wordIPD.add(MinOptMax.multiply(letterSpaceIPD, iLetterSpaces));
vecAreaInfo.add
(new AreaInfo(iThisStart, iTempStart, (short) 0,
(short) iLetterSpaces,
wordIPD, false));
if (letterSpaceIPD.min == letterSpaceIPD.max) {
// constant letter space; simply return a box
// whose width includes letter spaces
sequence.add
(new KnuthInlineBox(wordIPD.opt, lead, total, middle,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
} else {
// adjustable letter space;
// some other KnuthElements are needed
sequence.add
(new KnuthInlineBox(wordIPD.opt - iLetterSpaces * letterSpaceIPD.opt,
lead, total, middle,
new LeafPosition(this, vecAreaInfo.size() - 1), false));
sequence.add
(new KnuthPenalty(0, KnuthElement.INFINITE, false,
new LeafPosition(this, -1), true));
sequence.add
(new KnuthGlue(iLetterSpaces * letterSpaceIPD.opt,
iLetterSpaces * (letterSpaceIPD.max - letterSpaceIPD.opt),
iLetterSpaces * (letterSpaceIPD.opt - letterSpaceIPD.min),
new LeafPosition(this, -1), true));
sequence.add
(new KnuthInlineBox(0, lead, total, middle,
new LeafPosition(this, -1), true));
}
// if the last character is '-' or '/', it could be used as a line end;
// add a flagged penalty element and glue element representing a suppressible
// letter space if the next character is not a space
if (BREAK_CHARS.indexOf(textArray[iTempStart - 1]) >= 0
&& iTempStart < textArray.length
&& textArray[iTempStart] != SPACE
&& textArray[iTempStart] != NBSPACE) {
sequence.add
(new KnuthPenalty(0, KnuthPenalty.FLAGGED_PENALTY, true,
new LeafPosition(this, -1), false));
sequence.add
(new KnuthGlue(letterSpaceIPD.opt,
letterSpaceIPD.max - letterSpaceIPD.opt,
letterSpaceIPD.opt - letterSpaceIPD.min,
new LeafPosition(this, -1), false));
// update the information in the AreaInfo, adding one more letter space
AreaInfo ai = (AreaInfo) vecAreaInfo.get(vecAreaInfo.size() - 1);
ai.iLScount ++;
}
iNextStart = iTempStart;
}
} // end of while
if (((List)returnList.getLast()).size() == 0) {
//Remove an empty sequence because of a trailing newline
returnList.removeLast();
}
setFinished(true);
if (returnList.size() > 0) {
return returnList;
} else {
return null;
}
}
|
diff --git a/org.bndtools.rt.rest/src/org/bndtools/rt/rest/HttpServiceTracker.java b/org.bndtools.rt.rest/src/org/bndtools/rt/rest/HttpServiceTracker.java
index b5c0bdd..0c5c6b7 100644
--- a/org.bndtools.rt.rest/src/org/bndtools/rt/rest/HttpServiceTracker.java
+++ b/org.bndtools.rt.rest/src/org/bndtools/rt/rest/HttpServiceTracker.java
@@ -1,53 +1,53 @@
package org.bndtools.rt.rest;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpService;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
public class HttpServiceTracker extends ServiceTracker {
private final LogService log;
static final class Endpoint {
final RestAppServletManager manager;
final ResourceServiceTracker serviceTracker;
final ResourceClassTracker classTracker;
Endpoint(RestAppServletManager manager, ResourceServiceTracker serviceTracker, ResourceClassTracker classTracker) {
this.manager = manager;
this.serviceTracker = serviceTracker;
this.classTracker = classTracker;
}
}
public HttpServiceTracker(BundleContext context, LogService log) {
super(context, HttpService.class.getName(), null);
this.log = log;
}
public Object addingService(@SuppressWarnings("rawtypes") ServiceReference reference) {
@SuppressWarnings("unchecked")
- HttpService httpService = context.getService(reference);
+ HttpService httpService = (HttpService) context.getService(reference);
RestAppServletManager manager = new RestAppServletManager(httpService);
ResourceServiceTracker serviceTracker = ResourceServiceTracker.newInstance(context, manager, log);
serviceTracker.open();
ResourceClassTracker classTracker = new ResourceClassTracker(context, manager, log);
classTracker.open();
return new Endpoint(manager, serviceTracker, classTracker);
}
@Override
public void removedService(@SuppressWarnings("rawtypes") ServiceReference reference, Object service) {
Endpoint endpoint = (Endpoint) service;
endpoint.classTracker.close();
endpoint.serviceTracker.close();
endpoint.manager.destroyAll();
context.ungetService(reference);
}
}
| true | true | public Object addingService(@SuppressWarnings("rawtypes") ServiceReference reference) {
@SuppressWarnings("unchecked")
HttpService httpService = context.getService(reference);
RestAppServletManager manager = new RestAppServletManager(httpService);
ResourceServiceTracker serviceTracker = ResourceServiceTracker.newInstance(context, manager, log);
serviceTracker.open();
ResourceClassTracker classTracker = new ResourceClassTracker(context, manager, log);
classTracker.open();
return new Endpoint(manager, serviceTracker, classTracker);
}
| public Object addingService(@SuppressWarnings("rawtypes") ServiceReference reference) {
@SuppressWarnings("unchecked")
HttpService httpService = (HttpService) context.getService(reference);
RestAppServletManager manager = new RestAppServletManager(httpService);
ResourceServiceTracker serviceTracker = ResourceServiceTracker.newInstance(context, manager, log);
serviceTracker.open();
ResourceClassTracker classTracker = new ResourceClassTracker(context, manager, log);
classTracker.open();
return new Endpoint(manager, serviceTracker, classTracker);
}
|
diff --git a/src/main/java/com/bergerkiller/bukkit/tc/signactions/SignActionSwitcher.java b/src/main/java/com/bergerkiller/bukkit/tc/signactions/SignActionSwitcher.java
index 9c055df..01ae894 100644
--- a/src/main/java/com/bergerkiller/bukkit/tc/signactions/SignActionSwitcher.java
+++ b/src/main/java/com/bergerkiller/bukkit/tc/signactions/SignActionSwitcher.java
@@ -1,196 +1,196 @@
package com.bergerkiller.bukkit.tc.signactions;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.Sign;
import com.bergerkiller.bukkit.common.collections.BlockMap;
import com.bergerkiller.bukkit.common.utils.BlockUtil;
import com.bergerkiller.bukkit.common.utils.LogicUtil;
import com.bergerkiller.bukkit.common.utils.MaterialUtil;
import com.bergerkiller.bukkit.tc.Direction;
import com.bergerkiller.bukkit.tc.DirectionStatement;
import com.bergerkiller.bukkit.tc.Permission;
import com.bergerkiller.bukkit.tc.actions.GroupActionWaitPathFinding;
import com.bergerkiller.bukkit.tc.events.SignActionEvent;
import com.bergerkiller.bukkit.tc.events.SignChangeActionEvent;
import com.bergerkiller.bukkit.tc.pathfinding.PathConnection;
import com.bergerkiller.bukkit.tc.pathfinding.PathNode;
import com.bergerkiller.bukkit.tc.pathfinding.PathProvider;
import com.bergerkiller.bukkit.tc.properties.IProperties;
public class SignActionSwitcher extends SignAction {
private BlockMap<AtomicInteger> switchedTimes = new BlockMap<AtomicInteger>();
private AtomicInteger getSwitchedTimes(Block signblock) {
AtomicInteger i = switchedTimes.get(signblock);
if (i == null) {
i = new AtomicInteger();
switchedTimes.put(signblock, i);
}
return i;
}
@Override
public boolean match(SignActionEvent info) {
return info.isType("switcher", "tag");
}
@Override
public void execute(SignActionEvent info) {
boolean doCart = false;
boolean doTrain = false;
if (info.isAction(SignActionType.GROUP_ENTER, SignActionType.GROUP_UPDATE) && info.isTrainSign()) {
doTrain = true;
} else if (info.isAction(SignActionType.MEMBER_ENTER, SignActionType.MEMBER_UPDATE) && info.isCartSign()) {
doCart = true;
} else if (info.isAction(SignActionType.MEMBER_LEAVE) && info.isCartSign()) {
info.setLevers(false);
return;
} else if (info.isAction(SignActionType.GROUP_LEAVE) && info.isTrainSign()) {
info.setLevers(false);
return;
} else {
return;
}
if (!info.hasRailedMember()) {
return;
}
final boolean facing = info.isFacing();
- if (facing && info.isPowered()) {
+ if (facing) {
final BlockFace cartDirection = info.getCartDirection();
//find out what statements to parse
List<DirectionStatement> statements = new ArrayList<DirectionStatement>();
statements.add(new DirectionStatement(info.getLine(2), cartDirection, Direction.LEFT));
statements.add(new DirectionStatement(info.getLine(3), cartDirection, Direction.RIGHT));
//other signs below this sign we could parse?
for (Sign sign : info.findSignsBelow()) {
boolean valid = true;
for (String line : sign.getLines()) {
DirectionStatement stat = new DirectionStatement(line, cartDirection);
if (stat.direction == Direction.NONE) {
valid = false;
break;
} else {
statements.add(stat);
}
}
if (!valid) {
break;
}
}
Block signblock = info.getBlock();
while (MaterialUtil.ISSIGN.get(signblock = signblock.getRelative(BlockFace.DOWN))) {
Sign sign = BlockUtil.getSign(signblock);
if (sign == null) break;
boolean valid = true;
for (String line : sign.getLines()) {
DirectionStatement stat = new DirectionStatement(line, cartDirection);
if (stat.direction == Direction.NONE) {
valid = false;
break;
} else {
statements.add(stat);
}
}
if (!valid) break;
}
//parse all of the statements
//are we going to use a counter?
int maxcount = 0;
int currentcount = 0;
AtomicInteger signcounter = null;
for (DirectionStatement stat : statements) {
if (stat.hasNumber()) {
maxcount += stat.number;
if (signcounter == null) {
signcounter = getSwitchedTimes(info.getBlock());
if (info.isAction(SignActionType.MEMBER_ENTER, SignActionType.GROUP_ENTER)) {
currentcount = signcounter.getAndIncrement();
} else {
currentcount = signcounter.get();
}
}
}
}
if (signcounter != null && currentcount >= maxcount) {
signcounter.set(1);
currentcount = 0;
}
int counter = 0;
Direction dir = Direction.NONE;
for (DirectionStatement stat : statements) {
if ((stat.hasNumber() && (counter += stat.number) > currentcount)
|| (doCart && stat.has(info, info.getMember()))
|| (doTrain && stat.has(info, info.getGroup()))) {
dir = stat.direction;
break;
}
}
info.setLevers(dir != Direction.NONE);
- if (dir != Direction.NONE) {
+ if (dir != Direction.NONE && info.isPowered()) {
//handle this direction
info.setRailsTo(dir);
return; //don't do destination stuff
}
}
// Handle destination alternatively
if (info.isAction(SignActionType.MEMBER_ENTER, SignActionType.GROUP_ENTER) && (facing || !info.isWatchedDirectionsDefined())) {
PathNode node = PathNode.getOrCreate(info);
if (node != null) {
String destination = null;
IProperties prop = null;
if (doCart && info.hasMember()) {
prop = info.getMember().getProperties();
} else if (doTrain && info.hasGroup()) {
prop = info.getGroup().getProperties();
}
if (prop != null) {
destination = prop.getDestination();
prop.setLastPathNode(node.name);
}
if (!LogicUtil.nullOrEmpty(destination)) {
if (PathProvider.isProcessing()) {
double currentForce = info.getGroup().getAverageForce();
// Add an action to let the train wait until the node IS explored
info.getGroup().getActions().addAction(new GroupActionWaitPathFinding(info, node, destination));
info.getMember().getActions().addActionLaunch(info.getMember().getDirectionFrom(), 1.0, currentForce);
info.getGroup().stop();
} else {
// Switch the rails to the right direction
PathConnection conn = node.findConnection(destination);
if (conn != null) {
info.setRailsTo(conn.direction);
}
}
}
}
}
}
@Override
public boolean build(SignChangeActionEvent event) {
if (event.isCartSign()) {
return handleBuild(event, Permission.BUILD_SWITCHER, "cart switcher", "switch between tracks based on properties of the cart above");
} else if (event.isTrainSign()) {
return handleBuild(event, Permission.BUILD_SWITCHER, "train switcher", "switch between tracks based on properties of the train above");
}
return false;
}
@Override
public void destroy(SignActionEvent event) {
PathNode.clear(event.getRails());
}
@Override
public boolean overrideFacing() {
return true;
}
}
| false | true | public void execute(SignActionEvent info) {
boolean doCart = false;
boolean doTrain = false;
if (info.isAction(SignActionType.GROUP_ENTER, SignActionType.GROUP_UPDATE) && info.isTrainSign()) {
doTrain = true;
} else if (info.isAction(SignActionType.MEMBER_ENTER, SignActionType.MEMBER_UPDATE) && info.isCartSign()) {
doCart = true;
} else if (info.isAction(SignActionType.MEMBER_LEAVE) && info.isCartSign()) {
info.setLevers(false);
return;
} else if (info.isAction(SignActionType.GROUP_LEAVE) && info.isTrainSign()) {
info.setLevers(false);
return;
} else {
return;
}
if (!info.hasRailedMember()) {
return;
}
final boolean facing = info.isFacing();
if (facing && info.isPowered()) {
final BlockFace cartDirection = info.getCartDirection();
//find out what statements to parse
List<DirectionStatement> statements = new ArrayList<DirectionStatement>();
statements.add(new DirectionStatement(info.getLine(2), cartDirection, Direction.LEFT));
statements.add(new DirectionStatement(info.getLine(3), cartDirection, Direction.RIGHT));
//other signs below this sign we could parse?
for (Sign sign : info.findSignsBelow()) {
boolean valid = true;
for (String line : sign.getLines()) {
DirectionStatement stat = new DirectionStatement(line, cartDirection);
if (stat.direction == Direction.NONE) {
valid = false;
break;
} else {
statements.add(stat);
}
}
if (!valid) {
break;
}
}
Block signblock = info.getBlock();
while (MaterialUtil.ISSIGN.get(signblock = signblock.getRelative(BlockFace.DOWN))) {
Sign sign = BlockUtil.getSign(signblock);
if (sign == null) break;
boolean valid = true;
for (String line : sign.getLines()) {
DirectionStatement stat = new DirectionStatement(line, cartDirection);
if (stat.direction == Direction.NONE) {
valid = false;
break;
} else {
statements.add(stat);
}
}
if (!valid) break;
}
//parse all of the statements
//are we going to use a counter?
int maxcount = 0;
int currentcount = 0;
AtomicInteger signcounter = null;
for (DirectionStatement stat : statements) {
if (stat.hasNumber()) {
maxcount += stat.number;
if (signcounter == null) {
signcounter = getSwitchedTimes(info.getBlock());
if (info.isAction(SignActionType.MEMBER_ENTER, SignActionType.GROUP_ENTER)) {
currentcount = signcounter.getAndIncrement();
} else {
currentcount = signcounter.get();
}
}
}
}
if (signcounter != null && currentcount >= maxcount) {
signcounter.set(1);
currentcount = 0;
}
int counter = 0;
Direction dir = Direction.NONE;
for (DirectionStatement stat : statements) {
if ((stat.hasNumber() && (counter += stat.number) > currentcount)
|| (doCart && stat.has(info, info.getMember()))
|| (doTrain && stat.has(info, info.getGroup()))) {
dir = stat.direction;
break;
}
}
info.setLevers(dir != Direction.NONE);
if (dir != Direction.NONE) {
//handle this direction
info.setRailsTo(dir);
return; //don't do destination stuff
}
}
// Handle destination alternatively
if (info.isAction(SignActionType.MEMBER_ENTER, SignActionType.GROUP_ENTER) && (facing || !info.isWatchedDirectionsDefined())) {
PathNode node = PathNode.getOrCreate(info);
if (node != null) {
String destination = null;
IProperties prop = null;
if (doCart && info.hasMember()) {
prop = info.getMember().getProperties();
} else if (doTrain && info.hasGroup()) {
prop = info.getGroup().getProperties();
}
if (prop != null) {
destination = prop.getDestination();
prop.setLastPathNode(node.name);
}
if (!LogicUtil.nullOrEmpty(destination)) {
if (PathProvider.isProcessing()) {
double currentForce = info.getGroup().getAverageForce();
// Add an action to let the train wait until the node IS explored
info.getGroup().getActions().addAction(new GroupActionWaitPathFinding(info, node, destination));
info.getMember().getActions().addActionLaunch(info.getMember().getDirectionFrom(), 1.0, currentForce);
info.getGroup().stop();
} else {
// Switch the rails to the right direction
PathConnection conn = node.findConnection(destination);
if (conn != null) {
info.setRailsTo(conn.direction);
}
}
}
}
}
}
| public void execute(SignActionEvent info) {
boolean doCart = false;
boolean doTrain = false;
if (info.isAction(SignActionType.GROUP_ENTER, SignActionType.GROUP_UPDATE) && info.isTrainSign()) {
doTrain = true;
} else if (info.isAction(SignActionType.MEMBER_ENTER, SignActionType.MEMBER_UPDATE) && info.isCartSign()) {
doCart = true;
} else if (info.isAction(SignActionType.MEMBER_LEAVE) && info.isCartSign()) {
info.setLevers(false);
return;
} else if (info.isAction(SignActionType.GROUP_LEAVE) && info.isTrainSign()) {
info.setLevers(false);
return;
} else {
return;
}
if (!info.hasRailedMember()) {
return;
}
final boolean facing = info.isFacing();
if (facing) {
final BlockFace cartDirection = info.getCartDirection();
//find out what statements to parse
List<DirectionStatement> statements = new ArrayList<DirectionStatement>();
statements.add(new DirectionStatement(info.getLine(2), cartDirection, Direction.LEFT));
statements.add(new DirectionStatement(info.getLine(3), cartDirection, Direction.RIGHT));
//other signs below this sign we could parse?
for (Sign sign : info.findSignsBelow()) {
boolean valid = true;
for (String line : sign.getLines()) {
DirectionStatement stat = new DirectionStatement(line, cartDirection);
if (stat.direction == Direction.NONE) {
valid = false;
break;
} else {
statements.add(stat);
}
}
if (!valid) {
break;
}
}
Block signblock = info.getBlock();
while (MaterialUtil.ISSIGN.get(signblock = signblock.getRelative(BlockFace.DOWN))) {
Sign sign = BlockUtil.getSign(signblock);
if (sign == null) break;
boolean valid = true;
for (String line : sign.getLines()) {
DirectionStatement stat = new DirectionStatement(line, cartDirection);
if (stat.direction == Direction.NONE) {
valid = false;
break;
} else {
statements.add(stat);
}
}
if (!valid) break;
}
//parse all of the statements
//are we going to use a counter?
int maxcount = 0;
int currentcount = 0;
AtomicInteger signcounter = null;
for (DirectionStatement stat : statements) {
if (stat.hasNumber()) {
maxcount += stat.number;
if (signcounter == null) {
signcounter = getSwitchedTimes(info.getBlock());
if (info.isAction(SignActionType.MEMBER_ENTER, SignActionType.GROUP_ENTER)) {
currentcount = signcounter.getAndIncrement();
} else {
currentcount = signcounter.get();
}
}
}
}
if (signcounter != null && currentcount >= maxcount) {
signcounter.set(1);
currentcount = 0;
}
int counter = 0;
Direction dir = Direction.NONE;
for (DirectionStatement stat : statements) {
if ((stat.hasNumber() && (counter += stat.number) > currentcount)
|| (doCart && stat.has(info, info.getMember()))
|| (doTrain && stat.has(info, info.getGroup()))) {
dir = stat.direction;
break;
}
}
info.setLevers(dir != Direction.NONE);
if (dir != Direction.NONE && info.isPowered()) {
//handle this direction
info.setRailsTo(dir);
return; //don't do destination stuff
}
}
// Handle destination alternatively
if (info.isAction(SignActionType.MEMBER_ENTER, SignActionType.GROUP_ENTER) && (facing || !info.isWatchedDirectionsDefined())) {
PathNode node = PathNode.getOrCreate(info);
if (node != null) {
String destination = null;
IProperties prop = null;
if (doCart && info.hasMember()) {
prop = info.getMember().getProperties();
} else if (doTrain && info.hasGroup()) {
prop = info.getGroup().getProperties();
}
if (prop != null) {
destination = prop.getDestination();
prop.setLastPathNode(node.name);
}
if (!LogicUtil.nullOrEmpty(destination)) {
if (PathProvider.isProcessing()) {
double currentForce = info.getGroup().getAverageForce();
// Add an action to let the train wait until the node IS explored
info.getGroup().getActions().addAction(new GroupActionWaitPathFinding(info, node, destination));
info.getMember().getActions().addActionLaunch(info.getMember().getDirectionFrom(), 1.0, currentForce);
info.getGroup().stop();
} else {
// Switch the rails to the right direction
PathConnection conn = node.findConnection(destination);
if (conn != null) {
info.setRailsTo(conn.direction);
}
}
}
}
}
}
|
diff --git a/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSObject.java b/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSObject.java
index aa3b3a0d..16840449 100644
--- a/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSObject.java
+++ b/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSObject.java
@@ -1,71 +1,76 @@
/*
* Copyright (c) 2004-2009 XMLVM --- An XML-based Programming Language
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 675 Mass
* Ave, Cambridge, MA 02139, USA.
*
* For more information, visit the XMLVM Home Page at http://www.xmlvm.org
*/
package org.xmlvm.iphone;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.swing.SwingUtilities;
public class NSObject {
public static void performSelectorOnMainThread(final Object target, final String method,
final Object arg, boolean waitUntilDone) {
Runnable runnable = new Runnable() {
@Override
public void run() {
Class<?>[] paramTypes = { Object.class };
Object[] params = { arg };
Class<?> targetClass = target.getClass();
Method m = null;
try {
m = targetClass.getMethod(method, paramTypes);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
try {
m.invoke(target, params);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
};
try {
- if (waitUntilDone) {
- SwingUtilities.invokeAndWait(runnable);
+ if (SwingUtilities.isEventDispatchThread()) {
+ // TODO should run this runnable in a thread if waitUntilDone == false
+ runnable.run();
} else {
- SwingUtilities.invokeLater(runnable);
+ if (waitUntilDone) {
+ SwingUtilities.invokeAndWait(runnable);
+ } else {
+ SwingUtilities.invokeLater(runnable);
+ }
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
| false | true | public static void performSelectorOnMainThread(final Object target, final String method,
final Object arg, boolean waitUntilDone) {
Runnable runnable = new Runnable() {
@Override
public void run() {
Class<?>[] paramTypes = { Object.class };
Object[] params = { arg };
Class<?> targetClass = target.getClass();
Method m = null;
try {
m = targetClass.getMethod(method, paramTypes);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
try {
m.invoke(target, params);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
};
try {
if (waitUntilDone) {
SwingUtilities.invokeAndWait(runnable);
} else {
SwingUtilities.invokeLater(runnable);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
| public static void performSelectorOnMainThread(final Object target, final String method,
final Object arg, boolean waitUntilDone) {
Runnable runnable = new Runnable() {
@Override
public void run() {
Class<?>[] paramTypes = { Object.class };
Object[] params = { arg };
Class<?> targetClass = target.getClass();
Method m = null;
try {
m = targetClass.getMethod(method, paramTypes);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
try {
m.invoke(target, params);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
};
try {
if (SwingUtilities.isEventDispatchThread()) {
// TODO should run this runnable in a thread if waitUntilDone == false
runnable.run();
} else {
if (waitUntilDone) {
SwingUtilities.invokeAndWait(runnable);
} else {
SwingUtilities.invokeLater(runnable);
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/src/io/indy/beepboard/gfx/GLCursor.java b/src/io/indy/beepboard/gfx/GLCursor.java
index 6c57610..3f8e97f 100644
--- a/src/io/indy/beepboard/gfx/GLCursor.java
+++ b/src/io/indy/beepboard/gfx/GLCursor.java
@@ -1,111 +1,111 @@
package io.indy.beepboard.gfx;
import io.indy.beepboard.logic.Cursor;
import io.indy.beepboard.logic.Grid;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
public class GLCursor
{
private static final String TAG = "GLCursor";
private GLRenderer glRenderer;
private Cursor logicalCursor;
private FloatBuffer vertexBuffer;
public GLCursor(GLRenderer g)
{
glRenderer = g;
}
public void setLogicalCursor(Cursor g)
{
logicalCursor = g;
}
public void setup(GL10 gl, float width, float height, float fov)
{
logicalCursor.dimensionChanged(width, height);
vertexBuffer = asVertexBuffer(generateCursorVertices());
}
public void draw(GL10 gl)
{
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glColor4f(0f, 1f, 0f, 0.9f);
gl.glNormal3f(0f, 0f, 1f);
gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
}
private float[] generateCursorVertices()
{
float planeHeight = glRenderer.getPlaneHeight();
float planeWidth = glRenderer.getPlaneWidth();
float planeMaxSize = glRenderer.getPlaneMaxSize();
float planeDistance = glRenderer.getPlaneDistance();
Grid logicalGrid = logicalCursor.getGrid();
int gridWidth = logicalGrid.getGridWidth();
float cursorWidth = planeWidth / (float)gridWidth;
float xOffset = -(planeMaxSize / 2f);
float yOffset = -(planeMaxSize / 2f);;
float xOrigin, yOrigin, zOrigin;
int i, j, tBase;
int tileNumCorners = 4;
int tileDimensions = 3;
float[] vertices;
vertices = new float[tileNumCorners * tileDimensions];
xOrigin = xOffset;
yOrigin = yOffset;
zOrigin = -planeDistance - 5f;
vertices[ 0] = xOrigin;
vertices[ 1] = yOrigin;
vertices[ 2] = zOrigin;
Log.d(TAG, "cursorWidth: "+cursorWidth);
vertices[ 3] = xOrigin + cursorWidth;
vertices[ 4] = yOrigin;
vertices[ 5] = zOrigin;
vertices[ 6] = xOrigin;
- vertices[ 7] = yOrigin + planeHeight;
+ vertices[ 7] = yOrigin + planeMaxSize;
vertices[ 8] = zOrigin;
vertices[ 9] = xOrigin + cursorWidth;
- vertices[10] = yOrigin + planeHeight;
+ vertices[10] = yOrigin + planeMaxSize;
vertices[11] = zOrigin;
return vertices;
}
private FloatBuffer asVertexBuffer(float[] vertices)
{
FloatBuffer vb;
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder());
vb = vbb.asFloatBuffer();
vb.put(vertices);
vb.position(0);
return vb;
}
}
| false | true | private float[] generateCursorVertices()
{
float planeHeight = glRenderer.getPlaneHeight();
float planeWidth = glRenderer.getPlaneWidth();
float planeMaxSize = glRenderer.getPlaneMaxSize();
float planeDistance = glRenderer.getPlaneDistance();
Grid logicalGrid = logicalCursor.getGrid();
int gridWidth = logicalGrid.getGridWidth();
float cursorWidth = planeWidth / (float)gridWidth;
float xOffset = -(planeMaxSize / 2f);
float yOffset = -(planeMaxSize / 2f);;
float xOrigin, yOrigin, zOrigin;
int i, j, tBase;
int tileNumCorners = 4;
int tileDimensions = 3;
float[] vertices;
vertices = new float[tileNumCorners * tileDimensions];
xOrigin = xOffset;
yOrigin = yOffset;
zOrigin = -planeDistance - 5f;
vertices[ 0] = xOrigin;
vertices[ 1] = yOrigin;
vertices[ 2] = zOrigin;
Log.d(TAG, "cursorWidth: "+cursorWidth);
vertices[ 3] = xOrigin + cursorWidth;
vertices[ 4] = yOrigin;
vertices[ 5] = zOrigin;
vertices[ 6] = xOrigin;
vertices[ 7] = yOrigin + planeHeight;
vertices[ 8] = zOrigin;
vertices[ 9] = xOrigin + cursorWidth;
vertices[10] = yOrigin + planeHeight;
vertices[11] = zOrigin;
return vertices;
}
| private float[] generateCursorVertices()
{
float planeHeight = glRenderer.getPlaneHeight();
float planeWidth = glRenderer.getPlaneWidth();
float planeMaxSize = glRenderer.getPlaneMaxSize();
float planeDistance = glRenderer.getPlaneDistance();
Grid logicalGrid = logicalCursor.getGrid();
int gridWidth = logicalGrid.getGridWidth();
float cursorWidth = planeWidth / (float)gridWidth;
float xOffset = -(planeMaxSize / 2f);
float yOffset = -(planeMaxSize / 2f);;
float xOrigin, yOrigin, zOrigin;
int i, j, tBase;
int tileNumCorners = 4;
int tileDimensions = 3;
float[] vertices;
vertices = new float[tileNumCorners * tileDimensions];
xOrigin = xOffset;
yOrigin = yOffset;
zOrigin = -planeDistance - 5f;
vertices[ 0] = xOrigin;
vertices[ 1] = yOrigin;
vertices[ 2] = zOrigin;
Log.d(TAG, "cursorWidth: "+cursorWidth);
vertices[ 3] = xOrigin + cursorWidth;
vertices[ 4] = yOrigin;
vertices[ 5] = zOrigin;
vertices[ 6] = xOrigin;
vertices[ 7] = yOrigin + planeMaxSize;
vertices[ 8] = zOrigin;
vertices[ 9] = xOrigin + cursorWidth;
vertices[10] = yOrigin + planeMaxSize;
vertices[11] = zOrigin;
return vertices;
}
|
diff --git a/errai-bus/src/main/java/org/jboss/errai/bus/server/servlet/JettyContinuationsServlet.java b/errai-bus/src/main/java/org/jboss/errai/bus/server/servlet/JettyContinuationsServlet.java
index c6d0ceb14..f1ba154ef 100644
--- a/errai-bus/src/main/java/org/jboss/errai/bus/server/servlet/JettyContinuationsServlet.java
+++ b/errai-bus/src/main/java/org/jboss/errai/bus/server/servlet/JettyContinuationsServlet.java
@@ -1,176 +1,176 @@
/*
* Copyright 2010 JBoss, a divison 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.servlet;
import com.google.inject.Singleton;
import org.jboss.errai.bus.client.framework.ClientMessageBus;
import org.jboss.errai.bus.client.framework.MarshalledMessage;
import org.jboss.errai.bus.server.api.MessageQueue;
import org.jboss.errai.bus.server.api.QueueActivationCallback;
import org.jboss.errai.bus.server.api.QueueSession;
import org.mortbay.jetty.RetryRequest;
import org.mortbay.util.ajax.Continuation;
import org.mortbay.util.ajax.ContinuationSupport;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import static org.jboss.errai.bus.server.io.MessageFactory.createCommandMessage;
/**
* The <tt>JettyContinuationsServlet</tt> provides the HTTP-protocol gateway between the server bus and the client buses,
* using Jetty Continuations.
*/
@Singleton
public class JettyContinuationsServlet extends AbstractErraiServlet {
/**
* Called by the server (via the <tt>service</tt> method) to allow a servlet to handle a GET request by supplying
* a response
*
* @param httpServletRequest - object that contains the request the client has made of the servlet
* @param httpServletResponse - object that contains the response the servlet sends to the client
* @throws IOException - if an input or output error is detected when the servlet handles the GET request
* @throws ServletException - if the request for the GET could not be handled
*/
@Override
protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
pollForMessages(sessionProvider.getSession(httpServletRequest.getSession(),
httpServletRequest.getHeader(ClientMessageBus.REMOTE_QUEUE_ID_HEADER)),
httpServletRequest, httpServletResponse, true);
}
/**
* Called by the server (via the <code>service</code> method) to allow a servlet to handle a POST request, by
* sending the request
* xxxxxxx
*
* @param httpServletRequest - object that contains the request the client has made of the servlet
* @param httpServletResponse - object that contains the response the servlet sends to the client
* @throws IOException - if an input or output error is detected when the servlet handles the request
* @throws ServletException - if the request for the POST could not be handled
*/
@Override
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
final QueueSession session = sessionProvider.getSession(httpServletRequest.getSession(),
httpServletRequest.getHeader(ClientMessageBus.REMOTE_QUEUE_ID_HEADER));
service.store(createCommandMessage(session, httpServletRequest.getInputStream()));
pollQueue(service.getBus().getQueue(session), httpServletResponse.getOutputStream(), httpServletResponse);
}
private void pollForMessages(QueueSession session, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, boolean wait) throws IOException {
httpServletResponse.setHeader("Content-Encoding", "gzip");
final GZIPOutputStream stream = new GZIPOutputStream(httpServletResponse.getOutputStream());
try {
final MessageQueue queue = service.getBus().getQueue(session);
if (queue == null) {
- switch (getConnectionPhase(request)) {
+ switch (getConnectionPhase(httpServletRequest)) {
case CONNECTING:
case DISCONNECTING:
return;
}
sendDisconnectWithReason(httpServletResponse.getOutputStream(),
"There is no queue associated with this session.");
return;
}
synchronized (queue) {
if (wait) {
final Continuation cont = ContinuationSupport.getContinuation(httpServletRequest, queue);
if (!queue.messagesWaiting()) {
queue.setActivationCallback(new QueueActivationCallback() {
public void activate(MessageQueue queue) {
queue.setActivationCallback(null);
cont.resume();
}
});
if (!queue.messagesWaiting()) {
cont.suspend(45 * 1000);
}
} else {
queue.setActivationCallback(null);
}
}
pollQueue(queue, stream, httpServletResponse);
}
} catch (RetryRequest r) {
/**
* This *must* be caught and re-thrown to work property with Jetty.
*/
throw r;
} catch (final Throwable t) {
t.printStackTrace();
httpServletResponse.setHeader("Cache-Control", "no-cache");
httpServletResponse.addHeader("Payload-Size", "1");
httpServletResponse.setContentType("application/json");
stream.write('[');
writeToOutputStream(stream, new MarshalledMessage() {
public String getSubject() {
return "ClientBusErrors";
}
public Object getMessage() {
StringBuilder b = new StringBuilder("{Error" +
"Message:\"").append(t.getMessage()).append("\",AdditionalDetails:\"");
for (StackTraceElement e : t.getStackTrace()) {
b.append(e.toString()).append("<br/>");
}
return b.append("\"}").toString();
}
});
stream.write(']');
} finally {
stream.close();
}
}
private static void pollQueue(MessageQueue queue, OutputStream stream,
HttpServletResponse httpServletResponse) throws IOException {
if (queue == null) return;
queue.heartBeat();
httpServletResponse.setHeader("Cache-Control", "no-cache");
httpServletResponse.setContentType("application/json");
queue.poll(false, stream);
}
}
| true | true | private void pollForMessages(QueueSession session, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, boolean wait) throws IOException {
httpServletResponse.setHeader("Content-Encoding", "gzip");
final GZIPOutputStream stream = new GZIPOutputStream(httpServletResponse.getOutputStream());
try {
final MessageQueue queue = service.getBus().getQueue(session);
if (queue == null) {
switch (getConnectionPhase(request)) {
case CONNECTING:
case DISCONNECTING:
return;
}
sendDisconnectWithReason(httpServletResponse.getOutputStream(),
"There is no queue associated with this session.");
return;
}
synchronized (queue) {
if (wait) {
final Continuation cont = ContinuationSupport.getContinuation(httpServletRequest, queue);
if (!queue.messagesWaiting()) {
queue.setActivationCallback(new QueueActivationCallback() {
public void activate(MessageQueue queue) {
queue.setActivationCallback(null);
cont.resume();
}
});
if (!queue.messagesWaiting()) {
cont.suspend(45 * 1000);
}
} else {
queue.setActivationCallback(null);
}
}
pollQueue(queue, stream, httpServletResponse);
}
} catch (RetryRequest r) {
/**
* This *must* be caught and re-thrown to work property with Jetty.
*/
throw r;
} catch (final Throwable t) {
t.printStackTrace();
httpServletResponse.setHeader("Cache-Control", "no-cache");
httpServletResponse.addHeader("Payload-Size", "1");
httpServletResponse.setContentType("application/json");
stream.write('[');
writeToOutputStream(stream, new MarshalledMessage() {
public String getSubject() {
return "ClientBusErrors";
}
public Object getMessage() {
StringBuilder b = new StringBuilder("{Error" +
"Message:\"").append(t.getMessage()).append("\",AdditionalDetails:\"");
for (StackTraceElement e : t.getStackTrace()) {
b.append(e.toString()).append("<br/>");
}
return b.append("\"}").toString();
}
});
stream.write(']');
} finally {
stream.close();
}
}
| private void pollForMessages(QueueSession session, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, boolean wait) throws IOException {
httpServletResponse.setHeader("Content-Encoding", "gzip");
final GZIPOutputStream stream = new GZIPOutputStream(httpServletResponse.getOutputStream());
try {
final MessageQueue queue = service.getBus().getQueue(session);
if (queue == null) {
switch (getConnectionPhase(httpServletRequest)) {
case CONNECTING:
case DISCONNECTING:
return;
}
sendDisconnectWithReason(httpServletResponse.getOutputStream(),
"There is no queue associated with this session.");
return;
}
synchronized (queue) {
if (wait) {
final Continuation cont = ContinuationSupport.getContinuation(httpServletRequest, queue);
if (!queue.messagesWaiting()) {
queue.setActivationCallback(new QueueActivationCallback() {
public void activate(MessageQueue queue) {
queue.setActivationCallback(null);
cont.resume();
}
});
if (!queue.messagesWaiting()) {
cont.suspend(45 * 1000);
}
} else {
queue.setActivationCallback(null);
}
}
pollQueue(queue, stream, httpServletResponse);
}
} catch (RetryRequest r) {
/**
* This *must* be caught and re-thrown to work property with Jetty.
*/
throw r;
} catch (final Throwable t) {
t.printStackTrace();
httpServletResponse.setHeader("Cache-Control", "no-cache");
httpServletResponse.addHeader("Payload-Size", "1");
httpServletResponse.setContentType("application/json");
stream.write('[');
writeToOutputStream(stream, new MarshalledMessage() {
public String getSubject() {
return "ClientBusErrors";
}
public Object getMessage() {
StringBuilder b = new StringBuilder("{Error" +
"Message:\"").append(t.getMessage()).append("\",AdditionalDetails:\"");
for (StackTraceElement e : t.getStackTrace()) {
b.append(e.toString()).append("<br/>");
}
return b.append("\"}").toString();
}
});
stream.write(']');
} finally {
stream.close();
}
}
|
diff --git a/xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-api/src/test/java/org/xwiki/extension/internal/DefaultExtensionLicenseManagerTest.java b/xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-api/src/test/java/org/xwiki/extension/internal/DefaultExtensionLicenseManagerTest.java
index 1baa9ae8e..5e41f9d4b 100644
--- a/xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-api/src/test/java/org/xwiki/extension/internal/DefaultExtensionLicenseManagerTest.java
+++ b/xwiki-commons-core/xwiki-commons-extension/xwiki-platform-extension-api/src/test/java/org/xwiki/extension/internal/DefaultExtensionLicenseManagerTest.java
@@ -1,70 +1,70 @@
/*
* 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.extension.internal;
import java.io.IOException;
import java.util.List;
import junit.framework.Assert;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.xwiki.extension.ExtensionLicense;
import org.xwiki.extension.ExtensionLicenseManager;
import org.xwiki.test.AbstractComponentTestCase;
public class DefaultExtensionLicenseManagerTest extends AbstractComponentTestCase
{
private ExtensionLicenseManager licenseManager;
@Override
public void setUp() throws Exception
{
super.setUp();
this.licenseManager = getComponentManager().lookup(ExtensionLicenseManager.class);
}
@Test
public void testGetLicenses()
{
Assert.assertTrue(this.licenseManager.getLicenses().size() > 0);
}
@Test
public void testGetLicense() throws IOException
{
ExtensionLicense license = this.licenseManager.getLicense("Apache License 2.0");
List<String> content =
IOUtils.readLines(getClass().getResourceAsStream("/extension/licenses/Apache License 2.0.txt"));
- content = content.subList(1, content.size());
+ content = content.subList(2, content.size());
Assert.assertNotNull(license);
Assert.assertEquals("Apache License 2.0", license.getName());
Assert.assertEquals(content, license.getContent());
license = this.licenseManager.getLicense("ASL");
Assert.assertNotNull(license);
Assert.assertEquals("Apache License 2.0", license.getName());
Assert.assertEquals(content, license.getContent());
}
}
| true | true | public void testGetLicense() throws IOException
{
ExtensionLicense license = this.licenseManager.getLicense("Apache License 2.0");
List<String> content =
IOUtils.readLines(getClass().getResourceAsStream("/extension/licenses/Apache License 2.0.txt"));
content = content.subList(1, content.size());
Assert.assertNotNull(license);
Assert.assertEquals("Apache License 2.0", license.getName());
Assert.assertEquals(content, license.getContent());
license = this.licenseManager.getLicense("ASL");
Assert.assertNotNull(license);
Assert.assertEquals("Apache License 2.0", license.getName());
Assert.assertEquals(content, license.getContent());
}
| public void testGetLicense() throws IOException
{
ExtensionLicense license = this.licenseManager.getLicense("Apache License 2.0");
List<String> content =
IOUtils.readLines(getClass().getResourceAsStream("/extension/licenses/Apache License 2.0.txt"));
content = content.subList(2, content.size());
Assert.assertNotNull(license);
Assert.assertEquals("Apache License 2.0", license.getName());
Assert.assertEquals(content, license.getContent());
license = this.licenseManager.getLicense("ASL");
Assert.assertNotNull(license);
Assert.assertEquals("Apache License 2.0", license.getName());
Assert.assertEquals(content, license.getContent());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.